chris
chris

Reputation: 65

Posting javascript to a database

I am trying to get a javascript variable into my sql server database using ajax and php and jquery. Does anybody know how i can do this?

Upvotes: 0

Views: 1128

Answers (3)

11101101b
11101101b

Reputation: 7779

You call Jquery's post method in your javaScript:
$.post("update.php", { name: "John Doe"}, function() {});

And then update.php contains something like this (Assuming MySQL):

<?php 
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("my_db", $con);

mysql_query("INSERT INTO Persons (Name)
VALUES ('$name')");

mysql_close($con);
?>

Upvotes: 0

Massenburger
Massenburger

Reputation: 51

JavaScript (and jQuery):

function postValues() {
    $.ajax({
        url: 'someurl.php',
        type: 'POST',
        data: ({ javascript_variable: $('#someid').val() })
    });
}

PHP (in a file named someurlphp, or whatever you want to call it, just make sure your jquery ajax call is calling the correct file)

<?php
    $sql = sprintf(
        'INSERT INTO sometable
         SET some_col = "%s"',
         mysql_real_escape_string($_REQUEST['javascript_variable']));
    mysql_query($sql);
?>

Upvotes: 1

James Allardice
James Allardice

Reputation: 165961

Using jQuery, it's very simple. Use the .post function:

$.post("somefile.php", { someVar: yourVariable }, function() {
    //Done!
});

I'm assuming that by "get a javascript variable into database" you mean the value of the variable.

In somefile.php you can access the variable with $_POST["someVar"].

Upvotes: 0

Related Questions