0

My code is listed below. I added several console.log to let me locate my problem. But the return of the code is quite strange, and I didn't manage to find answers here, so I asked a new question.

var quote_data = new XMLHttpRequest();
var url = "http://SOME.WEBSITE.com/API_QUERIES?&FIELDS=VALUES&output=text"

console.log("HERE0: Begin");

quote_data.open("GET", url, true);

console.log("HERE1: After open");

quote_data.setRequestHeader('Authorization', 'Basic '+btoa('USERNAME'+':'+'PASSWORD'));

console.log("HERE2: After setRequestHeader");

quote_data.send();

console.log("HERE3: After send");

quote_data.onreadystatechange = function (){
  if (quote_data.readyState == 4 && quote_data.status == 200) {
    console.log(quote_data.status);
    console.log('HERE4A: Works Fine');
    var alltext = quote_data.responseText;
    var lines = alltext.split("\n");
    alert(lines);
    }
  else {
     console.log("HERE4B: Error Reason: "+quote_data.status+" "+quote_data.readyState);
   }
}

console.log("HERE5: After statechange");

var split_lines = alltext.split(",");

console.log("HERE6: End");

The return of this code is: Return from Google Chrome

My problem is: (1) Why after executing the part with console.log('HERE4A: Works Fine'); the code no longer move on to console.log("HERE5")? (2) Why executing console.log("HERE5") first after console.log("HERE3") instead of executing console.log("HERE4")?

Thank you all for your attention and help!!!

Wenbin Liu
  • 21
  • 4

1 Answers1

0

Ajax call is asynchronous so HERE5 will be displayed right after this ajax call. You should move the rest of the code into the function like:

quote_data.onreadystatechange = function (){
  if (quote_data.readyState == 4 && quote_data.status == 200) {
    console.log(quote_data.status);
    console.log('HERE4A: Works Fine');
    var alltext = quote_data.responseText;
    var lines = alltext.split("\n");
    alert(lines);
    console.log("HERE5: After statechange");

    var split_lines = alltext.split(",");

    console.log("HERE6: End");
    }
  else {
     console.log("HERE4B: Error Reason: "+quote_data.status+" "+quote_data.readyState);
   }
}
huydq5000
  • 274
  • 1
  • 8