Is there a way to loop through XMLHttpRequest?

There are two files in my project: one file contains PHP code (which is functioning correctly) and the other file contains JavaScript code. The issue lies within the JavaScript file:

function calcDistance() {
    var city = $("#txtpartenza").val();

    $.ajax({
        type: "POST",
        url: 'showDepartures.php',
        dataType: "json",
        success: function (data) {
            $.each(data, function (index) {
                var departure = data[index];
                findGeo(city, departure);
            });
        }
    });
}

function findGeo(departure, destination) {
    var latDeparture;
    var lonDeparture;
    var latDestination;
    var lonDestination;

    console.log(departure);          
    console.log(destination);        

    var xmlhttpDeparture = new XMLHttpRequest();
    var xmlhttpDestination = new XMLHttpRequest();

    xmlhttpDeparture.open("GET", "https://geocoder.cit.api.here.com/6.2/geocode.json?searchtext="+departure+"&app_id=[APP_ID]&app_code=[APP_CODE]&gen=8", true);
    xmlhttpDestination.open("GET", "https://geocoder.cit.api.here.com/6.2/geocode.json?searchtext="+destination+"&app_id=[APP_ID]&app_code=[APP_CODE]&gen=8", true);

    xmlhttpDeparture.send();
    xmlhttpDestination.send();

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

                    var resDeparture = JSON.parse(xmlhttpDeparture.responseText);

                    latDeparture = resDeparture.Response.View[0].Result[0].Location.DisplayPosition.Latitude;
                    lonDeparture = resDeparture.Response.View[0].Result[0].Location.DisplayPosition.Longitude;

                    var resDestination = JSON.parse(xmlhttpDestination.responseText);

                    latDestination = resDestination.Response.View[0].Result[0].Location.DisplayPosition.Latitude;
                    lonDestination = resDestination.Response.View[0].Result[0].Location.DisplayPosition.Longitude;

                    console.log(latDeparture);
                }
            };
        }
    };
}

The Ajax function is functioning as expected; I am able to call findGeo(city, departure) without any issues. However, within the findGeo(departure, destination) function, the XMLHttpRequest for "departure" is encountering problems. The variable latDeparture is not being printed in the console and the code inside the

xmlhttpDeparture.onreadystatechange = [...]
block is not being executed.

Just to provide a full picture, here is the essential part of the PHP file:

$i = 0;
$city = array();

while ($rows = $result->fetch_assoc()) {
    $city[$i] = $rows['departure'];
    $i=$i+1;
}
echo json_encode($city);

Answer №1

After thorough investigation, I have successfully identified the issue at hand.

It has come to my attention that the implementation of preventDefault is crucial in the initial line of the event handler for on('submit'...

Fortunately, I have devised a solution to rectify this issue:

$('form').on('submit', function (e) {

    e.preventDefault();

    [...]

Answer №2

It seems like the issue could be related to nested onreadystatechange statements causing a delay in responses. However, it appears that the second request is dependent on the response from the first request. You can try making the following change:

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

          xmlhttpDest.open("GET", "https://geocoder.cit.api.here.com/6.2/geocode.json?searchtext=" + destinazione + "&app_id=[APP_ID]&app_code=[APP_CODE]&gen=8", true);
          xmlhttpDest.send();
          xmlhttpDest.onreadystatechange = function() {
             //  your code
                  console.log(latPartenza);
              }

          };
      }
  };

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

Finding the correct path for ts-loader with webpack version 2.2.1 within a script

When running the gulp task below, I encounter an error: Module not found: Error: Can't resolve 'app.ts' in 'wwwroot/js/admin' gulp.task("admin:js", function (done) { module.exports = { context: "wwwroot/js/admin", ...

Troubleshooting: Issue with detecting keypress using jQuery

Currently, I have a jQuery script that checks password strength and changes an image source based on complexity. The functionality works smoothly within jsFiddle (set to jQuery 1.91), but when implemented on my webpage, the event seems to not be triggered. ...

Ways to send data to a popup in svelte

Hey there, I could really use some assistance with my Svelte app. I'm trying to implement a modal and pass a parameter to the modal component in order to customize its content. However, when using the open() function of Modal, we only need to provide ...

Filtering with AngularJS based on integer comparison will assist in stream

