开发者

Posting javascript to a database

I am trying to get a javascript variable into my sql server database using ajax and php and jque开发者_JAVA技巧ry. Does anybody know how i can do this?


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);
?>


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"].


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);
?>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