I'm trying to use $.post to retrieve multiple data from MySQL. I can't seem to get this working. How do I retrieve multiple data using jquery-ajax from MySQL?

php

$e = $_POST['stu'];
$sq ="SELECT physics, chemistry, agriculture FROM subjects WHERE student = :student";
$stmt = $getdb->prepare($sq);
$stmt->execute(array(':student'=>"123456"));
$rslt = $stmt->fetchAll();

$sd=array();
foreach($rslt as $val){
     $sd[] = $val; 
}
echo json_encode($sd);

jq:

$.post('my.php',
    {
      stu:"test"
    },
    function(data){
       $.each(data,function(ab){
         alert(ab.physics+" || "+ab.chemistry+" || "+item.agriculture);
       });
});

EDIT

console.log(data);

enter image description here

share|improve this question
    
Retrieve multiple data means ? – Pratik C Joshi Jun 17 '15 at 17:51
1  
There is your problem, nothing is getting returned which means your PHP is not doing what you would expect. print_r($rslt) after the fetch to see what is there. If it is an array (as it should be) you can skip the $sd array forming and just echo json_encode($rslt) – Jay Blanchard Jun 17 '15 at 18:00
1  
Try console.log(data). Your array has now changed and you'll need to figure out how to parse it. – Jay Blanchard Jun 17 '15 at 18:07
1  
Hehe! You just learned how to parse your data! You could use $.each(data[0], function.... – Jay Blanchard Jun 17 '15 at 18:37
1  
Glad to help @Becky. In this case, no, you don't need an each. If you were returning results for multiple students it would be different. – Jay Blanchard Jun 17 '15 at 18:42

Lets say you want to return two arrays.
So from the PHP side:

echo json_encode(Array($first_array,$second_array), JSON_FORCE_OBJECT);

then of the js side:

function(data) {
      var my_obj = JSON.parse(data);
      var first_arr = my_obj[0];
      var second_arr = my_obj[1]; 
}
share|improve this answer

If you are trying to use that kind of sintax then I suggest to change php code to the following sintax

$e = $_POST['stu'];
$sq ="SELECT physics, chemistry, agriculture FROM subjects WHERE student = :student";
$stmt = $getdb->prepare($sq);
$stmt->execute(array(':student'=>"123456"));
$rslt = $stmt->fetchAll();

$sd=array();
foreach($rslt as $val){
  $sd[] = array("".$val.""=>$val); 
}
echo json_encode($sd);    Ho

And in jquery ajax I recommend the following

$.post('my.php',
{
  stu:"test"
},
function(data){
   var result = $.parseJSON(data);
   $.each(result,function(i, ab){
     console.log(ab.physics+" || "+ab.chemistry+" || "+item.agriculture);
   });
});

Hope this is helpful...

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.