Hello I managed to get my submit to send a post request via ajax, but I want to make this asynchronous in case my php-file takes longer to process. I can't seem to wrap my head around the way to async the ajax part. Here is my function 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 send!';
/* append form-values to the formdata s 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 should probably start here..*/
/* object of my http request */
const ajax = new XMLHttpRequest();
/* opneing 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 send.</h2>` */
}else {
this.submitStatus = ajax.responseText;
this.isDisbabled = false;
}
}
}
/* function-call of my promise function */
/* send the request with the appended form data.
executing the load event */
ajax.send(formData);
/* resetting the input-fields to blank after the submit is done. */
this.user_name="";
this.user_email="";
this.user_message="";
}
I appreciate the help!
You could always wrap the AJAX call in an async function like so:
async function ajaxRequest() {
//ajax call here (pass in anything you need)
return result;
}
and then in your main function just await the result:
let ajaxResult = await ajaxRequest();
so the rest of your code won't execute until the ajax call has finished and the result has been received :)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.