Issues encountered with parsing Ajax XML request

I am encountering an issue with my simple ajax request to load XML data when a value in a dropdown is selected. The XML contains image paths that I need to switch based on the user's selection. Everything works perfectly fine in Firefox without any JavaScript errors, but strangely nothing happens in Chrome. Below is the code snippet I've been working on:

        <script type="text/javascript">
        function loadXMLDoc(url) {

            var xmlhttp;
            var txt, txtBase, txtOverlay1, txtOverlay2, txtBlack, name, img;

            if (window.XMLHttpRequest){
              // code for IE7+, Firefox, Chrome, Opera, & Safari
              xmlhttp=new XMLHttpRequest();
              xmlhttp.overrideMimeType("text/xml");
            }
            else { 
              // code for IE6 & IE5
              xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
            }
            xmlhttp.onreadystatechange=function() {

                if (xmlhttp.readyState==4 && xmlhttp.status==200) { 

                    txtBase='<img id="original"';
                    txtOverlay1='<img id="overlay1" class="overlay"';
                    txtOverlay2='<img id="overlay2" class="overlay"';
                    txtBlack='<img id="opacity" class="overlay"';

                    img=xmlhttp.responseXML.documentElement.getElementsByTagName("IMG");
                    name=img[0].getElementsByTagName("NAME");

                    txtBase = txtBase + name[0].firstChild.nodeValue + '/>';
                    txtOverlay1 = txtOverlay1 + name[1].firstChild.nodeValue + '/>';
                    txtOverlay2 = txtOverlay2 + name[2].firstChild.nodeValue + '/>';
                    txtBlack = txtBlack + name[3].firstChild.nodeValue + '/>';

                    txt = txtBase + txtOverlay1 + txtOverlay2 + txtBlack;
                    document.getElementById('inner_container').innerHTML = txt;
                    $(".red").css({"font-size":"2.0em"});
                    $(".blue, .green").css({"font-size":"1.0em"});
                }
            }
            xmlhttp.open("GET",url,true);
            xmlhttp.send();
        }
    </script>

To trigger the above function, I use this.

            <select>
                <option id="selected">Select a car</option>
                <option onclick="loadXMLDoc('http://www.brandybrowauto.com/files/nissan.xml')">Nissan</option>
                <option onclick="loadXMLDoc('http://www.brandybrowauto.com/files/mazdaspeed3.xml')">Mazdaspeed3</option>
            </select>

If anyone could provide insights on why it doesn't work in Chrome and suggest improvements to the code, especially since I'm new to ajax, it would be highly appreciated.

Answer №1

Have you tested any part of this code on your site using Chrome? If so, how much progress did you make? If not, I recommend utilizing the Chrome developer's tools to set breakpoints in your javascript and step through the code until it no longer functions correctly.

I suspect that the issue lies with Chrome possibly disliking the use of

xmlhttp.onreadystatechange

In this case, it may be more appropriate to use:

xmlhttp.onload

EDIT CONTENTS:

Upon reviewing your code (based on your comment response), it appears that the onclick event for your option will never trigger. I experimented with the code to confirm that it indeed does not work. The specified event will not execute.

<option onclick="alert('test');">Nissan</option>

Rather than relying on events from options, it is recommended to use onchange events from the select element.

<select onchange="alert(options[selectedIndex].text);">

Please test this solution and let me know if it meets your needs. You can then implement this information to initiate your xmlhttp logic.

Answer №2

Make sure to double-check the status code. Sometimes, when a XML file is requested multiple times, the server may send a different status code like 304.

To avoid this issue, jQuery automatically adds a random parameter to the URL (you can also do this manually).


Note:

If you are encountering issues with the click handler not triggering, try using the following markup for the select element instead:

<select onchange="if(this.value)loadXMLDoc(this.value)">
  <option value="0" id="selected" selected="selected">Select a car</option>
  <option value="/files/nissan.xml">Nissan</option>
  <option value="/files/mazdaspeed3.xml">Mazdaspeed3</option>
</select>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating an AJAX data form in a JSP scenario

