-2

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;
?>
0

2 Answers 2

1

[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);
8
  • using alert(me.imei) //imei is a attribute of the object , i get the output required, how can i print all the data's imei number. what condition should i use in my for loop ?? Commented Apr 29, 2014 at 8:48
  • me.imei for me contains an empty string {"0":"","imei":""} ...no numbers Commented Apr 29, 2014 at 8:52
  • can you post the php-file, maybe it doesn't produce the expected output? Commented Apr 29, 2014 at 8:55
  • when i send more than 1 object as ajax response, alert messages doesn't work anymore. Commented Apr 29, 2014 at 9:06
  • see my edited answer. Please note: you should change your db-password, because you've posted it, anybody will be able to access your DB now(removing the password from the post will not help much because the original post still may be inspected) Commented Apr 29, 2014 at 10:04
0

That is because your data is not getting parsed. Try the following code. Do you have a callback function?

 $.ajax({
          type:"GET",
          url:"http://hostname/list_devices.php",
          crossDomain:true,
          dataType:'jsonp',
          success: function jsondata(data)
               {
                var jsondata=JSON.parse(JSON.stringify(data));
                var datap=jsondata["Status"];
                     alert(datap);
               }

        });

    or try JSON.parse(JSON.stringify(ajax.response));
3
  • how can there be an alert when it's not getting parsed? Commented Apr 29, 2014 at 8:46
  • I had been through the same problem, it displays [Object object] but not the data. Commented Apr 29, 2014 at 8:53
  • @Deepika Not exactly my problem; a value is returned, e.g. 5, just the wrong value. Commented May 15, 2014 at 4:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.