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.
I didn’t understand your answer William, I’m using the POST method and I couldn’t solve it here.
– Diego Zanardo
@Diegozanardo The example is the same. Just change
"GET"
for"POST"
.– Guilherme Bernal
As you said, the problem is the interface seems locked.
– Diego Zanardo
In that case your function
UploadFile
should not return anything and all further action should occur within the callback. Instead of doingresultado = true;
, execute the code that must be executed if the upload is successful.– Guilherme Bernal