简体   繁体   中英

How to test if my XMLHttpRequest worked?

(sorry for the bad english)

I'm a beginner in js and php I would like to know how to test if my POST request worked,

The code which send the request :

var nom2 = document.getElementById('nom2').value;
var data2 = document.getElementById('image_upload').value;
returnValue = "nom2="+nom2+"&data2="+data2;
var requete = createXmlHttpRequestObject();
requete.open('POST', "photo2.php", true);
requete.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
requete.send(returnValue);

And the code to test if my request worked

if (isset($_POST['nom2']) && isset($_POST['data2']))
{
    echo"<script  type='text/javascript'>   message(); </script>";
}

The problem is that nothing is writed into the console log, and when i try to echo nothing is writed too. Need some help please !

Thanks !

You have to create a callback. This is a function that is called when the browser finished your request.

var nom2 = document.getElementById('nom2').value;
var data2 = document.getElementById('image_upload').value;
var parameters = "nom2="+nom2+"&data2="+data2;

var http = new XMLHttpRequest();
http.open("POST", "photo2.php", true);

//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

http.onreadystatechange = function() {//Call a function when the state changes.
    if(http.readyState == 4 && http.status == 200) {
        console.log(http.responseText); // <= Here your browser prints the response that came from the php echo to the browser console
    }
}
http.send(parameters);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM