Jquery Having Issue With Global Variable Inside Function Ajax Function
Solution 1:
After your javascript makes the initial ajax call the execution of the script proceeds to the return statement. At this point the response to your request has not been returned yet, therefore your callback function has not executed, meaning ret has not been assigned a value. You need to include the call to hello within your callback function in order to guarantee that ret has been assigned a value.
var ret;
function fetch_data(param1){
$.post(param1,
function(data){
if (data){
ret = data*2;
console.log("data", ret);
}
else{
ret = 15;
console.log("no data")
}
hello();
});
}
function hello(){
ret = fetch_data("/post_data");
console.log("from the main function", ret);
}
There are two ways that Ajax can access the server. These are synchronous (wnere the script stops and waits for the server to send back a reply before continuing) and asynchronous (where the script allows the page to continue to be processed and will handle the reply if and when it arrives). Your function is performing asynchromnously, meaning the fetch_data function is executing the return statement before the ajax call is completed.
Order of Events:
- fetch_data is called
- fetch_data fires off ajax request.
- fetch data returns ret(undefined)
- hello function prints ret to console
- ajax response is received from server
- ret is assigned a value based upon ajax response
I would like to further suggest that you modify your code to what I consider to be a better approach. I believe this approach captures your intent better than specifying the hello function within your callback.
function fetch_data(param1,callback){
$.post(param1,
function(data){
callback(data);
});
}
function hello(data){
if (data){
ret = data*2;
console.log("data", ret);
}
else{
ret = 15;
console.log("no data")
}
console.log("from the main function", ret);
}
function hello2(data){
//...different logic that modifies data
console.log("from the main function", ret);
}
//Function call passing the hello function as a parameter
fetch_data('/post_data', hello);
//Function call that passes hello2 function as a parameter
fetch_data('/post_data', hello2);
Post a Comment for "Jquery Having Issue With Global Variable Inside Function Ajax Function"