0

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 posible via Javascript or there are some other methods ?

var Val_Points = 0; /* Variable */
$('.btn').click(function() {
  Val_Points += 5; /* value +5 */
  /* Update individual SQL Data
  var UpdateSQL = dbConn.executeUpdate('UPDATE Usuarios SET Points="$Val_Points" WHERE Username="$_SESSION[username]"'); 
*/
  $('#exp_bar').val(Val_Points);
});
<?php
	session_start();
	require 'connect.php';
$username_session = $_SESSION['username']; /* "Robert" Session */
$query = "SELECT * FROM `Usuarios` WHERE usuario='$username_session'";
$result = mysqli_query($connection, $query);
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Points</p>
<progress id ="exp_bar" value="0" max="100"></progress><br>
<button class="btn">+1</button>

Also i was seeing a script that simplifly this https://hiddentao.github.io/squel/ Maybe could be more readable in scripting with this. Any help?

EDIT

I tried to do all of this with php via $_SESSION

<?php
session_start();
require 'connect.php';
$username_session = $_SESSION['username'];
$query = "SELECT * FROM `Usuarios` WHERE username='$username_session'";
$result = mysqli_query($connection, $query);

if(empty($_SESSION['Val_Points'])){

    $Val_Points_Session = $_SESSION['Val_Points'] = 0; 
}


 echo "<form action='' method='POST'>
   <progress id ='exp_bar' value='".$_SESSION['Val_Points']++."' max='100'></progress>
   <input class='btn' type='submit'  value='Increase val' /> 
 </form>";

 echo $_SESSION['Val_Points']; /* Show current variable */
$Update_SQL = "UPDATE Usuarios SET Points='$Val_Points_Session' WHERE username='$username_session'";

?>

But it doesn't update the table, the table keeps with the same value

Username Points
Robert 0

8
  • You are trying to execute php in your js? You have to make a call to the server (e.g. $.ajax ) and there the update can be done. I don't know why adding the php tag was refused... Commented May 21, 2015 at 1:00
  • It's possible from where i see some examples like this stackoverflow.com/questions/11232865/… but it didn't helped me also the php tag was added! Commented May 21, 2015 at 1:06
  • Ok with this library it seems to be possible to execute SQL from JS, I just can't imagine how this can be really safe, I prefer to have a layer in between, sorry can't help you with that only "traditional" way. Commented May 21, 2015 at 1:06
  • All i want to do is use a variable (Val_Points) from the javascript and update it into a query, i bet that there are another way to do this but i can't figure out. It's possible to create a variable going +5 from the HTML button with php and update it into a query? I'm new on this and i'm really confused. Commented May 21, 2015 at 1:12
  • Yes it is possible can give a template... and it is indeed very confusing at first: most important always remind yourself that JS is running on the client side and php on the server side (although you can add javascript to your php it won't be interpreted on the server). Commented May 21, 2015 at 1:18

2 Answers 2

3

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.

enter image description here

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.

enter image description here

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']
    }

?>
Sign up to request clarification or add additional context in comments.

1 Comment

Given my comments are no longer relevant, I'll be deleting them. I've also given this answer +1.
0

"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'] == ...) {
      ...
    }
  }
?>

1 Comment

@Criss you can also use .submit instead of .click to add a submit handler to a form instead of click to a button (and add the ajax command there) and make sure you return false so the form is not actually sent. You can refresh other values on the site like $('#counter-lbl').html('new content'); and don't need to reload the whole page. I would really create at least 2 php files (content + request handler) or it gets extremely confusing.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.