R
R
Romeo47552020-03-15 16:34:20
PHP
Romeo4755, 2020-03-15 16:34:20

Synchronous requests for JS XMLHttpRequest - how to implement it now?

Tell me how to accomplish the task of synchronous XMLHttpRequest in 2020.
That is, you need to stop the script execution before the response from the server (or finish it altogether if the response does not come within, for example, a minute).
Asynchronous requests disfigure the logic of the program - you have to call the next action not from a clear list of sequential actions, but from functions scattered across different scripts. I would like to be able to execute exactly a synchronous request - but there is so much negative information about it at different times that it is not clear what can be done at the moment, what cannot.
For example, this code does not work for me. Why - I do not know, whether I have a mistake, or whether this is no longer possible.

var request = new XMLHttpRequest();
 request.open('POST', 'baseindex_numberoflines.php');// from sellers
 request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.send("nameoftable="+atabname);
if(request.status == 200) {
    newdata = request.responseText;
  	document.getElementById ("newinfo").innerHTML = newdata;
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Cheremkhin, 2020-03-15
@Che603000

Tell me how to accomplish the task of synchronous query in 2020.

in 2020 you should not use XMLHttpRequestuse window.fetch
https://learn.javascript.ru/fetch
Asynchronous requests spoil the logic of the program

In js, asynchrony is the norm. To simplify the code, you can use Promise
https://learn.javascript.ru/promise
For an example, the pseudocode is below
fetch('baseindex_numberoflines.php', {method: 'post' , body: {id: '735474'}})
    .then(newdata=> { 
        // блок 1 - выполнится после успешного запроса
       document.getElementById ("newinfo").innerHTML = newdata );
       return "test"
    })
    .then(test=> { 
        // выполнится после блок 1
    })
    .catch(err=>{
      // блок выполнится после ошибки
    }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question