0

i want to get the http response from the php web page and save that in my variable in javascript code

this is my code :

    let state="";
function ajax(url) {
    return new Promise(function(resolve, reject) {
        var xhr = new XMLHttpRequest();
        xhr.onload = function() {
            resolve(this.responseText);
        };
        xhr.onerror = reject;
        xhr.open('GET', url);
        xhr.send();
    });
}
ajax("./code.php")
    .then(function(result) {
      this.state=result; 
      console.log(this.state)// work correctly
    })
    .catch(function() {
    });

console.log(this.state) //undefinde 

when i use console log in my save function, state variable logged correctly but outside the function console logged undefiend

how can i fix this problem

i'm beginner in javascript , I apologize for that :(

ali dehqani
  • 164
  • 1
  • 3
  • 18
  • The XMLHttpRequest is an assyncronous function, it means the script won't stop until it was completed, so when the line console.log is executed, the sunciont save was not called yet because xhttp didn't complete the task yet. If you put console.log inside save function, than will work. – Gustavo Jun 21 '20 at 14:15
  • @Gustavo ok i know it but i want to use state variable outside the function and i don't know how to do this work . ? – ali dehqani Jun 21 '20 at 14:19
  • You might try to set non assync in the open statement (xhr.open('GET',url,true)) so it will stop execution (teorically) in the send statement until it gets a return from call. – Gustavo Jun 22 '20 at 12:36

0 Answers0