Issues encountered while interpreting XML with JavaScript

My script has a javascript function that sends an http_request to a php file on my server, which then generates an XML file (output below). The same javascript function attempts to parse the XML and passes it to other functions for further processing.

I have been struggling to successfully parse the XML document.

XML Output

<Results><!--Root-->
  <Result_Set>
    <State>State</State>
    <Cities>
      <City>City 1</City>
      <City selected="true">City 2</City>
       ...ETC...
    </Cities>
    <Zipcodes>
       <Zipcode selected="true">Zipcode 1</Zipcode
       <Zipcode>Zipcode 2</Zipcode>
        ...ETC...
    </Zipcodes>
  </Result_Set>
</Results>

Javascript Code Snippet

function GetZipInfo(zipcode){
    var xmlhttp;
    var x,resultSet,state,cities,zipcodes

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

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

            resultSet=xmlhttp.responseXML.documentElement.getElementsByTagName("Result_Set") //Function Crashes Here

            for(x=0;x<resultSet.length;x++){
                state=resultSet[x].getElementsByTagName("State")[0].nodeValue;
                cities=resultSet[x].getElementsByTagName("Cities");
                zipcodes=resultSet[x].getElementsByTagName("Zipcodes");

                selectState(state)
                xmlDropdown(cities, "City", "Cities")
                xmlDropdown(zipcodes, "Zipcode", "Zipcodes")
            }
        }
    }   
    xmlhttp.open("GET","GetZipInfo.php?Zipcode="+zipcode,true);
    xmlhttp.send();
}

This is my first time attempting to parse an XML document in any language, so I'm quite lost on what might be going wrong.

Any help would be greatly appreciated!

Edit: It seems my response is returning as responseText instead of responseXML.

Response Text

I am utilizing php to generate the XML page:

header("Content-Type: text/plain");
//Create the DOM
echo $xmlDoc->saveXML()

I'm still uncertain why it's not coming back as XML. Could it possibly be related to echo $xmlDoc->saveXML()?

Edit: After considering comments, it appears my issue may be with the header in the XML file. I added "alert(xmlhttp.responseText)" to my code which displays:

<?xml version="1.0"?>
<!--The Contents of my XML file-->

Could setting the encoding type resolve this issue? If so, how can I adjust my PHP code (above) to include that encoding?

Answer №1

Your response should have a MIME type of text/xml, or something that ends with +xml (check out RFC 3023).

Don't forget to include an XML declaration at the beginning.

Lastly, remember that while getElementsByTagName works for all elements in HTML documents, you should use document.getElementsByTagName in XML documents:

var resultSet = xmlhttp.responseXML.getElementsByTagName("Result_Set");

Answer №2

Make sure to include a colon at the top of your code:

<?xml version="1.0" encoding="UTF-8" ?>

Don't forget to add semicolons after these lines:

selectState(state);
xmlDropdown(cities, "City", "Cities");
xmlDropdown(zipcodes, "Zipcode", "Zipcodes");

In your XML code, remember to include '>' after:

</Zipcode>

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

React-navigation installation in React Native project failed due to ENOENT error - file or directory does not exist

Encountering errors during the installation of react-navigation in my react native project using npm install @react-navigation/native https://i.sstatic.net/uKiPQ.png The installation process reaches halfway, pauses for a few minutes, and then displays an ...

Error encountered with the OpenAI Chat Completions API: "The request could not be completed, status code 404"

Currently, I am in the process of developing an application similar to ChatGPT using React and Axios for API requests to OpenAI's Chat Completions API. However, I have hit a roadblock as I keep encountering a 404 error when attempting to make a reques ...

Obtain an Instance of a Class Using a Decorator

Delving deep into the world of decorators, I stumbled upon some fascinating ideas for incorporating them into my reflux implementation. My concept involves tagging a store's class method with an action, so that whenever that action is triggered, it au ...

Preserving the Selected Date on the Calendar Even After the PHP Variable is Passed

I am currently using the calendar code below with a slight modification that I implemented. However, I have encountered an issue where when I select a date, the calendar successfully highlights the selected date. But once I pass this selected date along ...

