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

The issue of not being able to add data to the client is encountered in a local setup involving Socket.io, MSSQL

I have a large dataset that needs to be retrieved from a SQL server using Node.js and then broadcasted to clients in real-time using Socket.IO. I've been successful in fetching the data, but the UI on the client side isn't updating. Although I c ...

403 Forbidden - CSRF Token Not Recognized

I am encountering an issue with Node Express and CSurf - 403 (Forbidden) Invalid csrf token. After reviewing other solutions and attempting all available options, I am still unable to resolve this. The API functions perfectly when tested in Postman. Howe ...

Is there a way to run JavaScript using Selenium and extract information at the same time?

Greetings and thank you for taking the time to read this. I am currently working on a parser that scans hundreds of websites to check if they have a specific module or plugin installed. The main challenge I am facing is determining whether a website utili ...

The dynamic table rows are appearing out of order in the DOM

success: function (data, status) { var header = $("#MainDiv"); header.html(null); var headertemplate = $("<table class='searchlistbody'><tr></th><th>Name</th></tr>"); ...

What is the best way to structure a data object in Javascript or VueJs?

As I work on developing a small application using VueJs, the data I receive is structured in a particular format: { "interactions":[ { "id":14, "user_id":1, "schedule":"2017-06-04 05:02:12", "typ ...

How can I use jQuery to switch the positions of two <div> elements in HTML based on the selection of a dropdown value?

I need to switch the display positions of two <div> containers based on a dropdown value change. Can this be accomplished using jQuery? Here are the two div containers whose display positions need to be interchanged: <div id="first"><p> ...

What is the best way to create and implement custom declaration files that are not available on @types or DefinitelyTyped?

I have encountered a situation where I am using an npm package named foo that is not available on DefinitelyTyped or may be outdated. Despite this, I still want to consume it under stricter settings like noImplicitAny, so I need to create custom definition ...

Filtering an array by a search term

How do you filter an array based on a specific search term? For example, if we have an array [Tom Harry, Tom John, John Glen, Tom Harward] and we search for "Tom H," then only Tom Harry and Tom Harward should be the output. [Tom Harward, Tom Harry]; Usin ...

Using a JavaScript script in my HTML alongside Vue.js is not possible

Hello there! I recently created a Node.js server and now I'm trying to display an HTML file that contains a Vue script which loads data using another method written in a separate JS file. However, when I attempt to load my HTML file in the browser, ...

What is the best way to send pg-promise's result back to the controller in Express?

While working with Ruby on Rails (RoR), I am familiar with the MVC (Model-View-Controller) concept. In this framework, the controller is responsible for receiving data from the model, processing it, and rendering the view. An example of this structure look ...

Is there a way to display a PHP error message while submitting the form asynchronously?

Utilizing phpMailer in combination with AJAX to send emails. The objective is to send the email and then showcase any error messages from submit.php on contact.php Currently, every submission displays "Message sent" even if it was not actually sent. Con ...

ASP.NET Dynamic Slideshow with Horizontal Reel Scrolling for Stunning

I'm curious if there is anyone who can guide me on creating a fascinating horizontal reel scroll slideshow using asp.net, similar to the one showcased in this mesmerizing link! Check out this Live Demo for a captivating horizontal slide show designed ...

Efficiently transferring time values from dynamically created list items to an input box using JavaScript

Is there a way to store a dynamically generated time value from an li element into an input box using JavaScript? I have a basic timer functionality on my website that includes starting, stopping, pausing, taking time snaps, and resetting them. These time ...

Inserting images into a MySQL database using Ajax and file uploads

I am using JQuery Mobile, PHP, and Ajax to upload an image and insert it into a database, but I am facing an issue with inserting the image's name in the database. The result in the database shows "C:fakepathLighthouse.jpg", but I only want to insert ...

CSS margin-left causing issues in Chrome Extension

My current situation is incredibly puzzling, as I am at a loss for what is happening. I developed a Firefox add-on using jQuery and CSS to revamp a website. When attempting to transfer the add-on to Chrome (which was relatively straightforward due to the s ...

The functionality of JSON.stringify involves transforming colons located within strings into their corresponding unicode characters

There is a javascript string object in my code that looks like this: time : "YYYY-MM-DDT00:00:00.000Z@YYYY-MM-DDT23:59:59.999Z" When I try to convert the object to a string using JSON.stringify, I end up with the following string: "time=YYY ...

Electron.js issue: ipcRenderer and ipcMain leading to a white screen problem

I am currently working on a desktop application using Electron, Vue, and Vuetify. However, I have encountered an issue where sending data from the rendererProcess to mainProcess using IPC results in a white blank screen. I'm unsure of what is causing ...

Ensure that Javascript waits for the image to be fully loaded before triggering the Ajax function

function addResource() { var imgIndex = getIndexByImageID(currentDraggedImgID); var newImageID = resourceCollectionSize.length; // Insert the image $('#thePage').append('<img alt="Large" id="image' + newImageID + &a ...

Modifying the width of a jQuery UI dialog from within the dialog box itself

I have designed an ASP.Net web page with a div and iFrame to display another page within it. Now, I am wondering if there is a way to change the width of the dialog from a button inside the dialog itself... Is this achievable? Thank you. ...

Updating a nested property within an array of objects in MongoDB

Storing grades for an online education application using MongoDB. Here is a sample classRoom document stored in my mongoDB database. StudentGradeObjs are kept in an array within a GradeObject. GradeObjs are stored in an array of GradeObjects inside a class ...