how to return data from ajax call

In this post we are going to disscus and solve a problem that most of the web developer face while returning the data from a function having ajax call. The problem is first explained with the actual statement, then root cause is explained and finally the solution is provided.

Problem Statement

We want to return the response data from a function having ajax call but the data is not returned accurately.

Problem cause:

Normally when you make an ajax call the data is received and then you use that data. Now consider a case when we want to return this data via a function call. Here comes the actual problem, i.e. you can not return this data. This is because ajax is an asynchronus request. The return statement is called before the actual data is received in the response.

Solution

Lets consider an expample that we make an ajax call to the get-data.php file. The function name is getData. So we want to make a function call and return the data via ajax request. Here is the code:

   
//FUNCTION DEFINITION
//This is how you define a function if you want to make an ajax call and return the response

function getData(callback){

    $.ajax({
		
         type: "GET",
         url: "get-data.php",
         data: dataToSend,
         success: function(data){  
           
             callback(data);
		
          }
	  
    });
	
}

//FUNCTION CALL
//Here is how you call this function and get the data returned

   getData(function(returnedData){

       //use the return data (we show in alert)
       alert(returnedData);

   });

In example above there is a function definition in which on success of ajax call, the data is returned via callback(data). For getting this data we make a function call. The function call code portion is the way how you can receive the data sent by callback(data) If you follow the above procedure you will be able to return the data

Leave a Reply

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