Currently, I have implemented a "price" field on my website using the JQuery-UI slider. This field comprises of two integer values: minPrice and maxPrice. Suppose I possess an array of objects structured in this manner: objarr=[ { 'name'=&ap ...

Activate and deactivate button

I've tried multiple examples on this site for enabling and disabling a button using javascript with jquery, but none of them seem to work for me. Here is my current dilemma: <asp:TextBox ID="mytext" runat="server" onkeyup="enableButton(this, 3)"/ ...

Survey with results routing based on rating

I am looking to incorporate a basic survey on my website featuring a few multiple choice questions. Each question will be assigned a score, and upon completing the survey, users will be redirected to a personalized page based on their overall score. Doe ...

Creating a Copy to Clipboard feature in React can be achieved by transferring data from an h1 tag to an input field

I'm trying to extract data from an API into an h1 tag in my app. Is there a way for me to easily copy this data and paste it into an input field? Any help would be greatly appreciated. Thanks! ...

Executing JavaScript functions within static files in Django

I can't figure out why I'm unable to invoke a javascript function when clicking my Bootstrap button in a Django project. In my directory, I have set up the static folder as "main/static/main/js/script.js". While I can successfully load the stati ...

Unable to make a post using vue.js

I am facing an issue while trying to submit form data using "vue-resource" in my code. The error message I receive mentions a problem with the use of this method alongside vue-cli and vuetify. Error [Vue warn]: Error in v-on handler: "TypeError: this.$h ...

Retrieving Information with the Fetch API in Node.js and Storing it in a MongoDB Database

I'm a newcomer to mongooseDB and am currently experimenting with inserting data from an API into the database. It successfully creates the Collection, but unfortunately it is not generating the documents. Any suggestions on what I might be doing incor ...

Choose a specific option from the dropdown menu using a URL parameter

After reviewing this code snippet: <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script> // <![CDATA[ $(document).ready(function() { // Parse your query parameters here, and assi ...

Update and republish an outdated npm package

After successfully publishing an npm package, I attempted to make an update which unfortunately resulted in some issues. It seems that I made a mistake during the build process. Since it had been a year since my last update, I have forgotten the exact step ...

Firebase's push() method compared to Angularfire's $save() operation

When comparing angularfire .$save() to firebase .push(), what are the differences? I understand that push() generates a unique key when data is stored, but I'm having trouble replicating this behavior with angularfire. Should I stick to using .push() ...

How to bring in images from a local source in a React.js file

I've been looking into relative paths and absolute paths, but I'm having trouble importing local images correctly. My main objective is to create a React slideshow using these images. Why does it keep trying to find the images in the "components" ...

Create an interactive and responsive user interface for Object using the Angular framework

After receiving a JSON Object from an API call with multiple string values, I need to create an Interface for this Object in the most efficient way possible. Rather than manually writing an Interface with 100 keys all of type string, is there a quicker a ...

Is it possible for me to generate values using PHP that can be easily read by JavaScript?

I'm currently building a website and I am facing some challenges when trying to incorporate JavaScript for real-time calculations. Here are my issues: Is there a more efficient way to avoid manually typing out the code for each level up to 90, lik ...

The ng-bind directive is functional when used with a textarea element, but it does not work with

Recently diving into the world of angularjs, I stumbled upon ng-bind and its interesting functionality when used as a directive for textarea: <input type="text" ng-model="review.start"/> <textarea ng-bind="review.start"> </textarea> I ...

React higher order component (HOC) DOM attributes are causing the error message 'Unknown event handler property' to be triggered

I recently created a Higher Order Component (HOC) using recompose, but I'm encountering a React Warning every time the props are passed down. Warning: Unknown event handler property `onSaveChanges`. It will be ignored. All my properties with a speci ...

Is there a way to transfer non-string parameters from JavaScript to a Java .jar file?

In my AngularJS application, I want to call a .jar file to handle the uploading of images/files. The idea is for Angular to send blob data (image information) to the .jar, along with the folder name where the image should be stored. My Java method would r ...

Angular JS Retrieving Data in the Background with the Assistance of $timeout or $interval Service

Looking to fetch data from a webapi in the background using either the $timeout or $interval service in Angular JS. I have some concerns about how the $timeout and $interval services work. I've run into issues when incorporating these services into m ...