Answered by:
ajax $.get runs late after the loop !!

Question
-
User-1123701243 posted
Hello
I have a a loop processing $.get statement inside it. The $.get returns value from controller function. as follows:
res = null; for (key in data.Results) { var url = "/Search/Get_ManID?MakeName=Test"; $.get(url, function (data) { res = data; // it will get some value , data = 148 } alert(res);
It will alert null instead of the value that it will hold.
The issue is that the alert statement will run before the $.get function.
How can I control the order of code running.
Wednesday, April 14, 2021 2:30 PM
Answers
-
User475983607 posted
That is the expected results due to AJAX being asynchronous. Basically, the alert is executed before the AJAX response is returned. Use a promise or the standard AJAX success handler.
res = null; for (key in data.Results) { var url = "/Search/Get_ManID?MakeName=Test"; $.get(url, function (data) { res = data; // it will get some value , data = 148 alert(res); }
- Marked as answer by An0nym0u5User Tuesday, September 21, 2021 12:00 AM
Wednesday, April 14, 2021 3:10 PM -
User1535942433 posted
Hi human2x,
As far as I think,you could push the value into a object and alert the object.Just like this:
res = null; arrayen = []; for (key in data.Results) { var url = "/Search/Get_ManID?MakeName=Test"; $.get(url, function (data) { res = data; // it will get some value , data = 148 attayen.push(res); } alert(JSON.stringify(attayen));
Best regards,
Yijing Sun
- Marked as answer by An0nym0u5User Tuesday, September 21, 2021 12:00 AM
Thursday, April 15, 2021 6:41 AM
All replies
-
User475983607 posted
That is the expected results due to AJAX being asynchronous. Basically, the alert is executed before the AJAX response is returned. Use a promise or the standard AJAX success handler.
res = null; for (key in data.Results) { var url = "/Search/Get_ManID?MakeName=Test"; $.get(url, function (data) { res = data; // it will get some value , data = 148 alert(res); }
- Marked as answer by An0nym0u5User Tuesday, September 21, 2021 12:00 AM
Wednesday, April 14, 2021 3:10 PM -
User1535942433 posted
Hi human2x,
As far as I think,you could push the value into a object and alert the object.Just like this:
res = null; arrayen = []; for (key in data.Results) { var url = "/Search/Get_ManID?MakeName=Test"; $.get(url, function (data) { res = data; // it will get some value , data = 148 attayen.push(res); } alert(JSON.stringify(attayen));
Best regards,
Yijing Sun
- Marked as answer by An0nym0u5User Tuesday, September 21, 2021 12:00 AM
Thursday, April 15, 2021 6:41 AM