MikeL
MikeL

Reputation: 79

XMLHttpRequest returning in FF but not IE

I'm trying to do an AJAX call to pull back data to popluate a drop down box based off the select of another drop down box. My code is working fine in FF 9.0.1 (used for firebug), but failing in IE 7 (which is my company standard). I've tried several ways to show the data, and I don't have the time right now to learn how to do this in jQuery. I'm sure this will be a head smacker, but what about IE is causing this issue?

Here are my code pages. First is the trimmed down version of the form calling the JavaScript.

<html>
<head>
<script language="JavaScript" src="/includes/Transaction_Update.js"></script>
<form id="submit" name="submit" action="Transaction_Process.php" method="post">
    <table align='left'>
      <tr>
        <td class='reporttd'>Vendor</td>
        <td>
          <select name='selVendorCode' id='selVendorCode' onChange="getServiceCode()">
            <option value='' selected='selected'></option>
            <?php echo $vendorOptionList; ?>
          </select>
        </td>
      </tr>
      <tr>
        <td class='reporttd'>Service Code</td>
        <td class='reporttd'>
          <select name='selServiceCode' id='selServiceCode'>
            <option value='' selected='selected'></option>
          </select>
        </td>
      </tr>
    </table>  
  </div>
</div>
</form>

JavaScript page

//setup xmlHttp request for Ajax call
var xmlHttp = createXmlHttpRequestObject();

function createXmlHttpRequestObject(){

    var xmlhttp;
    try{
        xmlHttp = new XMLHttpRequest();
    }
    catch(e)
    {
        var xmlHttpVersions = new Array("MSXML2.XMLHTTP.6.0",
                                        "MSXML2.XMLHTTP.5.0",
                                        "MSXML2.XMLHTTP.4.0",
                                        "MSXML2.XMLHTTP.3.0",
                                        "MSXML2.XMLHTTP",
                                        "Microsoft.XMLHTTP");
        for (var i=0; i<xmlHttpVersions.length && !xmlHttp; i++){
            try{
                xmlHttp = new Activexobject(xmlHttpVersions[i]);
            }
            catch(e) {}
        }
    }

    if (!xmlHttp){
        alert("Error creating the XMLHttpRequest object.");
    }
    else{
        return xmlHttp;
    }
}
//Call page to get all service codes for a vendor.
function getServiceCode(){  
    if (xmlHttp){
        try{
            var vCode = document.getElementById("selVendorCode").value;
            var parms = "vCode=" + vCode;

            //Call Transaction_AJAX.php to pass back an XML.
            xmlHttp.open("GET", "Transaction_AJAX.php?" + parms, true);
            xmlHttp.onreadystatechange = handleRequestStateChange;
            xmlHttp.send(null);
        }
        catch(e){
            alert("Can't connect to server:\n" + e.toString());
        }
    }
}

//Checks state of the HTTP request call, and proceed if status is ready
function handleRequestStateChange(){
    if (xmlHttp.readyState == 4){
        if(xmlHttp.status == 200){
            try{
                handleServerResponse();
            }
            catch(e){
                alert("Error reading the response: " + e.toString());
            }
        }
        else{
            alert("There was a problem retrieving the data:\n" + xmlHttp.StatusText);
        }
    }
}

//Handles response from the server
function handleServerResponse(){
    var xmlResponse = xmlHttp.responseXML;
        if (!xmlResponse || !xmlResponse.documentElement){
        throw("Invalid XML Structure:\n" + xmlHttp.responseText);
    }

    var rootNodeName = xmlResponse.documentElement.nodeName;
    if(rootNodeName == "parsererror"){
        throw("Invalid XML Structure:\n" + xmlHttp.responseText);
    }

    xmlRoot = xmlResponse.documentElement;
    if(rootNodeName != "root" || !xmlRoot.firstChild){
        throw("Invalid XML structure:\n" + xmlHttp.responseText);
    }

    //Get response and load it into drop down
    responseText = xmlRoot;

    var sel = document.getElementById("selServiceCode");
    sel.options.length = 0;
    var opt = document.createElement("option");
    document.getElementById("selServiceCode").options.add(opt);
    for(var i=0; i < responseText.childElementCount; i++){
        var newOpt = new Option(responseText.childNodes[i].childNodes[1].textContent,responseText.childNodes[i].childNodes[0].textContent);
        sel.options[sel.options.length] = newOpt;
    }
}

