Xmlhttprequest Expect Response

Asked

Viewed 723 times

0

I would like my Xmlhttprequest to wait for the answer.

function UploadFile(campoFile, urlUpload, campoNome) {
    var img = $("#" + campoFile).val();
    var resultado = false;
    if (img) {
        var file = document.getElementById(campoFile).files[0];
        var formData = new FormData();
        formData.append(file.name, file);
        var xhr = new XMLHttpRequest();
        xhr.open('POST', url, true);
        Carregar();
        var url = urlUpload;
        url = '@Url.Content("~/")' + url;
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4 && xhr.status == 200) {
                var dados = JSON.parse(xhr.responseText);
                if (dados.Nome != "") {
                    $('#' + campoNome).val(dados.Nome);
                    resultado = true;
                } else {
                    alert("Ocorreu um erro no upload da imagem.");
                    $('#loader').remove();
                    resultado = false;
                }
            }
        }
        xhr.send(formData);
    }
    return resultado;
}

I’ve tried to change the xhr.open('POST', url, true); for false, but then my load doesn’t work.

2 answers

2


In the MDN there are some examples of synchronous requests, the first of them:

var request = new XMLHttpRequest();
request.open('GET', '/bar/foo.txt', false);  // `false` makes the request synchronous
request.send(null);

if (request.status === 200) {
  console.log(request.responseText);
}

What is wrong is that you should not use a callback with the onreadystatechange for that. Just read xhr.responseText and do what you would do in the callback directly after the send().

But remember that this prevents any other javascript code from running on the page. If the user clicks on a button, for example, the onclick will not fire and the interface will appear to be locked. From the user’s perspective, it may be bad. Unless, of course, you are using Web Workers.


In short:

[...]
var url = urlUpload;
var xhr = new XMLHttpRequest();
xhr.open('POST', url, false);
xhr.send(formData);
var dados = JSON.parse(xhr.responseText);
[...]
  • I didn’t understand your answer William, I’m using the POST method and I couldn’t solve it here.

  • @Diegozanardo The example is the same. Just change "GET" for "POST".

  • As you said, the problem is the interface seems locked.

  • In that case your function UploadFile should not return anything and all further action should occur within the callback. Instead of doing resultado = true;, execute the code that must be executed if the upload is successful.

0

Hello, there is a way to do this simple. using the

//usando o  <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
axios.get("https://api.github.com/users/itasouza")
.then(function(response){
    //esperando a resposta para fazer alguma coisa
    console.log(response);
    console.log("login :" + response.data.login);
    console.log("id : " + response.data.id);
})
.catch(function(error){
    console.log(error);
})

Browser other questions tagged

You are not signed in. Login or sign up in order to post.