WordPress Ajax stands for Asynchronous JavaScript and XML. This helps us to load data from the server without refreshing browser page. Ajax is the technique for creating better, faster and more interactive web application with the help of CSS, XML, JavaScript, and HTML.
How to create a contact form using WordPress Ajax?
1. Create an HTML Form
At first, let’s create an HTML FORM that collects data from the user. To create HTML form copy the code below in your index.php file.
<div class="ajax-form"> <div class="container"> <div class=row> <div class="col-md-6 col-md-offset-3 form-box"> <form action="" method="post" class="ajax" enctype="multipart/form-data"> <h1>Ajax Form</h1> <label><b>Name</b></label> <input type="text" placeholder="Enter Your Name" name="name" required class="name"> <label><b>Email</b></label> <input type="email" placeholder="Enter your Email" name="email" required class="email"> <label><b>Message</b></label> <input type="textarea" placeholder="Message" name="message" required class="message"><hr> <div id="msg"></div> <input type = "submit" class="submitbtn" value="submit"> <div class="success_msg" style="display: none">Message Sent Successfully</div> <div class="error_msg" style="display: none">Message Not Sent, There is some error.</div> </form> </div> </div> </div>
The above HTML contains <form> tag which consists, text fields for Name, Email, and Message. To process this form and submit data using AJAX, we need jQuery file which is already inbuilt in the latest WordPress.
2. Using AJAX to submit the form
Now, we are going to use jQuery to handle our AJAX request. Create the file name main.js under the js folder inside your theme folder. In this file, we’ll place code for Ajax call.
Tasleem says
I am facing error page not found when submitting form.
Joe says
That error should be eliminated when you change the dataType to ‘text’ (or just eliminate it). I believe ‘type’ is a typo. :)
Great post. Very helpful!
Mohamed Mostafa says
what if i need to call a link for submit button
for ex: send.php?username=123456789&password=123456789&numbers=123456789&sender=SENDERNAME&message=MESSAGE&unicode=u&return=full
Matthias Radscheit says
Thanks for the article. The first code sample contains too many closing curly brackets.
Dustin Ghia says
Not working… The page reloads without error after submitting, but no email is sent.