javascript - How to to return a value from Ajax call to server -


i make ajax call server retrieve records , return them json object. here code call

$(".reply").click(function (){        $.ajax({     url: "/ajax_up/",     type: 'get',     datatype: "json",     success: function (data) {     sync_data=json.stringify(data)      }  });  

am trying use returned data construct grid, when pass variable syncd_data have declared global in ajax call, seems undefined.

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

but when alert(sync_data) within ajax call below:

$(".reply").click(function (){            $.ajax({         url: "/ajax_up/",         type: 'get',         datatype: "json",         success: function (data) {         sync_data=json.stringify(data)          }      });  

it shows data correctly. can use data outside ajax call? insights or examples highly appreciated. thanks

you need make sure calling function inside of success callback of ajax call:

success: function (data) {     sync_data=json.stringify(data);     dosomething(sync_data);         } 

this because ajax asynchronous, need make sure call done , successful before proceeding next event. if variable declared 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 ajax request. can consume anywhere.


Comments

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

ios - Change Storyboard View using Seague -