lancellx
lancellx

Reputation: 285

javascript sends data to php by XMLHttpRequest,also want the php send some data back

I create a xhr in js to send some data to a php file. The php file will insert these data into database. Now I need to know the auto increased ID. I use

echo mysql_insert_id();

to get the ID in php. How can I read this value in javascript?

var xhr = new XMLHttpRequest();

 xhr.open(
         "POST",
         "xxx.php",true
     );
    var postContainer = new Array();
    postContainer.push(
    {
        data1 : value1, 
        data2 : value2,
    });
    var newJ = JSON.stringify(postContainer); 
    xhr.setRequestHeader("Content-type","application/json");
    xhr.send(newJ);  

Upvotes: 0

Views: 256

Answers (1)

aziz punjani
aziz punjani

Reputation: 25766

You can attach an event handler to listen for the onreadystatechange event.

xhr.onreadystatechange = function(){
   // check to make sure response finished and status is 200 meaning OK 
   if ( xhr.readyState == 4 && xhr.status == 200 ){
        console.log( xhr.responseText );        
   }
}

Upvotes: 1

Related Questions