Reputation: 11
My code only executes the codes after the second block of varoReq=new XMLHttpRequest();
but the first part isn't working. How can I get them both to work?
It only executes the codes after the 40th line and the first part which is the part after the 8th line isn't working
import {
girisKontrolSaha
} from './saha-giris.js';
window.onload = function() {
girisKontrolSaha();
var oReq = new XMLHttpRequest();
oReq.onreadystatechange = function() {
if (oReq.readyState == XMLHttpRequest.DONE) {
//console.log(oReq.response);
var response = oReq.response;
response = JSON.parse(response);
console.log(response);
response.forEach(element => {
console.log(element)
console.log(typeof(element.sonuc));
var postNode = document.createElement('div');
postNode.className = "table-orta1"
var card = '<div class="table-orta-icerik">' +
'<div class="icerik-baslik">' +
'<div class="icerik-bilgi">' +
'<p class="gunluk-liste1">' +
element.sonuc +
'</p>' +
'</div>';
postNode.innerHTML = card;
var postList = document.getElementById("table-orta1");
postList.appendChild(postNode);
});
}
}
oReq.open("GET", "../../backend/istatistik-günlük.php");
oReq.send();
var oReq = new XMLHttpRequest();
oReq.onreadystatechange = function() {
if (oReq.readyState == XMLHttpRequest.DONE) {
//console.log(oReq.response);
var response = oReq.response;
response = JSON.parse(response);
console.log(response);
response.forEach(element => {
console.log(element)
console.log(typeof(element.sonuc));
var postNode = document.createElement('div');
postNode.className = "table-orta2"
var card = '<div class="table-orta-icerik">' +
'<div class="icerik-baslik">' +
'<div class="icerik-bilgi">' +
'<p class="gunluk-liste2">' +
element.sonuc +
'</p>' +
'</div>';
postNode.innerHTML = card;
var postList = document.getElementById("table-orta2");
postList.appendChild(postNode);
});
}
}
oReq.open("GET", "../../backend/istatistik-haftalik.php");
oReq.send();
}
Upvotes: 1
Views: 69
Reputation: 51
You are basically sending 2 async request. First you are creating one request and storing it in variable oReq and sending the request and then you are immediately creating another request and storing it in variable with same name. When you use XMLHttpRequest.send() to send request, it sends the request in asynchronous manner and does not wait for response to come before initiating another request. So here 2 asynchronous requests are going but for only 2nd request callback is given because of variable reassignment, that's why only last request is working. You can find more details about XMLHttpRequest.send() here. https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/send
P.S: Small suggestion, try to use let keyword in place of var, it will not allow accidental variable reassignment.
Upvotes: 1