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 trying to get a php file setup to return the results of a MySQL database query from a jQuery AJAX call. The returned results will be an array. I have a very basic start where I am just getting some basic data back and forth to and from the php file, but am stuck with some basic syntax issues:

The PHP code:

$arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);  
echo json_encode($arr); 

The jQuery code:

$.post("dbFile.php", str, function(theResponse){
     alert('the response: ' + theResponse);
     var obj = $.parseJSON(theResponse);
     alert(obj.a);

I can print out obj.a, obj.b, obj.c... no problem. The problem is I will be incrementing a counter as I increment through the MySQL results. So, the array does not use letters, it uses numbers:

$arr[$i] = mysqlresults ... $i++;

So, in the JavaScript/jQuery I have an object (not an array). I can print out obj.a for example, but I can not print out obj.2 (for example). In other words, if I replace the letters with numbers in the php array, I don't know how to print them out in JavaScript/jQuery. Can I change the object that parseJSON returns into an array somehow (so that I can cycle through it)?

share|improve this question
1  
If you send the result with echo json_encode(array_values($arr)); it will be guaranteed to be an ordinary (continuously indexed) Javascript array. –  mario Jun 7 '11 at 3:40
add comment

2 Answers

up vote 1 down vote accepted

You can use:

alert(obj['a']);

See this question for more info.

share|improve this answer
add comment

Use the array access syntax:

alert(obj[42]);
share|improve this answer
add comment

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.