The CalendarExtender feature allows users to easily add years by simply clicking

<asp:CalendarExtender ID="ceBirthday" runat="server" TargetControlID="txtBirthday" CssClass="MyCalendar" Format="dd.MM.yyyy"> </asp:CalendarExtender> Is there a way to include years in the Calendar header for faster navigation? Currently, I ha ...

Transform collapsible color upon materialize click

Is there a way to change the color of the collapsible header only when clicked? I'm struggling with adding the color inside the class element while calling the "connect" function. Can this be achieved? <div class="collapsible-header" onclick="conn ...

Issues with Jquery and revslider functionality in React.js are causing problems

Just getting started with react.js and diving into the world of react development. Encountering an issue while converting static HTML to react.js where jQuery scripts only execute after manually refreshing the page, causing a slowdown in React speed. T ...

Can you utilize session in the routes.php file of CodeIgniter?

I've encountered some challenges with URL routing in CodeIgniter. I have a login controller that loads a login view file for user input, and I'm using Ajax login which only returns the base URL. However, instead of using the login controller in m ...

Angular post request does not update the table

After displaying a table and a form on a page, I encountered an issue where the table does not update with new data when submitting the form. Even after refreshing the page, the new data is not reflected. As a newbie to Angular, I'm unsure of what exa ...

Troubleshooting the Issue of PHP Variables Not Being Assigned to Javascript Variables

I am currently struggling with an issue. I am trying to assign a PHP value to a variable in Javascript. Here is what I have attempted: <script> JSvariable = <?php echo $PHPvariable; ?>; </script> However, this approach is not yieldi ...

Ensuring a radio button is pre-selected by default in React by passing in a prop

Assume I have a React function similar to this function Stars({handleStarClick, starClicked}) { if (starClicked === 3) { document.getElementById('star3').checked = true } return ( <div className="rate"> ...

Unraveling HTML elements within a string using MongoDB: A step-by-step guide

Currently, I am in the process of creating a blog from scratch as a way to enhance my skills. The posts' content is stored as a long string in MongoDB with some random HTML tags added for testing purposes. I am curious about the conventional method fo ...

Generate clickable links on a web page with PHP and a form

Every week I find myself tediously creating links by manually copying and pasting. It's starting to feel like a crazy process, and I'm sure there must be a faster way. A123456 B34567 d928333 s121233 I need these numbers to be transformed into h ...

Adding up the numbers with JavaScript

Hello everyone, I've been working on some transformations and now I'm left with an array of objects: Can anyone help me come up with a flexible function that will generate a new object where each data[i] is the sum of values from the previous ob ...

javascript/jquery: ensure Android device displays content in full-screen mode

Currently working on developing a web app specifically for an android device that needs to be displayed in fullscreen mode. I came across the code snippet above on stack overflow, which successfully activates fullscreen mode upon click event. However, I a ...

Using React/Vite with createBrowserRouter in a subdirectory will not function properly unless a trailing slash is included

My current project involves using React/Vite/Express to create an app that is hosted within a subdirectory. For example, let's say the app is hosted at: https://example.com/my/app/ In my Vite configuration, I have specified base as ./ export default ...

Ways to incorporate additional values into an array object with Vuex

I'm new to using vuex and I am attempting to save objects into an array called orders within the store.js file. My goal is to extract values from an object (such as me.title) and save them into an array within the store file by clicking on a button t ...

What is the best way to retrieve the source code generated by Ajax

I designed a PHP script that generates text dynamically and returns it with a unique div id. However, when I use Ajax to retrieve this text as responseText, I am unable to access the properties of the div using JavaScript because the new text is not added ...

Utilize the findIndex method to search for an element starting at a designated index

Below is a snippet of code that I have: private getNextFakeLinePosition(startPosition: number): number{ return this.models.findIndex(m => m.fakeObject); } This function is designed to return the index of the first element in the array that has ...

pg-promise makes it easy to use named parameters with nested objects

Is it feasible to access nested objects while utilizing named parameters in pg-promise? Take a look at this example: var obj = { name: 'John', address: { postcode: 'abc' } }; db.query('SELECT * FROM users WHER ...