callback function and global variable in jquery ajax call -
i using callback option value outside success block(cross domain call). getting value inside callback function, not outside. please see following code. if value available inside callback function, whats difference in writing code outside success block.
var globalvar ; function callbackclick() { var jsondata = { "name": "alex" }; test("http://mydomain:84/authservice.svc/testasyncget", jsondata, callback); } var callback = function (data, textstatus, xhr) { globalvar = data; alert(data + "\t" + textstatus); //here getting data } var test = function (url, jsondata, cb) { $.support.cors = true; $.ajax({ url: url, type: "get", data: jsondata, contenttype: "application/json; charset=utf-8", datatype: "json", processdata: true, success: cb, error: function error(response) { alert("network error"); }, complete: function (msg) { } }); alert("global " + globalvar); //here not getting value }
one more:- though if didnt use callback function, code inside success block executes before alert statement outside $.ajax, why not getting value?
thanks
your alert after $.ajax() instruction executed after xmlhttprequest has started before has ended, i.e. before success function called. @ time, globalvar still undefined.
Comments
Post a Comment