0

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);  
1
  • You should consider using a javascript framework for xhr. It makes things A LOT easier. Take a look at jQuery. Here is how you make an ajax request in jQuery Commented Dec 5, 2012 at 21:32

1 Answer 1

1

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 );        
   }
}
Sign up to request clarification or add additional context in comments.

1 Comment

In the third line the xmlhttp should be xml. Thank you !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.