jQuery Ajax Example Using PHP

This tutorial help to create AJAX call with PHP and JavaScript. jQuery provide $.ajax() function used to get response from script through asynchronous/synchronous manner.

AJAX stands for Asynchronous JavaScript and XML, and it allows you to fetch content from the back-end server asynchronously, without a page refresh. 

It’s provide dynamic data loading using backend script. In other words , with help of ajax you can dynamically load partial page or portion of page. It will also help to submit form data server side and saved into database.

jQuery ajax function have a lot of properties but I am describing only few common properties.

url

– The target of the request url.

type

– The type of HTTP request either: "GET" (Default) or "POST".

async

– When we set asynchronous to TRUE then it will load data in background and this will allow you to run mutiple AJAX requests at the same time. If you set to FALSE the request will run and wait response from server,this is working only single threading process.

data

– data as a key value pair and send to target request script for process. example "{param1: 'value1'}".
dataType – Specify the type of data that is returned: "xml/html /json ".

success

– The function that is fired when the AJAX call has completed successfully.

error

– The function that is fired when the AJAX call encountered errors.

 

Source Code for jQuery AJAX Request Using PHP

that.getDetails = function(params) {
	alert(params['target']);
$.ajax({ 
         url: siteurl +params['url'], //request url
         data: {action : ‘test’},//data which you want send to server side
         type: 'post', //request type
         success: function(response) {
			 alert(response);//when ajax request success
                      $(params['target']).html(response);
                  },
         error:function (xhr, ajaxOptions, thrownError){
                    alert(xhr.status);//if ajax request failed
                    alert(thrownError);
                }    
				  
});

I have created a common method will take URL as parameter. This method ll send asynchronous request to the server.

The $ sign is used to refer to a jQuery object.

The url is the first parameter that will be called in the background to fetch content from the server side. 

The data hold the information that ll send to the server as a request payloads.

The type is http request method.

Leave a Reply

Your email address will not be published.