The PHP page creating the XML file

<?php
header('content-type:text/xml; charset=utf-8');

include("../includes/DBConn.php");

$vCode = $_GET['vCode'];

///Setup cursers and proc command
$curs = OCI_New_Cursor($c); 
$stmt = OCI_Parse($c,"begin schema.package.procedure(:var_code, :expected_cv); end;");

OCI_Bind_By_Name($stmt, ":var_code", $vCode);
OCI_Bind_By_Name($stmt,":expected_cv",&$curs,-1,OCI_B_CURSOR);

//execute statment and cursors
oci_execute($stmt); 
oci_execute($curs); 

//Create xml document
$dom = new DOMDocument('1.0', 'UTF-8');

$root = $dom->createElement('root');
$root = $dom->appendChild($root);

//loop through results of Proc
while (ocifetchinto($curs,&$vendor_cv )) { 

    //Add node for each row
    $occ = $dom->createElement("cell");
    $occ = $root->appendChild($occ);

    //Id Value
    $id = "value";
    $child = $dom->createElement($id);
    $child = $occ->appendChild($child);

    //Here is the actual value
    $id = $vendor_cv[1];
    $value = $dom->createTextNode($id);
    $value = $child->appendChild($value);

    //Id text
    $id = "text";
    $child = $dom->createElement($id);
    $child = $occ->appendChild($child);

    //Here is the actual value
    $id = $vendor_cv[1];
    $value = $dom->createTextNode($id);
    $value = $child->appendChild($value);
}
//Close xml tags and save.
$xmlString = $dom->saveXML();

//Echo XML back to Transaction_Update.js
echo $xmlString;
?>

Upvotes: 0

Views: 673

Answers (2)

Saravanan S
Saravanan S

Reputation: 1043

You can change your for loop in handleServerResponse to the following to fix this issue:

for(var i=0; i < responseText.childNodes.length; i++){
    var node = responseText.childNodes[i];
    var text = node.childNodes[1].text ? node.childNodes[1].text : node.childNodes[1].textContent;
    var value = node.childNodes[0].text ? node.childNodes[0].text : node.childNodes[0].textContent;
    var newOpt = new Option(text,value);
    sel.options[sel.options.length] = newOpt;
}

Upvotes: 0

Shyju
Shyju

Reputation: 218732

Here is how you do it in jQuery

1) Include jQuery library in your head section of the page. (here i am refering it from the google cdn)

<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>  
</head>

In your javascript

$("#stateDropDown").change(function(){
    var stateId=$("#stateDropDown").val();
    $.ajax({
      url: 'getcities.php?stateid='+stateId,
      success: function(data) {
       $("cityDropDown").html(data);       
      }
    });
});

Assuming you have a HTML select element with id "stateDropDown" for states and another one with id "cityDropDown" for cities.

The above code will do the follolwing

1) When the value of state dropdown changes, it executes the inside code.

2 ) Reade the selected item value and store it in a variable called stateId.

3) Using the jQuery ajax method , it makes a call to getcities.php page with a query string key called stateid

4) when we get a response from the ajax call, the control flow will be in the part called "success" handler. there we are receiving the response in a variable called data.

5) setting the received response (data) as the inner html of the city dropdown.

Assuming the getcities.php page will return some output like this

<option value='1'>Ann Arbor</option>
<option value='2'>Dexter</option>
<option value='3'>Novi</option>

jQuery will take care of your cross browser issues. Yes its is well tested and everybody is using it.

http://www.jquery.com

Upvotes: 2

Related Questions