2

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)?

John R
  • 2,920
  • 13
  • 48
  • 62
  • 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 07 '11 at 03:40

2 Answers2

5

Use the array access syntax:

alert(obj[42]);
deceze
  • 510,633
  • 85
  • 743
  • 889
2

You can use:

alert(obj['a']);

See this question for more info.

Community
  • 1
  • 1
Matty K
  • 3,781
  • 2
  • 22
  • 19