Reputation: 97
I'm trying to to use Javascript to update the innerHTML of a webpage after an onclick event. My Javascript (java.js) uses this code to access a PHP page which echoes back the text that goes in the innerHTML. The thing is, I want to update the innerHTML of two items (a "color" table and an "item" table) which are not located next to each other and have different element ID's. Each call from java.js works fine individually (like if one is commented out), but when both of them are run, whichever one is first will get stuck on the "loading" message and the second one will work. Loading "content.php?item='5'&color='5'" in a web browser shows both tables.
I suspect this is something to do with the mechanics of $_GET[] (which I don't totally understand; this is my first time working with PHP). But the calls should happen sequentially and the keys ('item' and 'color') don't conflict, so I can't figure out what's going wrong.
function makeActive(active_tab) {
//item table
callAHAH('content.php?item='+active_tab, 'item', 'getting items for tab '+active_tab+'. Wait...', 'Error');
//color table
callAHAH('content.php?color='+active_tab, 'color', 'getting colors for tab '+active_tab+'. Wait...', 'Error');
}
if (isset($_GET['color'])) {
require 'color.php';
$index = 1*$_GET['color'];
$arr = $ITEM_TYPES[$index];
echoColorTable($arr); //makes table in color.php
} else {
echo "color not set "; //debug
}
if (isset($_GET['item'])) {
require 'item.php';
$index = 1*$_GET['item'];
echoItemTable($index); //makes table in item.php
} else {
echo "item not set "; //debug
}
Upvotes: 2
Views: 459
Reputation: 141829
The problem is with the callAHAH function you linked to. It doesn't have a var
keyword when it declares req
. So it is a global variable and there can only ever be one request at once. It also reuses that global variable in the responseAHAH function. In general global variables are a bad idea for reasons like this. I recommend ditching the callAHAH function altogether and using something like this which does the exact same thing without using a global variable:
function loadInto(url, id, loading, error) {
var ajax;
var el = document.getElementById(id);
el.innerHTML = loading;
if (typeof XMLHttpRequest !== 'undefined')
ajax = new XMLHttpRequest();
else // Some people still support IE 6
ajax = new ActiveXObject("Microsoft.XMLHTTP");
ajax.onreadystatechange = function(){
if(ajax.readyState === 4){
if(ajax.status == 200){
el.innerHTML = ajax.responseText;
}else{
el.innerHTML = error;
}
}
};
ajax.open('GET', url);
ajax.send();
}
It's also not named callAHAH
, and that's always a plus.
Upvotes: 1