15

In my front end JavaScript application, I make an ajax request to fetch data from the server. As soon as I get the data, I want to return that piece of information to the view.

var view_data;
$.ajax({
    url:"/getDataFromServer.json",
    //async: false,
    type: "POST",
    dataType: "json",
    success:function(response_data_json) {
        view_data = response_data_json.view_data;
        console.log(view_data); //Shows the correct piece of information
        return view_data; // Does not work. Returns empty data
    }
 });

 // return view_data; --> Keeping the return outside of the ajax call works but then I need to make my ajax call synchronous in order for this return clause to be executed after the ajax call fetches data.

How would I do this?

Vikrant
  • 4,920
  • 17
  • 48
  • 72
user3422637
  • 3,967
  • 17
  • 49
  • 72

3 Answers3

21

Instead of returning data from success: pass data to a function.

var view_data;
$.ajax({
    url:"/getDataFromServer.json",
    //async: false,
    type: "POST",
    dataType: "json",
    success:function(response_data_json) {
        view_data = response_data_json.view_data;
        console.log(view_data); //Shows the correct piece of information
        doWork(view_data); // Pass data to a function
    }
 });

function doWork(data)
{
    //perform work here
}
Vikrant
  • 4,920
  • 17
  • 48
  • 72
7

ajax is by nature asyc. The code doesn't wait for the response from your success callback, so the data isn't accessible outside of success unless passed.

You'd need to handle the data inside the success, try calling a separate method/function:

function handleResponse(data) {
    // do something with data
}

success:function(response_data_json) {
    handleResponse(response_data_json.view_data); 
}

here are the docs on jquery's ajax method

You could also just use an external success function rather then an annon inline that then calls the function anyway. it will still pass the data as a param

function handleResponse(data) {
  // do something
}

$.ajax({
    url:"/getDataFromServer.json",
    //async: false,
    type: "GET",
    dataType: "json",
    success:handleResponse
 });

UPDATE: as pointed out in the comments, you might be better using a http get request rather then a post. they both have advantages however get requests can be cached, so for retrieving data it might give a perf boost.

atmd
  • 7,430
  • 2
  • 33
  • 64
  • Am I incorrect in assuming that because he wants to fetch data from the server it should be a ```GET``` request, as opposed to a ```POST``` request? – Paul Fitzgerald Apr 22 '15 at 10:21
  • @PaulFitzgerald no necessarily, although in this case it appears so. If he was posting data and wanted to handle a fail/success message from the back end then a post make sense, but in this I think you're right, it should be a `get` – atmd Apr 22 '15 at 10:23
1

that's the best way to pass prams and get response

function get_table_data_helper(table, id){
    return $.ajax({
        url: DOCUMENT_ROOT + '/php/get_table_data.php',
        type: 'post',
        data: {table: table, id: id},
        async: false,
        success:function(add_clint_res){
            (jQuery.parseJSON(add_clint_res));
        }
    });
}
function get_table_data(table, id, column){
    return jQuery.parseJSON(get_table_data_helper(table, id).success(function (data) {  return jQuery.parseJSON(data);  })['responseText'])[column];

}

then do get your data like

get_table_data('city_table', '3', 'city_col')
fefooo
  • 51
  • 4