Javascript only execute the last function called - javascript

I want my page to execute the same function 3 times, calling for 3 different things each time.
The code is currently
<script>
ajaxGet('/goget.php?name='+edit.dep.value, 'dep_result');
ajaxGet('/goget.php?name='+edit.arr.value, 'arr_result');
ajaxGet('/goget.php?type='+edit.reg.value, 'reg_result');
</script>
But it only executes the last call. Why?
Javascript:
var XMLHttpRequestObject = false;
if (window.XMLHttpRequest) {
XMLHttpRequestObject = new XMLHttpRequest();
} else if (window.ActiveXObject) {
XMLHttpRequestObject = new ActiveXObject("Microsoft.XMLHTTP");
}
function ajaxGet(ajaxLoadData, changeToID) {
if(XMLHttpRequestObject) {
var obj = document.getElementById(changeToID);
XMLHttpRequestObject.open("GET", ajaxLoadData);
XMLHttpRequestObject.onreadystatechange = function() {
if (XMLHttpRequestObject.readyState == 4 && XMLHttpRequestObject.status == 200) {
obj.innerHTML = XMLHttpRequestObject.responseText;
}
}
XMLHttpRequestObject.send(null);
}
}

You'll want to have each call to ajaxGet create its own XMLHttpRequest.
An XMLHttpRequest can only handle 1 request at a time. And, since they'll be making the request asynchronously, they'll be processing in parallel rather than sequentially.
function ajaxGet(ajaxLoadData, changeToID) {
var obj = document.getElementById(changeToID);
var xhr = new XMLHttpRequest();
xhr.open("GET", ajaxLoadData);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
obj.innerHTML = xhr.responseText;
}
};
xhr.send(null);
}
Granted, browsers generally limit requests to only a few at a time (usually 2), queuing any additional. But your code shouldn't count on that.
Side note: Unless you need to support IE6 or older, you shouldn't need to fallback to ActiveXObject.

You need to change your ajaxGet() method to instantiate a new XMLHttpRequest object at every call. Since, you're using the same XMLHttpRequest every new request is overwriting the previous one.
Hence, you're getting the results returned by the last method call only.
function getXHRObj() {
if (window.XMLHttpRequest) {
return new XMLHttpRequest();
} else if (window.ActiveXObject) {
return new ActiveXObject("Microsoft.XMLHTTP");
}
}
function ajaxGet(ajaxLoadData, changeToID) {
var XMLHttpRequestObject = getXHRObj();
var obj = document.getElementById(changeToID);
XMLHttpRequestObject.open("GET", ajaxLoadData);
XMLHttpRequestObject.onreadystatechange = function() {
if (XMLHttpRequestObject.readyState == 4 && XMLHttpRequestObject.status == 200) {
obj.innerHTML = XMLHttpRequestObject.responseText;
}
}
XMLHttpRequestObject.send(null);
}

Related

XMLHttpRequest() javascript

