Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery JSON Problem

I want to populate form fields with values from a database immediately after the user enters a value in the #sid field. Here is my jQuery/HTML example:

<script src="jquery-1.3.1.min.js"></script>
<script type="text/JavaScript">
$(document).ready(function()
{
  $('#sid').bind("change", function(){
    $.getJSON("test.php?sid=" + $("#sid").val(), 
    function(data)
    {
      $.each(data.items, 
      function(i, item)
      {
        if (item.field == "saffil")
        {
              $("#saffil").val(item.value);
        }
        else if (item.field == "sfirst")
        {
              $("#sfirst").val(item.value);
        }
      });
      });
   });
});
</script>

Here is my processing script (test.php which gets called by the .getJSON method)

<?
require_once("db_pers.inc");

$ssql = "SELECT * FROM contacts_mview WHERE sempid = '".$_GET['sid']."'";

$rres = pg_query($hdb, $ssql);
pg_close($hdb);

$ares = pg_fetch_assoc($rres);

$json = array(array('field' =>  'saffil',
            'value' =>  $ares['saffil']),
          array('field' =>  'sfirst',
            'value' =>  $ares['sfirst']));

echo json_encode($json);
?>

According to firebug the GET param is passed just fine to test.php and the JSON object comes back just fine:

[{"field":"saffil","value":"Admin"},{"field":"sfirst","value":"Nicholas"}]

however nothing happens on the page and I get the following error message back:

G is undefined
init()()jquery-1....1.min.js (line 12)
(?)()()test.html (line 15)
I()jquery-1....1.min.js (line 19)
F()()jquery-1....1.min.js (line 19)
[Break on this error] (function(){var l=this,g,y=l.jQuery,p=l.....each(function(){o.dequeue(this,E)})}});

This is my first stab at ajax with jQuery so any input would be much appreciated!

Thanks,

  • Nicholas
like image 791
niczak Avatar asked Dec 14 '25 19:12

niczak


2 Answers

Nice little injection attack waiting to happen there ;)

Try changing

$.each(data.items,

to:

$.each(data,

Edit: to answer your comment, I like to name my fields the same as the data key:

<input type="text" name="saffil" value="" />
<input type="text" name="sfirst" value="" />

var data = {saffil:'foo', sfirst:'bar'};
$.each(data, function(key, value) {
   $('[name='+key+']').val(value)
})
like image 102
Crescent Fresh Avatar answered Dec 16 '25 09:12

Crescent Fresh


I agree with the previous repliers. That script is an SQL injection waiting to happen. You should probably use something like PDO with prepared statements or at least something like pg_escape_string.

like image 23
Lior Cohen Avatar answered Dec 16 '25 09:12

Lior Cohen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!