Hello Friends, This is my first tutorial post.
Today I'll explain you how to retrieve JSON response via Ajax
call.
First we build a PHP script to send response in JSON format, then
we will gather this response from an Ajax call through jQuery script.
Let’s first create a PHP script
Create a PHP script, I’ll name it as “json_response.php”
And add following code in it
json_response.php
<?php
//set header for JSON response
//set header for JSON response
header("Content-Type: application/json");
//render array in JSON format
//render array in JSON format
echo json_encode(array('status' => 200, 'message'
=> 'Response from PHP script in JSON format.'));
This is a basic example to send JSON response.
PHP script will send response with status code and
message.
Now create a HTML file to fetch JSON response and add
it in header tag.
Create a HTML file, I’ll name it as “json_response.html”
And add following code.
json_response.html
json_response.html
<html>
<head>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script type="text/javascript">
$('document').ready(function() {
//create ajax call to fetch json response
$.ajax({ url: 'json_header.php',
type: 'GET',
dataType: 'JSON', // it is necessary to get JSON response
success: function(response) {
// if reponse status is
success
if (response.status == 200) {
// add message to header tag
$('#message').html(response.message);
}
}
});
});
</script>
</head>
<body>
<h1
id="message"></h1>
</body>
</html>
Note: It is very important to add ajax request parameter dataType: 'JSON' to fetch response in JSON format.
After running HTML file in browser you see the header
tag has message as
“Response from PHP script in JSON format.”
Comments
Post a Comment