to resume my problem, i'm using many XMLHttpRequest() rockets, with a view to get the value (miniTable) returned by the TableRow() function. The problem is, with the alert() on the end of the TableRow() function, i'm have exactly the value that i want, but on TableContent2 variable i'm having an "Undefined" value. I don't know why!! here all the JS file that i'am using (don't care about variables and code calculating the variables). I really need your help, because i'm blocked since 3 days on that. Thank you again and good afternoon freinds.
(function() {
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
myFunction(xmlhttp);
}
};
xmlhttp.open("GET", "File1.xml", true);
xmlhttp.send();
})();
function ContentFunction(func) {
TableContent2 = TableRow();
alert(TableContent2);
}
function TableRow() {
xmlhttp3 = new XMLHttpRequest();
xmlhttp3.onreadystatechange = function() {
if (xmlhttp3.readyState == 4 && xmlhttp3.status == 200) {
texttest = myFunction2(xmlhttp3);
alert(miniTable);
return miniTable;
}
};
xmlhttp3.open("GET", "File2.xml", true);
xmlhttp3.send();
}
function myFunction2(xml) {
var xmlDoc2 = xml.responseXML;
var ObjectText;
var x = xmlDoc2.getElementsByTagName("Clip");
/*Calcule de ObjectText*/
alert(ObjectText);
return ObjectText;
}
function myFunction(xml) {
xmlhttp2 = new XMLHttpRequest();
var xmlDoc = xml.responseXML;
var x = xmlDoc.getElementsByTagName("Film");
xmlhttp2.onreadystatechange = function() {
if (xmlhttp2.readyState == 4 && xmlhttp2.status == 200) {
myFunction2(xmlhttp2);
}
};
xmlhttp2.open("GET", "File2.xml", true);
xmlhttp2.send();
}
TableRow returns nothing. The return statement at xmlhttp3.onreadystatechange isn't in the earlier scope. Besides that, your xmlhttp3 is set to be asynchronous, then you can't directly return any information of the AJAX. Synchronous requests, which are deprecated (that's why you shouldn't use them), can be directly read, since they act like a infinite loop that breaks when the request is done (for(;xhr.readyState!==4;);, doing this manually will pause the request and the script execution forever, this is why synchronous requests have been made before.).
Synchronous requests aren't a good idea, they break interaction with entire of the page, since they pause the page/script execution. For instance, if you've a animation, it'll be paused, including event listeners.
Also, it looks like miniTable haven't been declared in any part of your code.
Consider using callback functions, they'll be stored in the TableRow scope and can be called later, with extra arguments.
This is a base:
function ContentFunction(func) {
TableRow(function(TableContent2) {
alert(TableContent2);
});
}
function TableRow(doneFnc) {
var xmlhttp3 = new XMLHttpRequest;
xmlhttp3.onreadystatechange = function() {
if (xmlhttp3.readyState === 4 && xmlhttp3.status === 200) {
var texttest = myFunction2(xmlhttp3);
/* success callback */
doneFnc(texttest);
}
};
xmlhttp3.open("GET", "File2.xml", true);
xmlhttp3.send();
}

2 different ajax functions called one after another return the same value

I have a bizarre behavior of 2 different ajax functions called one after another.
Each of them fetch different value and populate different text boxes but the problem is they return the value of the first function called.
here is the code:
if (id == "Other") {
document.getElementById("Value").style.display = "block";
document.myForm.Price.value = "";
document.myForm.Code.value = "";
} else {
document.getElementById("Value").style.display = "none";
document.myForm.TypeValue.value = id;
getCOde(id);
getPrice(id);
}
here is getPrice function:
function getPrice(value) {
if (window.XMLHttpRequest) { //safari, chrome, opera, ffox
xmlhttp = new XMLHttpRequest();
} else { //IE
ActiveXObject("Microft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.AddingForm.itemPrice.value = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "../scripts/getPrice.php?ID=" + value, true);
xmlhttp.send();
}
here is the getCode fucntion
function getCode(value) {
if (window.XMLHttpRequest) { //safari, chrome, opera, ffox
xmlhttp = new XMLHttpRequest();
} else { //IE
ActiveXObject("Microft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.AddingForm.itemCode.value = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "../scripts/getyCode.php?ID=" + value, true);
xmlhttp.send();
}
both functions work well if only one of them is called. and beside if I interchange their order, than the value which is returned is the one of the first function called.
I wonder how to make one function to wait till another is executed. because i guess the order is the problem
You should declare xmlhttp inside each function instead of having it as a global variable.
function getPrice(value){
var xmlhttp;
if(window.XMLHttpRequest){//safari, chrome, opera, ffox
xmlhttp=new XMLHttpRequest();
}
else{//IE
xmlhttp = ActiveXObject("Microft.XMLHTTP");
}
you are overriding the reference to one object with another so the object in the event handler refered to by the identifier xmlhttp is the same in both cases

How can I access to the serverside php from javascript?

I set some variables in serverside through PHP
$LGD_AMOUNT = ""; //Amount is for the price that customer purchases
$LGD_BUYER = "";//Buyer collect name of the customer
And I store these in $payReqMap
$payReqMap['LGD_AMOUNT'] = $LGD_AMOUNT;
$payReqMap['LGD_BUYER'] = $LGD_BUYER;
what I want to do is before I send these to the server side, in <script> part, I want to give them values. Is there any method that I can call these stored variables in <script> part?
This is a start point to use Ajax using pure Javascript;
function getxmlhttp (){
//Create a boolean variable to check for a valid Microsoft active x instance.
var xmlhttp = false;
//Check if we are using internet explorer.
try {
//If the javascript version is greater than 5.
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
//If not, then use the older active x object.
try {
//If we are using internet explorer.
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (E) {
//Else we must be using a non-internet explorer browser.
xmlhttp = false;
}
}
// If not using IE, create a
// JavaScript instance of the object.
if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
xmlhttp = new XMLHttpRequest();
}
return xmlhttp;
}//Function getxmlhttp()
//Function to process an XMLHttpRequest.
function processajax (serverPage, obj, getOrPost, str){
//Get an XMLHttpRequest object for use.
xmlhttp = getxmlhttp ();
if (getOrPost == "get"){
xmlhttp.open("GET", serverPage);
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
obj.innerHTML = xmlhttp.responseText;
}
}
xmlhttp.send(null);
}
else {
xmlhttp.open("POST", serverPage, true);
xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
obj.innerHTML = xmlhttp.responseText;
}
}
xmlhttp.send(str);
}
}

Calling a JavaScript function

To call, for example, a function named makeRequest, I learned you need to do makeRequest();. If you only do makeRequest; it is a reference to the function (I thought). Yet, looking at this code (which worked when I tested it), it calls makeRequest; on the window.onload without the parens.
Can someone explain?
window.onload = makeRequest;
var xhr = false;
function makeRequest() {
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
else {
if (window.ActiveXObject) {
try {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) { }
}
}
if (xhr) {
xhr.onreadystatechange = showContents;
xhr.open("GET", "colors.xml", true);
xhr.send(null);
}
else {
document.getElementById("updateArea").innerHTML = "Sorry, but I couldn't create an XMLHttpRequest";
}
}
function showContents() {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
var outMsg = xhr.responseText;
}
else {
var outMsg = "There was a problem with the request " + xhr.status;
}
document.getElementById("updateArea").innerHTML = outMsg;
}
}
On this line:
window.onload = makeRequest;
the function makeRequest is not called. You only assign the function pointer to the onload event. When the DOM is loaded the browser automatically calls this event and it it is only at that moment that the function it is pointing to is invoked (which might happen much later but leave you with the impression that the function is called immediately).
It's a reference when used on the right-side of an expression. ie
var x = myfunction;
would set x to be a "pointer" to myfunction.
var x = myfunction();
would store the value returned-by-myfunction into x.

