Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

i am not able 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 file: 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;?>
share|improve this question

2 Answers 2

up vote 0 down vote accepted

[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);
share|improve this answer
    
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 ?? –  Nida Zehra Apr 29 at 8:48
    
me.imei for me contains an empty string {"0":"","imei":""} ...no numbers –  Dr.Molle Apr 29 at 8:52
    
can you post the php-file, maybe it doesn't produce the expected output? –  Dr.Molle Apr 29 at 8:55
    
when i send more than 1 object as ajax response, alert messages doesn't work anymore. –  Nida Zehra Apr 29 at 9:06
    
i posted it.... –  Nida Zehra Apr 29 at 9:17

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));
share|improve this answer
    
how can there be an alert when it's not getting parsed? –  Dr.Molle Apr 29 at 8:46
    
I had been through the same problem, it displays [Object object] but not the data. –  Deepika Apr 29 at 8:53
    
@Deepika Not exactly my problem; a value is returned, e.g. 5, just the wrong value. –  khaverim May 15 at 4:39

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.