How to pass a variable from JavaScript to PHP using jQuery POST

I pass the sessionnum variable from the following Javascript function in the chat.php page:

 $(document).ready(function(){ timestamp = 0; updateMsg(); $("form#chatform").submit(function(){ $.post("backend.php",{ message: $("#msg").val(), name: author, action: "postmsg", time: timestamp, tablename1: sessionnum }, function(xml) { $("#msg").empty(); addMessages(xml); document.forms['chatform'].reset() fixScroll(); }); return false; }); }); 

To the following PHP function in backend.php:

 if(@$action == "postmsg") { mysql_query("INSERT INTO `$tablename1` (`user`,`msg`,`time`) VALUES ('$name','$message',".time().")",$dbconn); mysql_query("DELETE FROM `$tablename1` WHERE id <= ". (mysql_insert_id($dbconn)-$store_num),$dbconn); } $messages = mysql_query("SELECT user,msg FROM `$tablename1` WHERE time>$time ORDER BY id ASC LIMIT $display_num",$dbconn); 

It only works when I hard code a destination, such as $tablename1 = 100 in backend.php, although both the variable and its value are integers and the same values. This hack is unacceptable since I really have to pass the variable. Is there an error in my code?

This code is adapted from http://articles.sitepoint.com/article/ajax-jquery/3

Thanks for any help posting the variable using jQuery.

0
source share
2 answers

Try changing the POST variables to $_POST['variable_name'] . You use syntax that relies on global variables registered as variables. This is a feature that a) is not enabled by default, and b) poses a serious security risk when enabled. Thus, try changing the server-side code to:

 $action = $_POST['action']; $tablename1 = mysql_real_escape_string($_POST['tablename1']); $name = mysql_real_escape_string($_POST['name']); $message = mysql_real_escape_string($_POST['message']); if(@$action == "postmsg") { mysql_query("INSERT INTO `$tablename1` (`user`,`msg`,`time`) VALUES ('$name','$message',".time().")",$dbconn); mysql_query("DELETE FROM `$tablename1` WHERE id <= ". (mysql_insert_id($dbconn)-$store_num),$dbconn); } $messages = mysql_query("SELECT user,msg FROM `$tablename1` WHERE time>$time ORDER BY id ASC LIMIT $display_num",$dbconn); 

Note that to prevent some SQL injections, the variables that you use in your SQL queries (which the user can change) have been escaped using mysql_real_escape_string .

+2
source

It would seem that you rely on register_globals and refer to what would be a POST variable in PHP, instead of a reference to $ _ POST supgllobal , for example

 if ( $_POST['action'] == 'postmsg' ) { $name= mysql_real_escape_string( trim( $_POST['name'] ) ); // query using $name reference } 

As an aside, you should really rethink the possibility of using tablename in client code.

+1
source

All Articles