Thursday, August 28, 2014

Sample JQuery $.ajax() to get JSON

On this post, I will provide a knowledge share on how to use JQuery's $.ajax method to perform an HTTP asynchronous request. A front-end HTML page will pass an AJAX request to a back-end, which in return, returns a response in JSON format.

For this sample, I will use three basic files:

index.html
This will be the front-end page to make the AJAX request using JQuery $.ajax method.

jquery-1.11.1.min.js
This will contain all JQuery functionality to my JavaScript codes. Ypu may download the file on this link: http://jquery.com/download/

backend.php

I will be using PHP to handle the front-end request. This will accept the request from and returns an output in JSON format

A screen shot is shown below:

The index.html page will show a form with two input text boxes. The values entered in the input boxes will be submitted to the back-end, which in turn, will be concatenated. This may be a simple activity, but take note that the back end can do much more sophisticated actions.

The process button will trigger the AJAX call. The "result here" text will serve as the placeholder for the returned output.

The full code on the index.html page is as follows
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>jQuery-AJAX-JSON</title>
<style>
div#result{
 color:blue;
 width:
}
</style>
<script src="jquery-1.11.1.min.js"></script>
<script>


$(document).ready(function (){

 $("#process").click(function(){
  var val1 = $("input[name='val1']").val();
  var val2 = $("input[name='val2']").val();
  $.ajax({  
   url: 'backend.php',
   type: 'post',
   data: { value1: val1, value2: val2 },
   dataType: 'json',
   success: function(json) {
    alert('parameter1 = '+json.value1+'. parameter2 = '+json.value2);
    alert('combined = '+json.combined);
    $("#result").html(json.combined);
   },
   error: function(xhr, ajaxOptions, thrownError) {
    alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText + "\r\n" + "Err-01");
   }
   
  });
  /**/
 });
});

</script>
</head>

<body>

<form action="#" method="post">
value 1: <input type="text" name="val1" /><br />
value 2: <input type="text" name="val2" /><br />
<input id='process' type="button" name='submit' value='process' />
<div id='result' style="border:1px blue solid;width:500px;height:200px;margin:10px;">result here</div>
</body>
</html>

Now we will go over each part of the JQuery code...

The 'process' button serves as the trigger point of the request- meaning, once this is clicked, the AJAX request starts to process.

The 'process' button as an ID of 'process':


Once the button is clicked, the JQuery code below is triggered.

The first step the triggered code will do is get the values stored in the input text boxes:


The input boxes haves ID's have names of 'val1' and 'val2' respectively. The .val() on the selectors for the input boxes picks up the values entered as soon as the 'process' button is clicked. The values are stored to corresponding variables:

The JQuery $.ajax method is called with the following settings:
  • url
  • type
  • data
  • dataType
  • success
  • error


Let's go through each settings:

The url specifies the back-end page the request will be sent to. In this case, we will use PHP to handle the request:
The type specifies if we are submitting using post or get request. In this sample, I've used post.
The data contains the values to be sent on post request in key value pair format to the settings url, backend.php:
In the screen shot below, I entered values on the input text boxes as follows:
The backend.php will combine the values and output a response in JSON. Given the values in the input text entries, the response output will be:
The dataType specifies the returned format of the response output- this will be in JSON.
The success contains a function handler if the AJAX request went well. My sample code will generate alerts for returned JSON response output and display one response on the placeholder for 'result here'. 
Lastly, the error provides a handler in case the AJAX call did not went well:
That completes the sample code. Putting in all together, let's have a sample run:

We enter values on the input boxes and click the 'process' button. This will trigger the $.ajax call
The $.ajax call is successful and the output is displayed:
So there we have it, a sample $.ajax call to get JSON response.

Resources:

Got a question or have any web coding you'd like me to help you out? I'd be more than happy to assist you and blog about it!

Just drop me an email at jrundolor@gmamail.com and tell me more about it!

No comments:

Post a Comment