XMLHttpRequest wait response

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 have tried to change the xhr.open('POST', url, true); to false , however my load does not work.

    
asked by anonymous 07.08.2014 / 21:30

2 answers

2

At 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's wrong is that you should not use a callback with onreadystatechange for this. Just read xhr.responseText and do what you would in the callback directly after send() .

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

In summary:

[...]
var url = urlUpload;
var xhr = new XMLHttpRequest();
xhr.open('POST', url, false);
xhr.send(formData);
var dados = JSON.parse(xhr.responseText);
[...]
    
07.08.2014 / 23:12
0

Hello, there's a way to make it simple. using the axios

//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);
})
    
08.11.2018 / 14:03