JavaScript used for making an AJAX request

Currently, I am attempting to master the art of making an AJAX call using plain JavaScript with the goal of stepping away from JQuery for a specific project. However, I seem to be encountering a roadblock when it comes to xmlhttp.onreadystatechange. If anyone can provide insight into what I might be doing incorrectly (the function getDVDsAndBluRays() is triggered on DOMContentLoaded), I would greatly appreciate it. Thank you!

function getDVDsAndBluRays() {
  console.log("Successfully logged in");
  var xmlhttp = new XMLHttpRequest();
  var url = 'http://www.omdbapi.com/?t=metropolis&y=&plot=short&r=json';

  xmlhttp.onreadystatechange = function() {
    console.log("Logging unsuccessful");
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
      console.log('responseText:' + xmlhttp.responseText);
      var myMovies = JSON.parse(xmlhttp.responseText);
      myFunction(myMovies);

    }
    xmlhttp.open('GET', url, true);
    xmlhttp.send();
  };
}    

function myFunction(myMovies) {
  for (var i = 0; i < myMovies.length; i++) {
    var title = myMovies[i].Title.toLowerCase().split(' ').join('+');
    var year = myMovies[i].Year;
    console.log(title + ", " + "year");
  }
}

Answer №1

It should be like that, take note of the placement of open and send functions:

function obtainDVDsAndBluRays() {

  console.log("Fetching data");
  var xmlhttp = new XMLHttpRequest();
  var url = 'http://www.omdbapi.com/?t=metropolis&y=&plot=short&r=json';
  xmlhttp.open('GET', url, true);
  xmlhttp.send();

  xmlhttp.onreadystatechange = function() {
    console.log("Not logging");
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
      console.log('responseText:' + xmlhttp.responseText);
      var myMovies = JSON.parse(xmlhttp.responseText);
      analyzeData(myMovies);

    }

  };
}    

function analyzeData(myMovies) {
  for (var i = 0; i < myMovies.length; i++) {
    var title = myMovies[i].Title.toLowerCase().split(' ').join('+');
    var year = myMovies[i].Year;
    console.log(title + ", " + "year");
  }
}

onreadystatechange is triggered after the service call, you were actually "requesting the service when it responds"

Answer №2

Make sure to move your .open() and .send() functions outside of the onreadystatechange() handler. This way, you can ensure that they are executed before any state changes occur in the xmlhttp request.

The onreadystatechange() function is triggered when there is a change in the request state, so it's important to have the open and send functions set up beforehand.

I hope this explanation clears things up for you!

Answer №3

The placement of the open and send calls within the onreadystatechange event handler prevents them from being executed.

To resolve this issue, relocate these calls outside of the event handler.

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

Looking for a way to merge PDF files using an API?

I'm working on a web application that allows users to upload PDF files. I'm trying to find a way to add an additional PDF to the one uploaded by the user, but I haven't been able to solve this task yet. I'm wondering if there's an ...

Is it possible for jQuery to analyze HTML contained within a variable?

Currently, I am utilizing PHP along with an ajax command to retrieve the complete HTML content from an external webpage using the file_get_contents() function in PHP. After storing this HTML in a JavaScript variable, I am curious if it is possible to uti ...

Guidelines for incorporating Angular variables into jQuery scripts

I have a form with an input field that dynamically generates a list of names using Angular. My goal is to turn each name into a clickable link that will submit the form with that specific name as the input value. <form method="POST" action="/results/" ...

Custom Pagination Features and AJAX Data Retrieval in Datatables

I am utilizing Datatables to create a table with my data. From the server side [Java], I am sending JSON responses to JSP and using Datatables js to generate tables in JSP with the same data. When I send 100 records, Datatables automatically enables pagi ...

Uncertainties surrounding the complexity of this multi-stage form

Exploring this multi-step form I have a couple of questions: 1) Is there a way to transfer the value from the first step to the second step of the form? 2) How can I ensure that the datepicker value is not empty (to prevent user progress in the firs ...

Steps for including a URL in an ng-repeat when it is not included in the JSON object

After making a http call, I am getting a JSON object. One of the properties within this object is LinkUrl. Sometimes, LinkUrl will contain a predetermined URL from the returned object, while other times it will only have a file name. In the latter case, I ...

Utilizing Node.js to iterate through arrays grouped by categories

Here is some data I need to work with [ [ '@test','1.2.6-unstable' ], [ '@test','1.3.2-unstable' ], [ '@test','1.4.6-unstable' ], [ '@test2','4.0.1-unstable' ], [ &ap ...

Every time I hit the refresh button, I find myself forcefully logged out

After switching from using localStorage to cookies in my React JS web app, I am experiencing an issue where I get logged out whenever I refresh the page. Even though the cookies are still stored in the browser, the authentication process seems to be failin ...

Issue with Ajax not triggering PHP script

My first experience with using Ajax to call a php script is not going well. The script doesn't seem to be working at all. Here is the snippet of code where I implemented Ajax: <?php if (isset($_GET['error'])) { switch ($_GET[ ...

Puppeteer Alert: Unable to Locate Node for specified selector

When using Puppeteer to interact with an input element on a requested URL, I encountered an issue. First, I entered a quantity like this: await page.type('#bidamount_temp', bidAmount); However, when trying to click on the following button after ...

Is it possible to parameterize the adding of classes in jQuery?

Is it feasible to parameterize the jQuery addClass() function to set specific CSS properties when called? For example, applying a color property to a CSS class when addClass() is invoked? I am relatively new to JavaScript and CSS, so any guidance would be ...

Dealing with JWT management in the absence of Cookies

After doing some research on JSON Web Token (which is a new concept to me), I have learned about its secure mechanism for transmitting information between parties without the need for server Sessions. Currently, I am in the process of building a web app f ...

The UI does not reflect changes to the scope variable after it is updated by a service call

When I add a new item to the scope from another service, the select tag options that come from the service do not reflect the newly inserted value immediately. The new option only appears after refreshing the page. It seems like the scope is not updating t ...

Typescript: Defining the correct return type for resolved parameters in promises

Exploring the world of TypeScript, I recently attempted to convert some basic JavaScript promise samples into TypeScript promises. While working on this conversion process, I encountered an issue that has left me puzzled and unable to find a solution even ...

JavaScript calculator not calculating values correctly

I am facing an issue with my JavaScript calculator. The problem occurs when I try to perform addition, such as adding 5+5, the result gets stuck at 10 and does not continue to increment (10, 15, 20, etc). Below is the code snippet that I am using: func ...

Activate the fadetoggle function to smoothly transition and fade in

Is there a way to implement jQuery fading in when an element becomes visible? Check out this code snippet for reference: http://jsfiddle.net/IntelandBacon/nWscz/ $('.expand').click(function () { $(this).next().css("visibility", "visible"); ...

Combining platform-express and platform-fastify for optimal performance

I am currently working on a NestJS application and my goal is to upload files using the package @types/multer. However, I encountered an issue while following the guidelines from the official documentation: https://i.sstatic.net/JCX1B.png Upon starting ...

Encountering a problem with GraphQL API fetching in Next.js: receiving the error message "React functionality 'useContext' is not supported in this environment."

Currently, I have developed a Next.js 14.2.3 application with a GraphQL API endpoint (which I replaced with localhost for StackOverflow). For data fetching, I am utilizing "@apollo/client": "^3.10.3" and "graphql": "^16.8.1". The product page path has been ...

Troubleshooting Firebase import issue in Node.js, React, and Chakra UI framework

https://i.sstatic.net/ZPTmf.png Running "yarn dev" in my project directory is causing me to encounter this error. The code in firebaseConfig.js looks like this: // Import necessary functions from Firebase SDKs import { initializeApp } from "firebase/app" ...

Display endless data within a set window size

I am looking to create a fixed-size window for displaying text from the component <Message/>. If the text is longer, I want it to be scrollable within the fixed window size. See screenshot below: Screenshot export default function AllMessages(){ ...