I have two JS functions that preforms AJAX calls, I’ve wanted to test them so I’ve created two paragraphs with different ids that will hold the result of the responses text:
<script type="text/javascript">
trackApplicationAdded('1139631160', '12445'); //should change test1 paragraph
trackApplicationRemoved('1139631160'); //should change test2 paragraph
</script>
<p>Test1: <span id="test1"></span></p>
<p>Test2: <span id="test2"></span></p>
When I run each function on its own (commenting on of them), each one changes its own paragraph as expected, but when I run both of them, I can only see the paragraph change made by the LAST function.
I have a function that creates an XMLHttpRequest that gets the variable test which send the paragraph id that should be changed by each function (and as noted, it is working when each one is called by itself).
function sendRequest(url, params, test)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
if (window.XMLHttpRequest)
{
httpRequest=new XMLHttpRequest();
}
else // code for IE6, IE5
{
httpRequest=new ActiveXObject("Microsoft.XMLHTTP");
}
httpRequest.open("POST", url, true);
//Set request headers for POST command//
httpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
httpRequest.setRequestHeader("Content-length", params.length);
httpRequest.setRequestHeader("Connection", "close");
httpRequest.onreadystatechange=function()
{
if(httpRequest.readyState==4 && httpRequest.status==200)
{
//Here you can see "test" which, depends on the function, is test1 or test2//
document.getElementById(test).innerHTML=httpRequest.responseText;
}
}
httpRequest.send(params);
//end when the server will responde we will execute the "document.getElementById("txtHint").innerHTML=xmlhttp.responseText;" //
}
By the way, the AJAX preforms database insert by PHP functions and its everything working good in any situation. It is important to note that the problem is only with the paragraph changes and not what happens in the server.
Any one have an idea how to solve this ? Thanks…
EDIT
Here is the code of the 2 functions:
function trackApplicationAdded(fID, fappID)
{
var url = "trackApplicationAdded.php";
var params = "facebookID=" + fID + "&facebookApplicationID=" +fappID;
sendRequest(url,params, "test1");
}
function trackApplicationRemoved(fID)
{
var url = "trackApplicationRemoved.php";
var params = "facebookID=" + fID;
sendRequest(url,params, "test2");
}
You forgot
varwhen you declared “httpRequest”, so the second call overwrites the first. Without thevardeclaration the variable is global.At the top of “sendRequest()” just add: