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

1
  • 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. Commented Jun 7, 2011 at 3:40

2 Answers 2

5

Use the array access syntax:

alert(obj[42]);
2

You can use:

alert(obj['a']);

See this question for more info.

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.