-1

I am stuck on a arrays in jQuery. I am returning back from php an array In php file I am adding array like this in a loop:

$table_data[]= array("id"=>mysql_result($query,$i,"id"),"name"=>trim(mysql_result($query,$i,"name")));

at the end of php file :

echo json_encode($table_data);

On my jquery :

 $.ajax({
   type: "POST",
   url: "phpfilename.php",
   data: ({
     newtask: "grab"
   }),
   dataType: "json",
   success: function(data){
     alert("value - "+data.length);
   }
 });

(this returns correct record counts)

$.each(data, function(key, value) {
 alert( "The key is '" + key + "' and the value is '" + value + "'" );
});

(the above loop returns me : 0,1,2 as a key , Object as a value )

I need help with understanidn how to pass arrays from php to jquery and how to handle them . Maybe I am totally on wrong way.

2
  • 1
    What's the problem? You're getting the array and looping through it. What are you asking how to do? Commented May 22, 2012 at 12:05
  • 1
    You should read the MDN JavaScript Guide to learn the basics about arrays and objects in JavaScript. alert is the worse debug tool you could have chosen. The output is correct though, since you have an array of objects and the default string representation of an object is [object Object]. Commented May 22, 2012 at 12:05

1 Answer 1

1

To access any property of an object, the process is:

ObjectName.property 

or

ObjectName[''+ property +''];

read here

$.each(data, function(key, value) {

  // try

  console.log(value.id);
  console.log(value.name);

});
Sign up to request clarification or add additional context in comments.

3 Comments

that is it, great. thank you , I was searching it for hours. Thank you very much
you mean ObjectName["property"];
$.each(data, function(key, value) { // try console.log(value.id); console.log(value.name); }); this one was helpfull

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.