Nida Zehra Nida Zehra - 10 days ago 5
Ajax Question

Convert PHP JSON encoded array to JavaScript array in AJAX?

I am unable to convert the AJAX response into a JavaScript array. All I receive is

[object Object]
in my alert box.

var url = 'list_devices.php';
var modurl = url;
alert(modurl);
ajax.open("GET", modurl, true);
ajax.onreadystatechange = function () {
if (ajax.readyState == 4) {
if (ajax.status == 200) {
//var json = JSON.stringify(ajax.responseText);
var me = JSON.parse(ajax.response);
//var me=jQuery.parseJSON(responseData);
//alert(me);
alert(json);
//var uid=new Array();
//uid=me.split(",");
//$.mobile.navigate("#page1");
//$('#devices').empty();
//var temp=document.createElement('li');
//for (var i=0; i<uid.length; i++) {
//$('#devices').append('<li ><p>'+uid[i]+'</p></li>'); -->
//}
//$('#devices').append(temp);
}
}
}
ajax.send(null);
}


PHP:

(I am trying to fetch all the IMEI of the
user_id
stored in a session.)

<?php
header("content-type:text/javascript");
session_start();
$sql=new mysqli("hostname","user","pass","dbname");
if(!$sql):
echo "error connecting to database";
die();
else:
$i=0;
$temp=[];
$q="SELECT imei FROM tbl_user_device where user_id='".$_SESSION['user_id']."'";
$result=$sql->query($q);
while($output=$result->fetch_array()):
echo json_encode($output);
endwhile;
endif;
?>

Answer

[object Object] is the string-representation of an object , when you see this in the alert the parsing was successfull.

Use console.log(me); to see the contents of the object


<edit/>:

As it appears you want to return an array of results and iterate over this array to print the data.

Currently you return an object, you must populate an array with this object(or multiple objects when wanted):

php to return an array:

<?php
  //the correct MIME-type for json is application/json
  header("content-type:application/json");
  session_start();

  //use your data here
  $sql=new mysqli("hostname","user","pass","dbname");

  if(!$sql):
      echo "error connecting to database";
      die();
  else:

     $temp=[];
     //I've modified the query to return multiple rows
     //but it will work also with a single row
     $q="SELECT  imei,user_id FROM tbl_user_device";

     $result=$sql->query($q);

     //you better use fetch_assoc here 
     while($output=$result->fetch_assoc()):
        //populate the array with results
        $temp[]=$output;

    endwhile;
 endif;
 //print the json
 die(json_encode($temp));
?>

Iterating over the results:

    var url = 'list_devices.php';
    var modurl = url;

    ajax.open("GET", modurl, true);
    ajax.onreadystatechange = function() {
      if (ajax.readyState == 4) {
        if(ajax.status == 200) {
          var me= JSON.parse(ajax.response);
          //iterate over the array-items
          for (var i=0; i<me.length; i++) {
            var li=$('<li/>');
              //iterate over the properties 
              //of the current array-item
              for(var k in me[i]){
                li.append($('<p/>')
                            .append($('<strong/>').text(k+':'))
                            .append($('<code/>').text(me[i][k])));
              }
              $('#devices').append(li);
          }
        }
      }
    }

    ajax.send(null);