I want to correctly set up the data parameter for the ajax call. <script type="text/javascript"> $(document).ready(function() { $('#call').click(function () { $.ajax({ type: "post", ...

Explore all potentialities within an array of objects by examining and contrasting their key values

Looking to run a specific math formula with three parameters using an array of objects in JavaScript. The scenario involves sports, where there are three possibilities: Team A (win), Team B (win), or Draw. There are three different bet websites offering o ...

Why does one of the two similar javascript functions work while the other one fails to execute?

As a new Javascript learner, I am struggling to make some basic code work. I managed to successfully test a snippet that changes text color from blue to red to ensure that Javascript is functioning on the page. However, my second code attempt aims to togg ...

Send a response from socket.io to the client's browser

I am working on a project where I need to retrieve the ID of the current drawer from the server and pass it to the client. Here is the code I have so far: Client Side: socket.emit('returnDrawer'); socket.on('returnDrawer', fu ...

Leveraging AJAX for transmitting information to FormCollection

I am experimenting with using FormCollection instead of a model in my project. I have set up an AJAX request as shown below: myData = { id: '1', name: $("#name").val() }; $.ajax({ type: "GET", url: '/ ...

Tips for successfully passing store state as a prop in React-Redux with TypeScript

Having trouble passing information from the initial state of the store to a component where it's supposed to be rendered. Despite a console.log in the component showing that it's undefined, there doesn't seem to be any issue with the initial ...

Choosing one element from various options in multiple forms

I'm encountering an issue with selecting a specific element from multiple forms in my JavaScript code: The current JavaScript function I am working with is as follows: function makeActive(target) { $("div.interactive").removeClass("interactive") ...

Exploring the capabilities of arrays within Ajax

Below is the original code I wrote in JavaScript: var wt_val = []; for (i = 0; i<human_wt.length; i++){ var mult; mult = data_list[basket_list[button_port_name][i]].map(x => x*(wt[i]/100)); wt_val.push(mult); ...

ACL - Utilize ACL in conjunction with the passport authentication system

I am experimenting with node_acl in combination with passport-local. Unfortunately, I am facing an issue when trying to secure the route for the admin-user '/admin', as it keeps redirecting me to the /login page. Below is a simplified version of ...

In the realm of numeric input in JavaScript (using jQuery), it is interesting to note that the keyCode values for '3' and '#' are identical

I am in need of setting up an <input type="text" /> that will only accept numeric characters, backspace, delete, enter, tabs, and arrows. There are many examples out there, and I started with something similar to this: function isNumericKeyCode (ke ...

Creating a custom dashboard with interactive widgets using the MVC3 framework

I am looking to create a dashboard using MVC3 for an administrator that will allow them to perform various operations. Each widget will have multiple buttons, and each button will trigger an AJAX call to the same action in the controller. Similar to an u ...

Will cancelling a fetch request on the frontend also cancel the corresponding function on the backend?

In my application, I have integrated Google Maps which triggers a call to the backend every time there is a zoom change or a change in map boundaries. With a database of 3 million records, querying them with filters and clustering on the NodeJS backend con ...

Launching a vue-js-modal modal from a location beyond a component

In our current project, we have implemented the vue-js-modal plugin. I am facing a situation where I need to trigger a modal from code that is not within a Vue component. The official documentation only covers using the API inside a component. Is there a w ...

I am in possession of 10,000 entities in cesium. What is the best way to avoid using a loop to modify their material?

Starting new Cesium.PolylineGlowMaterialProperty({ glowPower: 0.15, color: Cesium.Color.fromCssColorString("rgba(42,92,170, 0.15)") }); Ending new Cesium.PolylineGlowMaterialProperty({ glowPower: 0.3, ...

Navigating external pages with Vue Router

Could really use some assistance. I've got a JSON file filled with various URL links, some internal and some external. This is what the JSON structure looks like: [ {stuff..., "Url":"https://www.google.com/", stuff..}, {stuff... ...

Create a feature in three.js that allows users to click on an object to display information about the

After loading an object using the GLTF loader into my scene, I want to create a point on this object to display popup info. Is there a way to add a point to a specific location on the object? ...

Calculate the total number of seconds from an ISO8601 duration with TypeScript by utilizing the date-fns library

Given an ISO8601 duration string like "PT1M14S," I am looking to convert it to seconds as an Integer using the date-fns library in TypeScript. ...

Troubleshooting OpenCart Error Redirects with UserFrosting

Hi there! I've been working on a project where I'm integrating OpenCart into UserFrosting. Specifically, I'm loading all the admin dashboard pages within the UserFrosting dashboard using jQuery's .load function to inject them into a div ...

JavaScript (Create a button that toggles the visibility of an element)

I have implemented a hamburger menu that transforms into an x when clicked. I am looking to modify it so that clicking on the hamburger opens the menu, and clicking on the x closes the menu. Below is the code I have been working with: <!DOCTYPE html&g ...

Creating a new route in a Express JS server to specifically handle POST requests

Just starting to learn the ropes of Javascript, and I'm diving into express to create an application that will enable users to craft new recipes, explore existing ones, and view details about each recipe. To get things moving, I've launched my s ...