Reputation: 153
First off let me say, I've never used JSON or AJAX before, but I think I understand the concept at least.
I'm only trying to pass some PHP values to a jquery function (located in an external .js file). I've tried everything I can possibly think of, and don't know what's going wrong here.
In index.php I have:
<?php
$data = array(1 => 'thisor', 2 => 'thatttt');
echo json_encode($data);
?>
..which obviously isn't the real data I'm wanting to pass, but it's just for testing. In my .js file I have the function:
$.getJSON("index.php", function(data){
alert('data loaded' + data);
})
.error(function() { alert("error"); });
and every time, it's throwing the error. However I've noticed if I use $.post with the same exact code following it, it doesn't throw an error anymore, and returns the data.
Also, is it necessary to 'echo' the json_encode? What if I don't want this information displayed on my webpage? Or.. I'm misunderstanding something here possibly.
Also x2, if it's worth noting, I read about 'header('Content-type: application/json');' that may need to go into the PHP file.. however when I did that, it no longer rendered the webpage in the browser, and instead just output the contents in plain text. Am I needing to do this somewhere else / make another external PHP file?
Apologies for any ridiculous questions, it really is my first day trying to learn this thing.
Upvotes: 0
Views: 2452
Reputation: 1071
It works fine for me. Are you sure that the ONLY thing output is the jon string? Is there anything else at all in the index.php file?
When using $.post, try changing your alert to:
alert('data loaded(' + JSON.stringify(data)+')');
and check that all you see is the json string.
Since you've said that the index.php file is also outputting other stuff, here is an example of what you COULD do (I'm not saying that this is good practice). So you could write your index.php file similar to this:
<?php
if(isset($_GET['ajax'])) {
$data = array(1 => 'thisor', 2 => 'thatttt');
echo json_encode($data);
exit;
}
?>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js">
</script>
<script type="text/javascript">
<!--
$.post("index.php?ajax", function(data){
alert('data loaded(' + JSON.stringify(data)+')');
})
.error(function() { alert("error"); });
// -->
</script>
Upvotes: 1