This question already has an answer here:
I want to send data from index.php
to the browser through AJAX. I want to encode it in JSON and to decode it to work on it. I am using jQuery.ajax()
. Can you point me to a tutorial?
</div>
Assuming your ajax call looks something like this
$.ajax({
....
.....
dataType: 'json', // required
success: function(data) { // data variable is where your json is stored
console.log(data); // view entire json object in firebug or other console
alert(data.name); // access value of array key called name
}
});
I recommend placing a console.log
call in the success function to see what the json object looks like.
In your index.php put this jquery code
$.post("data_provider.php",{'your_param': param_value},
function(data){
var jsonObj = JSON.parse(data);
//use your data here
jsonObj.id;
jsonObj.name;
});
In your data_provider.php, get your data from DB for example and encode them using json_encode function. For example :
$your_data = array('id' => $id, 'name' => $name );
echo json_encode ($your_data);
In ajax call you can use get or post according to your needs.