I was working through the night last night, burning the midnight oil as they say, trying to get this AJAX deal to work. I had to fill a select field with options once the user selects an option from a second select field. But, every time I made the AJAX call to retrieve the data, the target select field remained empty… in IE. Argh! IE! Why do you haunt me so?!
I put an onChange call on the select field to call the Javascript function when the user selects a field from the dropdown:
The fillData() function would grab the selected value from the drop down and send it to the getData.php file:
function fillData() {
var url = "getData.php?x=";
var len = document.form.choose.length;
for (i = 0; i < len; i++) {
if (document.form.choose[i].selected) {
url += document.form.choose[i].value;
}
}
request.open("GET", url, true);
request.onreadystatechange = updatePage;
request.send(null);
}
I had the getData.php file return something like this:
In the updatePage() function, I dropped the response from the getData.php file into the targeted select field:
function updatePage() {
if (request.readyState == 4)
if (request.status == 200) {
document.form.choose.innerHTML = request.responseText;
} else if (request.status == 404)
alert("Request URL does not exist");
else
alert("Error: status code is " + request.status);
}
The above pieces of code works fine for Firefox; but, for one reason or another, IE refuses to cooperate. I dropped in a couple alert statements in the updatePage() function to see what was happening. The response from the php files had the correct data. After assigning the response to the select field, a piece of the data gets chopped off in IE:
Target
After a bit of Google magic, the following solution works for both Firefox and IE. In the php file, I organized the data as a string of option pairs:
Target 1a:1a|Target 1b:1b
In the updatePage() function, I split the string on the | character to create an array of option pairs. Next, I looped through the array and split each pair on the : character to get the option text and option value. With these two values, I created a new Option object and attached it to the end of the Target select object.
function updatepage() {
if (request.readyState == 4)
if (request.status == 200) {
var response = request.responseText.split("|");
var choose = document.getElementById("choose");
var targets;
// set beginning point of select dropdown
// a length of 1 starts the append after the first option
choose.options.length = 1;
for (x=0; x
The result was perfect for what I needed and it worked in both Firefox and IE. I checked the page during a break at work and it worked fine in Opera and Safari too. w00t!
One thought on “Missing Data After AJAX Call”