Dealing with Multiple Ajax Requests
I have implemented several Like Buttons on a single PHP Page, which trigger the same Ajax function when clicked to update the corresponding text from Like to Unlike.
The current code works well for individual Like Button clicks, but if I click more than one at the same time and wait for them to update, only the last clicked button changes its text to Unlike.
Can someone suggest a better solution or provide an improved code snippet to address this issue?
Thanks
Page: Like.php
<span id="like1" onclick="ajaxFun(1)">Like</span><br />
<span id="like2" onclick="ajaxFun(2)">Like</span><br />
<span id="like3" onclick="ajaxFun(3)">Like</span><br />
<span id="like4" onclick="ajaxFun(4)">Like</span><br />
<span id="like5" onclick="ajaxFun(5)">Like</span><br />
....
<span id="like10" onclick="ajaxFun(10)">Like</span><br />
Page: ajaxx.js
function ajaxFun(id) {
document.getElementById("like"+id).innerHTML="Please wait...";
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else {
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
var getData=xmlhttp.responseText;
if(getData=="ok") {
document.getElementById("like"+id).innerHTML="Unlike";
}
else {
document.getElementById("like"+id).innerHTML="Like";
}
}
}
xmlhttp.open("GET","verify.php?id="+id,true);
xmlhttp.send();
}
Page : verify.php
This page verifies something and returns "ok" if successful, otherwise "not ok".
Error :(
Like
Like
Like
Please wait...
Please wait...
Please wait...
Please wait...
Please wait...
Please wait...
Unlike