AJAX sequential request to the same page -
i trying make 2 ajax requests same page 1 after another. but, getting response of last request. have below code.
<html> <head> <script type="text/javascript"> var xmlhttp; xmlhttp = new xmlhttprequest(); xmlhttp.open("get","getcdr.php?r=2",true); xmlhttp.send(); xmlhttp.open("get","getcdr.php?r=4",true); xmlhttp.send(); xmlhttp.onreadystatechange=function() { if (xmlhttp.readystate==4 && xmlhttp.status==200) { document.getelementbyid("mytab").innerhtml=document.getelementbyid("mytab").innerhtml+xmlhttp.responsetext; } } </script> </head> <body> <table id="mytab"> <tr><td>sl</td><td>mal</td></tr> </table> </body> </html>
your second request overwriting first request. since you're using async requests, should leveraging callbacks make sequential callbacks, if 1 request depends on another.
consider making second request within callback of first request.
function makerequestone(){ var xmlhttp; xmlhttp = new xmlhttprequest(); xmlhttp.open("get","getcdr.php?r=4",true); xmlhttp.send(); xmlhttp.onreadystatechange=function(){ if (xmlhttp.readystate==4 && xmlhttp.status==200){ console.log("request 1 complete, make second request"); console.log(xmlhttp.responsetext); makerequesttwo(); } } } function makerequesttwo(){ var xmlhttp; xmlhttp = new xmlhttprequest(); xmlhttp.open("get","getcdr.php?r=2",true); xmlhttp.send(); xmlhttp.onreadystatechange=function(){ if (xmlhttp.readystate==4 && xmlhttp.status==200){ console.log("request 2 complete"); console.log(xmlhttp.responsetext); } } } makerequestone();
although example little verbose, intended more illustrate.
Comments
Post a Comment