Tutorial :jQuery $.post() and MySQL problem



Question:

I'm using jQuery and $.post(). My code snippet is as follows for chat .php :

<?php  $msg=$_POST['msg'];  mysql_connect("localhost","root");  mysql_select_db("user");    mysql_query("INSERT INTO space (name,msg,serial) VALUES('Test','$msg','1')");  ?>  

and here is the code for my HTML file :

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  <html xmlns="http://www.w3.org/1999/xhtml">  <head>  <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />  <title>Shout!</title>    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>    <script type="text/javascript">    var status=1;  function action() {        if(status==1) {  $("#Layer1").hide("slow");  $("#Layer3").hide("fast");  $("#Layer4").hide("slow");  $("#close").attr("src","open.jpg");  status=0;    }     else if(status==0) {  status=1;  $("#Layer1").show("slow");  $("#Layer3").show("fast");  $("#Layer4").show("slow");  $("#close").attr("src","close.jpg");    }          }      function sendline() {      var msg=$("#msg").val();  $.post("chat.php",{msg:msg});  $("#msg").val(" ");  }    function typeyo() {  var text=$("#msg").val();    $("#Layer6").html(text);    }    </script>  <style type="text/css">  <!--  body {  background-color: #000000;  }  #Layer1 {  position:absolute;  width:200px;  height:115px;  z-index:1;  left: 199px;  top: 3px;  }  #Layer2 {  position:absolute;  width:69px;  height:64px;  z-index:2;  left: 570px;  top: 543px;  }  #Layer3 {  position:absolute;  width:131px;  height:91px;  z-index:3;  left: 487px;  top: 327px;  }  .style1 {  color: #FFFFFF;  font-family: "Segoe UI";  font-weight: bold;  }  #Layer4 {  position:absolute;  width:99px;  height:38px;  z-index:4;  left: 744px;  top: 485px;  }  #Layer5 {  position:absolute;  width:274px;  height:70px;  z-index:5;  left: 422px;  top: 62px;  }  #Layer6 {    width:638px;  height:356px;  z-index:5;  left: 352px;  top: 105px;        }  -->  </style></head>    <body>  <div class="style1" id="Layer3">  <textarea name="textarea" cols="30" rows="5" id="msg" ></textarea>  </div>  <div id="Layer1">Hello World!<img src="body.jpg" width="842" height="559" /></div>  <div id="Layer2"><img src="close.jpg" alt="Go Online/Offline" name="close" width="63" height="64" id="close" OnClick="action()"/></div>  <div id="Layer4">  <input type="button" value="Send Line" onclick="sendline()" /></div>  <div id="Layer6" style="color:white;font-family:Segoe UI;font-size:16px;width:500px; height:400px; overflow:auto;"></div>  </body>  </html>  

Now,there seems to be some problem posting the variable msg.Im using chat.php for $.post() on the HTML code that i've provided.

There seems to be a problem with sending the "msg" here . The chat.php file is fine since if we run it directly ,and not thorugh a $.post() call it works perfectly

Kindly Help! thank you!


Solution:1

Your msg variable that you try to send via POST is not initialized, add the following line at the beginning of your sendline function:

var msg = $("#msg").val();  

Note: you have a big/huge security issue inserting variables from POST in MySQL queries without prior treatment.


Solution:2

update: I suggest you use a javascript debugger, set a breakpoint at the beginning of function sendline() and step through the code. Which one to use depends on your browser(s).
Firefox -> e.g. Firebug
IE7 -> e.g. IE Developer Toolbar
IE8+ -> just press F12 to open the developer tools that are shipping with IE.


In addition to darma's answer: Your php script is prone to sql injections (intentional/malicious as well as unintentional ones). Either use prepared, parametrized statements or escape the data properly.

working example:

test.html:

<html>    <head><title>test.html</title>      <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script>      <script type="text/javascript">        function sendline() {          var msg = $('#msg').val();          // --- add some tests on msg here, e.g. msg=="" ---          $.post(            "chat.php",            {'msg':msg},            function(data, textStatus, req) { $('#reply').text('reply: ' + data); }          );        }      </script>    </head>    <body>      <div>        <textarea id="msg" rows="5" cols="30" name="textarea"></textarea>        <button onclick="sendline()">send line</button>      </div>      <div id="reply">&nbsp;</div>    </body>  </html>  

chat.php:

<?php  // --- add some tests on $_POST['msg'] here  // e.g. isset($_POST['msg']) and 0<strlen(trim($_POST['msg'])) ---    // you might want to use a slightly more sophisticated error handling than "or die(mysql_error())" ...but this is only an example.  $mysql = mysql_connect("localhost","localonly", "localonly") or die(mysql_error());  mysql_select_db("test", $mysql)  or die(mysql_error());  $msg=mysql_real_escape_string($_POST['msg'], $mysql);  $sql = "INSERT INTO space (name,msg,serial) VALUES('Test','$msg','1')";    // mysql_query($sql, $mysql) or die(mysql_error());  echo htmlspecialchars($sql);  

update2: You still don't have any error handling in your php script. Any of the mysql_* function can fail for various reasons; test the results. You need to "see" those errors, e.g. by writing them to a log file or something...
Try

<?php  define('LOGERRORS', 1);  function dbgLog($text) {    if (LOGERRORS) {      error_log(date('Y-m-d H:i:s : ').$text."\n", 3, 'error.log');    }  }    if ( !isset($_POST['msg']) ) {    dbgLog('script called without post parameter "msg"');    die();  }    $mysql = mysql_connect("localhost","root");  if ( !$mysql ) {    dbgLog('database connection failed: '.mysql_error());    die();  }    $result = mysql_select_db("user", $mysql);  if ( !$result ) {    dbgLog('database selection failed: '.mysql_error($mysql));    die();  }    $msg=mysql_real_escape_string($_POST['msg'], $mysql);  $sql = "INSERT INTO space (name,msg,serial) VALUES('Test','$msg','1')";  dbgLog('sending query: '.$sql);    $result = mysql_query($sql, $mysql);  if ( !$result ) {    dbgLog('query failed: '.mysql_error($mysql));    die();  }  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »