AJAX Tutorial For Beginners Featured

Step by Step jQuery AJAX Tutorial for Beginners

Views: 776

What is AJAX?

AJAX stands for Asynchronous JavaScript and XML. AJAX is a new technique for creating faster, better, and more interactive web applications using JSON, XML, HTML, CSS, and Java Script, AJAX allows us to display new contents on our web pages without reloading pages and can be styled using CSS.

With AJAX reloads are limited hence the transfer of resources gets limited and elements or data loads faster in slower connections and also reduces load on server.

Requirements for AJAX

There are no such complicated requirements needed to use AJAX in our web pages, AJAX can run without any custom requirements, although browser needs to have support for JavaScript as AJAX is a JavaScript method. The modern browsers by default support JavaScript. In this tutorial we will learn using AJAX with jQuery so we will need:

  • jQuery added to our html page
  • Basic HTML knowledge
  • Some basic CSS skills for adding styles to our elements.
  • A text editor for editing and creating our codes.

What is jQuery?

jQuery is a JavaScript based library which allows us to add animations, events, AJAX, calculations and other JavaScript based functions with ease and lesser codes. In jQuery we initiate ajax with $.ajax() method. You can download jQuery from the following link and add it to your HTML.

jQuery Download

Read This Step by Step jQuery AJAX Tutorial for Beginners

The AJAX’s $.ajax() method Tutorial

The $.ajax() method is most preferred way to perform an AJAX request. It’s configurations contain all the instructions needed to perform an AJAX request, it also supports to get failure and success callbacks once request is done. The AJAX method mainly comes with two parts i.e. the URL which will be called using AJAX method and the settings for AJAX requests. Let us know them in detail.

URL: Specifies the URL which will be used by AJAX to perform request to.

  • accepts: A set of key/value pairs that map a given dataType to its MIME type, which gets sent in the Accept request header.
  • async: Specifies whether the request will be sent asynchronously or not, by default the method is set to send asynchronous requests, is a Boolean value.
  • beforeSend: Specifies a function to be called before the AJAX request is made.
  • cache: Specifies whether the browser should cache the requested pages or not. By default it is set to true and accepts Boolean value.
  • complete: This allows to call a function once the AJAX request is completed and success and error handlers have completed their actions.
  • contents: Is a string/regular-expression that determines how jQuery will parse the response, given its content type.
  • contentType: When a AJAX request is made this is the header sent to server, by default it is set to ‘application/x-www-form-urlencoded; charset=UTF-8’.
  • context: This is the context of all AJAX related callbacks.
  • converters: The converter converts the response dataType to another format. Default value is {“* text”: window.String, “text html”: true, “text json”: jQuery.parseJSON, “text xml”: jQuery.parseXML}
  • crossDomain: This allows cross domain AJAX request, by default it is set to false, if you want to make a cross domain request then set it to true.
  • data: Is the set of data you want to send through AJAX request and is an object as key value pair.
  • dataFilter: This is used to handle the raw response data from server. This accepts two arguments namely data and type.
  • dataType: defines the data type returned by server after request is made.
  • error: This method is used to call a function if AJAX request fails.
  • global: Specifies whether or not to trigger the global AJAX event handlers, by default the value is true and this field accepts Boolean values.
  • headers: This allows to send additional headers with the AJAX request, is an object and accepts key/value pairs.
  • ifModifies: This allows the request only to be successful if the server response have been changed from the previous request. By default the value is set to false.
  • isLocal: Allows the current environment to be recognized as local environment.
  • jsonp: If set true it overrides callback function in a JSONP request. For security concerns keep it to false in case of insecure sources for AJAX requests.
  • jsonpCallback: This specifies the callback function name for JSONP request.
  • mimeType: Specifies the mimetype and overrides XHR mime type.
  • username: Specifies the username which will be used with XMLHttpRequest in response to an HTTP access authentication request.
  • password: Specifies the password which will be used with XMLHttpRequest in response to an HTTP access authentication request.
  • processData: Specifies whether the data passed in data object will be processed and transformed into query string or not. By default it is true.
  • scriptCharset: It specifies the charset of the request, it is only applicable if “script” transport is used.
  • statusCode: Is an object which returns the HTTP response status codes and function to be called once request is complete.
  • success: Holds a function which will be called after request is successful.
  • timeout: Used to configure the timeout for request in milliseconds.
  • traditional: Defines the param serialization, if true it will serialize traditionally.
  • type: The method used for AJAX request, i.e. GET, POST, PUT.
  • url: The location URL where request will be sent.
  • xhr: A callback function for creating the XMLHttpRequest object.
  • xhrFields: An object of field Name and field Value pairs to set on the native XHR object.

So till now in this AJAX tutorial we are aware about all options available with the $.ajax() method up to this part of AJAX tutorial, now let us see how we can make a simple AJAX call to desired server page and get results to display.

AJAX jQuery Tutorial For Beginners

jQuery AJAX PHP Post Example

Let us start coding our simple HTML page for this jQuery AJAX tutorial, the page holds a select element and a result div to display results, I have added the AJAX jQuery script on the page header, let us see the page elements example.

<div class="holder">
<label for="select_value">Select a value</label>
<br>
<select id="select_value" name="select_value">
<option value="1">Car</option>
<option value="2">Bus</option>
<option value="3">Truck</option>
</select>
<br>
<br>
<h3>Result</h3>
<hr>
<div class="result">
</div>
</div>

Now as our HTML elements are ready, we will create our server script which will process the request made and return results, my server page is in PHP and I am using JSON data type for returning results as an object in this AJAX tutorial, here is the PHP code snippet.

<?php
if(isset($_POST['select_value']))
{
$value=$_POST['select_value'];
if($value==1)
{
$data['name']='Car';
$data['description']='A car is a road vehicle used to carry passengers. Cars usually have four wheels and an internal combustion engine. Another name is automobile from Greek "auto" and French "mobile". This name means "self-moving", as cars do not need horses or other external sources of power to move. Cars have been around since 1885';
}
elseif($value==2)
{
$data['name']='Bus';
$data['description']='A bus is a large wheeled vehicle meant to carry many different persons along with the driver. It is larger than a car. The name is a shortened version of omnibus, which means "for everyone" in Latin. Buses used to be called omnibuses, but people now simply call them "buses".';
}
else
{
$data['name']='Truck';
$data['description']='A truck (lorry in British English) is a vehicle used to transport goods. The word "truck" comes from the Greek word "trochos", which means "wheel". They usually use diesel fuel.';
}
echo json_encode($data);
}
?>

So in above PHP code we are checking the AJAX request values, if it is 1, 2 or 3 and forming the data array accordingly, then we are encoding the object in JSON format with use of PHP’s inbuilt function json_encode() and echoing it in JSON format. We can retrieve the JSON data with either HTML form POST request or an AJAX call, so let us make an AJAX call, I will describe the code in details.

$(document).ready(function(e) {
$('#select_value').on('change', function(e){
var value=$('#select_value').val();
seldata={
'select_value':value
};
$.ajax({
url:'script.php',
type:"POST",
data:seldata,
dataType:"JSON",
success: function(data)
{
name=data.name;
description=data.description;
console.log(data.name);
$('.result').html('<h2>'+name+'</h2>'+description);
},
error: function(){
alert('Something wrong happened');
}
});
});
});

Make sure you have added the script opening and closing tags, write the jQuery codes between those tags, also make sure that your page loads jQuery before loading the code snippet, so let me explain the code.

With the following code I am checking if the page is fully ready and loaded properly using jQuery’s inbuilt ready event handler.

$(document).ready(function(e)
{
});

Inside the ready handler’s function there is another function checking if the select element’s value is changed by the user with jQuery change event handler

$('#select_value').on('change', function(e){

});

Then we are retrieving the current value for select element and storing it in “value” variable and creating an element for passing it to server with name ”seldata”.

var value=$('#select_value').val();

seldata={

'select_value':value

};

Now we will make our AJAX call by loading the jQuery $.ajax() method. Inside the AJAX handler of jQuery we are setting up our desired parameters like URL of server page, data to be sent, type of request either GET or POST, the data type server will return and success and error functions.

The AJAX success function: Inside the success function we are passing all values retrieved from server as “data” variable, then we are displaying our retrieved result inside the div element with a class “result”.

success: function(data)
{
name=data.name;
description=data.description;
console.log(data.name);
$('.result').html('<h2>'+name+'</h2>'+description);
}

The AJAX error function: We are simply echoing an error message with error method of AJAX inside our error function.

error: function(){
alert('Something wrong happened');
}

And this is how we make an AJAX request to our server side pages and display results, if you have any queries or questions in this topic, let me know in comments below. Please check the sample files if you need to review them you can download.

sample

If you found this tutorial helpful then do share with your friends and in social media. Good day.

Comments: 0

Your email address will not be published. Required fields are marked with *