0
Good staff as I can correctly print Hello World, using AJAX request, inside a for?
My real question is: understand why the for executes your entire loop in the first ajax request, and only then run loop in the second ajax request?
Today I have that result:
HTML and JS Code
<html>
<head>
</head>
<body>
</body>
<script src="../jquery-3.3.1.min.js"></script>
</html>
<script>
$(document).ready(function(){
});
function call(){
for(i = 0; i <= 5; i++){
$.ajax({
url: 'json.json',
type: 'get',
success: function(data){
call_1(data['data'].one);
$.ajax({
url:'json.json',
type: 'get',
success: function(data){
call_2(data['data'].two);
}
});
}
});
}
}
function call_1(res){
$('body').append(res);
}
function call_2(res){
$('body').append(res+'<hr>');
}
</script>
My json.json file:
{
"data": {
"one": "Hello",
"two": " World"
}
}
I decided to send along with the options of the ajax the:
async: false,
Thus remaining:
function call(){
for(i = 0; i <= 5; i++){
$.ajax({
async: false,
url: 'json.json',
type: 'get',
success: function(data){
call_1(data['data'].one);
$.ajax({
async: false,
url:'json.json',
type: 'get',
success: function(data){
call_2(data['data'].two);
}
});
}
});
}
}
What part of the code you can change and what part you can’t change?
– Sergio
The part about ajax.
– Weliton Sernajotto
Can you explain it better? I asked which can change and what nay can...
– Sergio
So, actually I wanted to understand why for executes all your loop in the first ajax request, only then run loop in the second ajax request.
– Weliton Sernajotto
Read this answer and say if it answers your question: https://answall.com/questions/1237/como-usar-o-valor-actual-de-umavari%C3%A1vel-numa-fun%C3%A7%C3%A3o-mais-interna/1238#1238
– Sergio
Sergio, didn’t solve using Let. =(
– Weliton Sernajotto
The problem or solution is not the
let
... is not yet understanding the asynchronous nature of ajax. If you read that question and my answer there you will understand that mechanism and it will help you understand the problem here. But you have to read everything, want to understand... read it and tell me how the two questions are related?– Sergio
I got it! I read about the asynchronous functions and adjusted the code, working correctly now. I put together with the ajax Settings the line: async: true, So he makes one request and after the other. Thank you.
– Weliton Sernajotto