Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading from a PHP array in JQuery

Tags:

jquery

ajax

php

I seem to have trouble with getting data from a php array, I've looked at various examples of how to do this but I must be missing something because I can not get my code to work.

PHP method

function getLatestActivity(){
   $messages = array( 
      array('id'=>'01', 'value'=>'blah'),
      array('id'=>'02', 'value'=>'Oil'),
      array('id'=>'03', 'value'=>'Spark') 
   );

   echo json_encode($messages); 
   return;  
}

AJAX get functiom

function getLatestActivities(){
   $.ajax({
      type: "GET", url: "include/process.php", 
      data:{
         getLatestActivity: "true",
         toUser: "4",
         ignoreMessages:"1",
         dataType: "json"
      },
      success: function(data){
         $.each(data, function (i, elem) {
            alert(data.id);
         });              
      }
   });   
}

The alert prints out the message "undefined", any help would be appreciated thank you.

like image 944
mk_89 Avatar asked Jan 25 '12 13:01

mk_89


2 Answers

Try with - it's your single object now:

alert(elem.id);
like image 140
hsz Avatar answered Oct 14 '22 21:10

hsz


It is quite likely that data isn't what you're expecting. You aren't setting any headers in your response, and as hinted at by @Sudesh dataType isn't in the right place. The result is that data is most likely a string because jquery will not parse it as json.

You're also referring to the wrong variable. data.id cannot exist with the data you are returning from php. you would need elem.id or if you prefer data[i].id if data did contain what you're expecting. As an aside - using $.each instead of a for loop is relatively inefficient.

You can check if that's the case with code such as:

function getLatestActivities(){
   $.ajax({
      type: "GET", url: "include/process.php", 
      data:{
         getLatestActivity: "true",
         toUser: "4",
         ignoreMessages:"1",
         dataType: "json"
      },
      success: function(data){
         console.log(data); // <- look at the response
         $.each(data, function (i, elem) {
            // alert(data.id); don't debug using alerts
            console.log(elem);
         });              
      }
   });   
}

If data is a string (or simply, not what you're expecting) this should get you closer:

function getLatestActivity(){
    ....
    header('Content-type: application/json');
    echo json_encode($messages); 
}

with

function getLatestActivities(){
   $.ajax({
      url: "include/process.php", 
      data:{
         getLatestActivity: true,
         toUser: 4,
         ignoreMessages:1,
      },
      success: function(data){
         console.log(data);           
         ...              
      }
   });   
}

data should at least then be an array.

like image 34
AD7six Avatar answered Oct 14 '22 21:10

AD7six