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.
$.postand useJSON.parse(data)to get the json object. Also I would suggest separating the php and the html into different files. So you could have something likegetJson.phpthat sends the json and yourindex.phpthat just containshtmlwith the javascript to send the request.getJSON()know then what to read?).echo json_encode(...). When you use AJAX, the output of the script is read by the AJAX callback function, it's not displayed on the webpage (unless the callback function displays it).