1

I have a PHP page that outputs some JSON. After the page loads, I would like to output the JSON using jQuery AJAX. However, nothing is happening. The alert() dialog isn't appearing and it doesn't work with the JavaScript console, either. What is wrong with my jQuery AJAX call?

<script type="text/javascript">
jQuery.ajax({ url: 'http://www.domain.com/page.php',
    dataType: 'json',
    success: function(data) {
        var obj = jQuery.parseJSON(data);
        alert(obj.json_array[0]);
        alert(obj.json_array[1]);
        alert(obj.json_array[2]);
    }
});
</script>

The PHP is:

<?php
$array = [
    'foo' => 'bar',
    'bar' => 'foo',
    'int' => 4
];

$json_array = json_encode($array);
echo $json_array;
?>

1 Answer 1

1

In PHP, you can have arrays where each element has a key and a value, but once you parse it in javascript, that becomes an object. So using [0], [1], or [2] is invalid. You must use foo, bar, or int. Also, when you echo a string, the name of the variable that holds the string is not saved in any way. The only thing saved (echoed) is, well, the string. In your example, echo $json_array; echoes {"foo":"bar","bar":"foo","int":4}, and when it is parsed, you get an object. So you don't need to say obj.json_array, you just say obj. So to fix your issue,

Replace

alert(obj.json_array[0]);
alert(obj.json_array[1]);
alert(obj.json_array[2]);

with

alert(obj.foo);
alert(obj.bar);
alert(obj.int);
Sign up to request clarification or add additional context in comments.

10 Comments

Hi Howzieky, I changed it to alert(obj.foo); but still, nothing is happening. No alert and it doesn't work in the JavaScript console either.
Can you put in console.log(obj) right after you set obj? What does it say?
I get: Uncaught ReferenceError: obj is not defined
You are certain this is after var obj = jQuery.parseJSON(data);? Try saying console.log(data) instead.
No problem, thanks for the update! Good luck with your project!
|

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.