DEV Community

Cover image for Submit Form without refresh using AJAX
pavankumarsadhu
pavankumarsadhu

Posted on • Updated on

Submit Form without refresh using AJAX

Hi all,

Today we will see how to submit form without refreshing page using ajax.

It involves 3 simple steps.

Step 1:

<form method="post" id="myForm" action="" >
<input type="text" placeholder="UserName" id="username" name="username" >
<input type="email" placeholder="UserEmail" id="useremail" name="useremail">
<input type="button" value="Login" onclick="submitForm()" >
</form>
<div id="response" ></div>
Enter fullscreen mode Exit fullscreen mode

Add above HTML simple form, which takes simple information Name & Email. Add an onclick EventListener to button, which will be triggered on click.

Step 2:

<script>
function submitForm()
{
var formData=$('#myForm').serialize();

$.ajax({
type:'post',
data:formData,
success:function(response)
{
$('#response').append(response);
}
});
}
</script>
Enter fullscreen mode Exit fullscreen mode

This is the crucial step where we send data using ajax. Using serialize method, store the form data in a variable, and pass variable as data, in the above mentioned format. Store response on success in a div tag.

Note: Add above javascript code after above HTML Code, otherwise javascript will throw an error.

Step 3:

<?php
if(isset($_POST['username']) && isset($_POST['useremail']))
{

echo "Form Successfully submitted";

exit;
}
?>
Enter fullscreen mode Exit fullscreen mode

Using PHP, On success ,this data will be sent as response, and in javascript we display the response in div tag.

Note: Add above php code at the top of page, if you add in the middle of the page, you will get unnecessary response in div tag.

As ajax to make it work, add below script in head tag.

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
Enter fullscreen mode Exit fullscreen mode

In this way, we can submit form without refresh. In this post, we are just displaying a message to user on submission of form. But we can also increase the complexity by sending mail to user, checking data in db whether user is already registered or not ...

Thanks for taking your valuable time for reading my post, if you have any queries , please leave a comment and will respond. If you find this post useful, please share it.

Read: How to Increase upload limit upto 1000GB in Wordpress using Increase Upload Limit Plugin for LIFETIME Free of Cost?

Social Profile : LinkedIn

Have a Nice Day!

Top comments (0)