How to make update function check if it has loaded same context as there already is?

So I have next update function:
function update() {
var xmlhttp;
try {
xmlhttp = new XMLHttpRequest();
} catch (e) {
var success = false;
var objects = ["MSXML2.XMLHTTP.5.0", "MSXML2.XMLHTTP.4.0", "MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP", "Microsoft.XMLHTTP"];
for (var i = 0; i < objects.length && !success; i++) {
try {
xmlhttp = new ActiveXObject(objects[i]);
success = true;
} catch (e) { };
}
if (!success) throw new Error("AJAX is unavailabe");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
document.getElementById('usersList').innerHTML = xmlhttp.responseText;
};
}
xmlhttp.open("get", "buttons.html", true);
xmlhttp.send(null);
}
update();
setInterval(update, 5000);
so what I want it not to update documents contents if it has loaded same stuff that there is already. How to do such thing?
Something like:
if (xmlhttp.readyState == 4 &&
document.getElementById('usersList').innerHTML != xmlhttp.responseText) {
document.getElementById('usersList').innerHTML = xmlhttp.responseText;
};
EDIT: After patrick's comment in the page, it looks better to store the response somewhere and compare it to the new instead of relying on the innerHTML that can change the original HTML string.
You'll need to do the download first to determine what text you're comparing in the first place. I'm assuming buttons.html is somehow dynamic, so when you download it, you need to compare it to what's already in the innerHTML of userList.
...
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
if(document.getElementById('usersList').innerHTML != xmlhttp.responseText)
document.getElementById('usersList').innerHTML = xmlhttp.responseText;
};
}
...
In addition, if you're going to do a lot of ajax, I suggest using a library such as jQuery. Ajax calls are as simple as
$('#userList').load('buttons.html');
or
$.ajax({
url: 'buttons.html',
success: function(data) {
if ($('#userList').html() != data)
$('#userList').html(data);
}
});

Categories

Resources