xmlhttprequest object working but not giving output in response?

2k Views Asked by At

i have following code in which i am making a call to getlink.php script to get a link of given file. But when i do alert(xhr.responseText) it does not show anything. But if i output on console as console.log("my object: %o", xhr); it gives responseText field. code is:

function linkFile(file) {  
    uri = "http://localhost/imgbag/getlink.php";  
    var xhr = new XMLHttpRequest();  
    var formdata= new FormData();
    formdata.append("linkFile",file);
    xhr.open("POST", uri, true);  
    xhr.send(formdata);
    console.log("my object: %o", xhr);
}
2

There are 2 best solutions below

0
On

when you use true in xhr.open it sets it to be async which means the response will come back later and you need to collect it by attaching a listener.

if you set that param to false your code will work (but will not be async and will block on the call (meaning it will just sit there till the response comes back)

here's how to add a listener (because your async approach is actually the better one)... http://www.w3schools.com/ajax/ajax_xmlhttprequest_onreadystatechange.asp

0
On

Define the onload attribute like this :

xhr.onload = function () {
    alert(xhr.responseText);
}

This ensures that the alert takes place only after the request has been successfully completed.

Sources : MDN