-1

I make an ajax call to my server to retrieve some records and return them as a JSON object. Here is the code for the call

$(".reply").click(function (){

      $.ajax({
    url: "/ajax_up/",
    type: 'GET',
    dataType: "json",
    success: function (data) {
    sync_data=JSON.stringify(data)

    }

}); 

Am trying to use the returned data to construct grid, so when I pass the variable syncd_data which I have declared global in the Ajax call, It seems to be undefined.

$(document).ready(function(){
        var data = source_data;
  //other code
        ..........................
        ..........................

But when I do alert(sync_data) from within the ajax call as below:

$(".reply").click(function (){

          $.ajax({
        url: "/ajax_up/",
        type: 'GET',
        dataType: "json",
        success: function (data) {
        sync_data=JSON.stringify(data)

        }

    }); 

It shows the data correctly. I can I use this data outside the Ajax call? Any Help Insights or examples will be highly appreciated. Thanks

user3670066
  • 85
  • 1
  • 3
  • 8

2 Answers2

1

You need to make sure you are calling that function inside of the success callback of your ajax call:

success: function (data) {
    sync_data=JSON.stringify(data);
    doSomething(sync_data);    
    }

This is because AJAX is Asynchronous, you need to make sure your call is done and successful before proceeding to the next event. Even if the variable is declared to be global.

UPDATE:

    var sync_data;

    $(document).ready(function(){

    $.ajax({
            url: "/ajax_up/",
            type: 'GET',
            dataType: "json",
            success: function (data) {
                 sync_data=JSON.stringify(data);    
               }
         });    

     });

This way, you'll make sure sync_data is, technically, populated in document.ready upon returning from the AJAX request. You can now consume it anywhere.

Diana Nassar
  • 2,303
  • 14
  • 17
0

add var sync_data = "" out of your ajax call and before it. And after your ajax call, you can see it's data by alert(sync_data);

by adding a variable before ajax call make it can use out of ajax call

Janaka R Rajapaksha
  • 3,585
  • 1
  • 25
  • 28