I\'m starting to learn some of SQL with javascript and i want to put my variable (\"Val_Points from javascript\") into a table (\"Usuarios\") of a user (ex : Robert). It\'s this
"Standard" approach
foo.php
is the site which contains a button and includes a script:
<button id="update-btn">update</button>
...
<script src="foo.js"></script>
foo.js
adds the on click handler:
$('#update-btn').click(function() {
$.ajax({
'url': 'fooHandler.php',
'method': 'POST',
'data': {'sid': ..., 'action': 'update', 'value': ...}
/* 'success': function(data) { ... } */
/* 'error': function ... */
});
});
fooHandler.php
handles requests to the server from the clients:
<?php
if (isset($_POST['sid'], $_POST['action'])) {
/* TODO check if valid session */
if ($_POST['action'] == 'update') {
/* check if the rest is in order */
if (isset($_POST['value'] and is_numeric($_POST['value'])) {
/* TODO execute query */
}
} elseif ($_POST['action'] == ...) {
...
}
}
?>
Is it possible to insert data with Javascript to an SQL database
Simple answer is no. Not just with Javascript.
For understanding this you need to know the difference between client-side
and server-side
.
Client-side
Operations that are performed by the client. The operations are made by the computer/software of the user. This also means the client can modify the data how ever he want.
Server-side
Operations that are performed by the server. The operations are made on an server and uses just the information that is send by the client. After the data is recived the client can not modify it.
Your database is on the server-side
its on your server. The client has no direct acces to this database, so you need to send the data from the client-side
to the server-side
. This can be done with javascript
.
So how to do this.
In your case you wanna combine Javascript
(client) with PHP
(server). Via PHP
we insert the data to your SQL
database.
Example
Javascript / Jquery(!)
We going to use $.ajax(). This is an function out of the jQuery framework and makes an request to your server.
$('.btn').click(function() {
var request = $.ajax({
url: "phpfile.php",
data: { label: "value" },
method: "POST"
});
request.done(function() {
// Do something after its done.
});
});
PHP
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// do your database stuff.
// the data you send from the client is in the $_POST array.
// for example $_POST['label']
}
?>