Performing an asynchronous POST request in JavaScript

Hey there, I successfully managed to implement a post request using ajax for my submit functionality. However, I am now looking to make this asynchronous to account for any delays in processing by my php file. Unfortunately, I am struggling to figure out how to integrate the asynchronous aspect with ajax in my function. Here is what I have so far:

submitForm(e) {

        console.log(e);

        e.preventDefault();
        /* to prevent double submitting the form after the first submit*/
        /* submitBtn.disbabled = true; */
        this.isDisabled=true;
        this.submitStatus = 'Successfully sent!';



        /* append form-values to the formdata so I can push it to my .php file */
        const formData = new FormData();
        formData.append('user_name', this.user_name);
        formData.append('user_email', this.user_email);
        formData.append('user_message', this.user_message);

        /* async function implementation should probably start here..*/
        

        /* object of my http request */
        const ajax = new XMLHttpRequest();

        /* opening my connection */
        ajax.open('POST', this.url);

        ajax.onreadystatechange = function() {
            /* if state is send and status is ok */
            if(ajax.readyState === 4 && ajax.status === 200) {
                if (ajax.responseText === "success") {
                /*  contactForm.innerHTML = `<h2>Thank you, ${contactName}, your message has been sent.</h2>` */
                }else {
                    this.submitStatus = ajax.responseText;
                    this.isDisbaled = false;
                }
            }
        }

        /* call to my promise function goes here */
        

        /* sending the request with the appended form data 
        and executing the load event */
        ajax.send(formData);

        /* resetting the input-fields to blank after the submit is completed */
        this.user_name="";
        this.user_email="";
        this.user_message="";
    }

Your assistance on this matter would be greatly appreciated!

Answer №1

To ensure that your AJAX call is properly executed, consider wrapping it in an asynchronous function like this:

async function makeAjaxRequest() {
   // Make the AJAX call here (include any necessary parameters)
    return response;
}

In your main function, simply await the result of the AJAX request:

let ajaxResponse = await makeAjaxRequest();

This way, the following code will not run until the AJAX call is completed and the response has been received :)

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

Combining CSS and JS files for accordion list - experiencing issues when used separately

Recently, I've been trying to create an accordion list and stumbled upon some code (HTML, CSS, and JS) on www.w3schools.com. When I have the code all in one document and run it as a single .html file, everything works perfectly. However, when I split ...

The operation malfunctions if the variable input is below 50, causing it to produce inaccurate results

The function "calcFinalTotal()" was created to calculate the post-tax discount on a purchase of items that were previously totaled and stored in an input tag with the ID of "totaltaxamount". This function applies a 10% discount to orders between $50 to $ ...

According to Intelijj IDEA, the success function in the AJAX request is reported as unused

I've encountered an issue and I'm unsure of the cause. This is my code for testing AJAX requests: function sendAJAX() { var dataToSend = {}; dataToSend["username"] = $("#username").val(); dataToSend["age"] = $("#age").val(); data ...

Having trouble with Vue component registration repeatedly failing

Currently, I am working on a front-end project using [THIS VUE TEMPLATE][https://www.creative-tim.com/product/vue-material-dashboard-pro] The issue I am facing involves trying to register a component locally and encountering the following error: "1 ...

Can you explain the definition of "mount" in the context of Express?

Currently diving into the world of Express.js, I stumbled upon this definition: "An Express router offers a limited set of Express methods. To initialize one, we call the .Router() method on the main Express import. To utilize a router, we mount it a ...

Having difficulty initializing jQuery DataTables upon button click with an Ajax request

I have a piece of HTML code that represents a partial view: <table id="table_id" class="table table-inverse"> <thead class="thead-inverse"> <tr> <th>Select</th> ...

Guide to iterating through an object and generating child components in React.js

Struggling with a React.js loop through child component issue as a newcomer to the language. I have an object and want to create child components from its values. Any help would be greatly appreciated. var o = { playerA: { name: 'a', ...

Having trouble displaying HTML UL content conditionally in Reactjs?

My goal is to display a list of items, limited to a maximum of 5 items, with a "more" button that appears conditionally based on the number of items in the list. However, I am encountering an issue where passing in 5 li items causes them to be rendered as ...

Combining a local URL with an absolute URL through jQuery AJAX

Currently, we are utilizing jQuery Ajax for a service get call: $.ajax({ url: _sbUrl + "gates/1.0/sweeps/getVehicleDetails/" + request.data.regn_no, method: "GET", success: function(response) { if (200 === response.statusCode) { if (typeof ...

Launching a new tab with a specific URL using React

I'm attempting to create a function that opens a new tab with the URL stored in item.url. The issue is, the item.url property is provided by the client, not by me. Therefore, I can't guarantee whether it begins with https:// or http://. For insta ...

Tips for extracting Stripe response post payment using a client-side-only integration

My current component handles sending a payment order to my stripe account on the client-side. Everything seems to be working fine, but I'm struggling to find a way to retrieve the response or token from stripe containing the order details, which I nee ...

Creating separate versions (development and production) of JavaScript code: a step-by-step guide

I have been working on a small web application that is distributed in a Docker container, using an nginx image. This application consists of plain html and js code, without any frameworks. Within the JS code, there is access to a remote host via WebSocket ...

Is it feasible to utilize a variable as a function within JavaScript programming?

I've been diving into the world of express.js and came across these statements. const express = require('express'); const app = express(); It's intriguing how we can call the variable "express" as a function by simply adding parenthese ...

javascript popup appears twice in IE when using PHP

After testing this script on multiple browsers, an issue arises when using IE. In all other browsers, the form submission alert only appears once. However, in Internet Explorer, the alert pops up twice. What could be causing this discrepancy? <!DOCTYP ...

Testing the mongoose.connect callback method in Jest: A step-by-step guide

Currently working on a new Express application and utilizing Jest as the testing framework. All sections of code have been successfully covered, except for the callback of the mongoose.connect method: I attempted to spy on the connect method of the mongo ...

Is the callback of $.post not being executed until the loop it's contained in finishes?

I'm working on a stock table that allows users to input the quantity of stock to issue. I have a function that verifies whether or not the database has sufficient stock for each entry in the table. When debugging through the code in Chrome, I noticed ...

Adding a listener to an element within a loop

I'm currently exploring a way to add an event listener in my script. Here's the variable I have: var inputs = data.context.find(':input').not(':button'); Following that, I have a FOR loop where I utilize this variable to ap ...

Adjusting the options in the subsequent dropdown menu based on the selection made in the initial dropdown menu

I am currently working on select boxes where values are dynamically added through an array. For example, if I have 4 values in the first select box, I only want to display 3 values in the second select box, excluding the value that has already been selecte ...

Properly handling the use of single and double quotation marks in variable declarations within a JavaScript file

I have a search box where users can enter their search text. For example, they can type book, 'book', or "book". The value entered in the search box is then assigned to a variable in the JavaScript file. var searchTerm = "${searchTerm}"; <br/ ...

What sets apart initializing an Express app using "app = new Express()" compared to "app = express()"?

Throughout my experience, express apps have always been initialized like this: var express = require('express') var app = express() However, today I came across an example where a new operator was used: var Express = require('express&apos ...