Execute JavaScript code once the XMLHttpRequest has completed execution

I'm facing an issue where the JavaScript code is executing faster than the XMLHttpRequest. I am hesitant to resolve it using:

setTimeout(function() {}, 100);

Below is a snippet of my code:

function change_country(id) {

    if (window.XMLHttpRequest) {
        xmlhttp = new XMLHttpRequest();
    }
    else {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }

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

            var data = JSON.parse(xmlhttp.responseText);

            document.getElementById("continent").value = data.continent;
            document.getElementById("country").value = data.country;

        }
        xmlhttp.open("GET", "request_country_change.php?id=" + id, true);
        xmlhttp.send();
    }
}

This excerpt serves as an example and is not part of the original code. It aims to demonstrate a form that undergoes changes. In this scenario, it fetches and populates a select field with all continents, followed by selecting the continent and countries based on the provided id. However, it loads the list in the select fields ahead of running the JavaScript portion.

document.getElementById("continent").value = data.continent;
document.getElementById("country").value = data.country;

The execution order seems off. While placing an alert or setTimeout in between rectifies the problem, I seek alternative solutions to address it.

Answer №1

To achieve the desired outcome, you could include another JavaScript function in the select statement like this:

Here is an example of how it can be done in JavaScript:

function updateCountry(selectedValue){
     document.getElementById("country").value = selectedValue;
}

Let me know if this aligns with what you are looking for.

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

Executing a post request using axios

Having some trouble with a post request using axios and it's refusing to cooperate. Here is the specific request I need to make. This is what I attempted: await axios.post( 'https://api.searchads.apple.com/api/v4/campaigns/XXXX/adgroups/targ ...

Communication between nodes using serial ports in Node.js fails to receive a response from the connected Arduino board

I've been attempting to establish communication between a computer and an Arduino board using node.js. Despite having a simple program, it just doesn't seem to work as expected. The Arduino program (which seems to be working fine) is as follows: ...

Steps for automatically closing a TextPrompt if the end user does not respond within a specific time frame

How can I programmatically close a Prompt in Microsoft Chatbot SDK v4, such as TextPrompt or ConfirmPrompt, and end the dialog after a certain period of time if the user does not reply? I attempted to use setTimeout and step.endDialog but encountered issu ...

Using Three.js to showcase 3 different slices of heatmaps within a 3D environment

I'm working on using Three.js to create a 3D representation of a matrix. Each 2D plane in the matrix should be displayed as a 2D heatmap. Here is an example of what I'm aiming for: https://i.sstatic.net/Kj5yb.png My current obstacle is figuring ...

What is the name of the event triggered when a jQuery UI draggable element is reverting back to its original position?

I am currently using jQuery UI to create a draggable element on my website. I have added a function to the drag event that continuously tracks the position of the element while the user is dragging it. Additionally, I have set revert: true on this element ...

Encountering an error message stating, "Unable to assign value to 'onclick' property"

Currently, I am at a beginner level in Javascript. While working on some exercises, I encountered an issue with the 'onclick' function as mentioned above. Despite going through other queries in this forum, I have not found a solution that works ...

The ng-submit() directive in Angular does not trigger submission when the "Enter" key is pressed in a text field

I have created a basic form using Angular where I want the ng-click function (updateMsg({name: name,room: room})) to be triggered when the user enters a value and then presses enter key. Unfortunately, the current code does not work as expected. The funct ...

Handling conditional statements in JSX

Here is an example of my straightforward component: function Messages(props) { return ( <View> <View style={styles.messageWrapper} > <View style={styles.isNotMine}> <View style={s ...

The following middleware is not functioning properly on a local SSL server

When I run my Nextjs app without SSL using "next dev", the middleware functions as expected without any errors. However, if I attempt to run the app with SSL enabled, an empty middleware function triggers an error. The code for the middleware function (l ...

Showing undefined or null values in React and JavaScript

My goal is to format undefined or null values by italicizing them. If the value is an empty string, it should be displayed as is. If it has a value, that value should also be displayed as is. However, I am encountering an issue where null or undefined val ...

Click the button to trigger an AJAX request that sends the values from the forms within a while loop

Can someone help me figure out how to send input values through AJAX when a button is clicked? Below is my code. Appreciate any assistance. while { <form class="commentform"> <input type="hidden" class="proid" name="proid" value="<?= ...

What is the best way to trigger a snackbar notification when two passwords do not match?

I'm currently developing a full stack application and I am facing an issue with displaying a snackbar in my signup component when the user's password and confirm password do not match. I have been advised to pass the setOpenAlert method as props ...

Access a PHP file using XMLHttpRequest to run additional JavaScript code

My main page, referred to as Main.php, contains a button that triggers the display of results from Results.php within a div (divResults) on Main.php. The HTML content "These Are The Results" returned by Results.php is successfully displayed in the divResu ...

The error "Property 'user' does not exist on type 'Session'." occurred while attempting to pass session data using express-session and accessing req.session.user

I'm currently working on creating a basic login form for users to access a website, where I plan to store their session data in a session cookie. The express-session documentation provides the following example for setting it up: app.post('/login ...

Adjustable value range slider in HTML5 with ng-repeat directive in AngularJs

I am facing a problem with my HTML5 range slider. After setting a value (status) and sending it to the database, when I reload the page the slider's value is always set to '50'. The slider is being generated within an ng-repeat from AngularJ ...

Once the jQuery Ajax call is completed, my goal is to redirect to a different page and display the returned JSON data on that new page

I am working on an index.aspx page that has a search button. When I click on the search button, it triggers jQuery AJAX to retrieve JSON data in the 'success:function(jsondata)' block. Now I want to display this data on the search.aspx page. I am ...

Unable to modify the hover color on the image or icon

After creating a circle icon with an image in the center, I wanted to make the image change colors on hover. The main focus of the icon is the circle itself. In my attempt to achieve this effect, I included the following code for the circle icon: .circle- ...

Will the rel attribute work in all web browsers and with all HTML tags?

Confirming that it is compatible for use with JQuery scripting. ...

Is there a way to retrieve the name of a JSON or obtain the file path using NodeJS Express Router?

I've been experimenting with adding a named routers feature to the Express router for my NodeJS project. I managed to implement it successfully, but there's one thing I'm stuck on... the path. Specifically, when I have a route setup like thi ...

Linking the value of an expression to ngModel

There is a specific scenario where I need the ng-model property to bind to a value retrieved from the database as part of the business logic. To illustrate this concept, I have set up an example function TodoCtrl($scope) { $scope.field1 = "PropertyFr ...