Monday 3 September 2018

Recover multiple data from MySQL using jquery ajax

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

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];
}

0 comments:

Post a Comment