Trouble obtaining AJAX result using onClick event

As a newbie to AJAX, I am still trying to grasp the concept. My task involves using an AJAX call to extract specified information from an XML file. Even after carefully parsing all tag elements into my JavaScript code, I encounter a problem when attempting to display the desired content upon button click. The image below illustrates the expected output.

function makeAjaxQueryWeather(){
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
    myFunction(this);
    }
  };
  xhttp.open("GET", "A8.xml", true);
  xhttp.send();
}

// handler for the readyState change
function readyStateChangeHandler(xhttp){

  if (xhttp.readyState == 4){
    // readyState = 4 means DONE

    if(xhttp.status == 200){
      // status = 200 means OK

      handleStatusSuccess(xhttp);

    }else{
      // status is NOT OK

      handleStatusFailure(xhttp);

    }
  }

}

// XMLHttpRequest failed
function handleStatusFailure(xhttp){

  // display error message

...

</pre>
<pre><code><h1>Part 2</h1>
<button onClick="makeAjaxQueryWeather()">
Click here to view weather forecast 1
</button>
<br/> <br/>
<div id="display">
</div>

https://i.stack.imgur.com/dLRXf.png

This is the XML file : https://i.stack.imgur.com/ToAYj.png

Answer №1

Update your display function with the following code snippet and test it out.

function showWeather(weatherData){
  // log weather data to the console
  // console.log(weatherData);

  // create HTML content to show weather details
  var html = `<h1>${weatherData.location + weatherData.time}</h1><span>${weatherData.date}</span>`;
  
  // insert the generated HTML content in the display section
  var displaySection = document.getElementById("display");
  displaySection.insertAdjacentHTML('afterbegin',html);
}

Answer №2

To properly handle XML strings and convert them into an XML DOM document, you can utilize the DOMParser() method:

This function can be implemented as follows:

// Function to parse XML string into a proper XML DOM document
function parseXML(xmlString) {
  return new window.DOMParser().parseFromString(xmlString, "text/xml");
}

You can then utilize this function to parse XML content received from an XMLHttpRequest call.

The following code snippet illustrates how this function can be used within the success handler of an XMLHttpRequest call:

// Handling successful XMLHttpRequest
function handleStatusSuccess(xhttp) {
  var xml = xhttp.response;
  xml = parseXML(xml);

  // Parse the XML data into an object
  var weatherObj = parseXMLWeather(xml);
  // Display the parsed object on the page
  displayWeather(weatherObj);
}

Finally, make sure to update the HTML generation with the appropriate values:

var html = "<h1>" + weatherObj.queryLocation + " " + weatherObj.queryTime + "</h1>";
html += weatherObj.YYYYMMDD;

By following these steps, you'll be able to seamlessly handle XML data in your web application.

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

Tips for retrieving the value of a table cell when the checkbox in the corresponding row is selected

Within my project, I am utilizing a table. The html code I am using is as follows: <table id="assTB" border="1px" cellspacing="0"> <colgroup> <col style="width:15%"> <col style="width:15%"> <col sty ...

Encountering a Vue syntax error following the binding of a session variable

Encountering a syntax error while attempting to bind a session variable as a prop of my Vue component. Scrutinizing my code did not reveal any mistakes, but perhaps another set of eyes may catch something. This is where I have registered my components: V ...

What are some methods for accessing jQuery ajax result data in Internet Explorer versions 7 or 8?

So, I'm facing an issue with retrieving the resultCount variable in different versions of Internet Explorer. int resultCount = 3; mav.addObject("resultCount", resultCount); This is how my jsp code looks like: $.ajax({ url: ...., type: &ap ...

scraping text content from a CSS node using Scrapy

My goal is to extract a catalog ID number from the following webpage: from scraping.selector import Selector from scraping.http import HtmlResponse url = 'http://www.enciclovida.mx/busquedas/resultados?utf8=%E2%9C%93&busqueda=basica&id=& ...

Reading data from a Node PassThrough stream after writing has finished can be achieved by piping the stream

Is it possible to write to a Node Passthrough stream and then read the data at a later time? I am encountering an issue where my code hangs when trying to do this. Below is a simplified example in Typescript: const stream = new PassThrough(); strea ...

The problem with Ajax POST is occurring in Firefox and Chrome, but not in IE8

I am encountering an issue with the code snippet provided below. Upon executing it in Internet Explorer 8, I receive an alert when the call is successful. However, this behavior does not occur in Firefox and Chrome. In other words, there is no alert disp ...

When trying to locate an item in an array within a VUE application, it may result in

I've got this code snippet that successfully finds the item details in an array: var findGroupId = medias.find(medias => medias.group_name === this.groupName) The medias variable is an array. When I run console.log(findGroupId), I get this result ...

What are some ways to ensure that the promise from postgres is fulfilled before moving forward with my code execution?

I am currently developing a Node-js application that requires retrieving information from the database before making another database call. However, I am facing an issue where the first check is not always resolved before proceeding to the next step. I hav ...

The div is incorrect and causing the label and input to move in the wrong direction

Whenever I try to adjust the position of the current-grade-name-input, the entire grade-point-input moves along with it inexplicably. /* final grade calculator: (wanted-grade - (current-grade * (1 - final%))) / final% Ex: have a 80 an ...

Revise Total Amount in Woocommerce Checkout Using an Ajax Call

Before seeking help on SO, I researched extensively to understand how to make an AJAX request with WordPress. Although my code and request are functioning correctly, they are not achieving the desired outcome. My goal is to update the "Total" value when c ...

Hosting services and content management system for a website built with Twitter Bootstrap

Embarking on a new venture to create a website for a Custom Home Building company, I am eager to learn and grow in web development. Although I have some programming experience, please bear with me as I ask my newbie questions. I have been searching high a ...

Using the data from two input fields, an ajax request is triggered to dynamically populate the jQuery autocomplete feature

I've been struggling with this issue for quite some time now. My goal is to pass 2 arguments (the values of 2 input fields in a form) in my ajax call so I can use them for a jQuery autocomplete feature (the search is based on a MySQL query using the v ...

What is the best way to populate my table with array values entered into an input box using ajax PHP?

I am currently working on a project that involves inserting authors into a table using arrays and AJAX. However, I am facing difficulties with the implementation and conversion process due to my lack of experience in this approach. <input type="text" c ...

What are the potential drawbacks of utilizing setState within the componentDidUpdate method in React?

I am facing a situation where I need to update a child component's state whenever a prop changes. Here is how I have approached it: componentDidUpdate(prevProps) { const { searchValue, searchCriterion } = this.props; if (searchValue !== prevP ...

Utilizing XPath to retrieve text from a hyperlink

I'm currently using Python with Xpath to scrape Reddit, specifically working on extracting links and displaying their titles on the front page. To do this, I'm utilizing the Scrapy framework and conducting tests in the Scrapy shell. I'm stru ...

Converting an unbroken series of string values into organized key-value pairs for easy reference

I assure you this is not a duplicated question. Despite my attempts with JSON.parse(), it seems to be ineffective. Here's the issue at hand: I recently received assistance from an answer that was both crucial and enlightening. However, the code prov ...

How can you fetch data from a PHP file using AJAX before performing a header redirect?

I am currently in the process of adding more dynamism to my website. I have developed a forum from scratch and now I am integrating JavaScript into it. All the PHP backend work is complete. My next goal is to enable user login without having to refresh the ...

Is it possible to close the navigation menu by clicking on a link or outside of the navigation area?

Hey everyone, I've recently dived into the world of web design and encountered my first hurdle. I need your expertise to help me solve this problem. How can I modify my JavaScript to close the NAV element by clicking on one of the links or outside t ...

What is the best way to invoke the datepicker function on all rows of table data that share the 'datepicker' class?

Hey there! I'm working with a table that features a JavaScript function for a datepicker, as well as the ability to add and delete rows. The challenge I'm facing is that each new row created has the same ID as the previous one. How can I ensure t ...

Unable to redirect using JQuery Ajax post after receiving an ActionResult from an MVC controller

I'm trying to send data from a method to an MVC controller that gives back an action result, and then have my site automatically navigate to the correct view. Here's the code snippet I'm currently working with: function RedirectFunction(ite ...