How to Submit Form using JavaScript and Ajax

In this Tutorial I’m using Plain JavaScript to Submit Form using Ajax.

Generally, a Form is Submitted when the user clicks the Submit button and the page gets Refreshed.

But, You can Submit a Form using JavaScript without refreshing the page with Ajax.

I will not use jQuery to Submit form, instead, I am going to use VanillaJS (Plain JavaScript) to Submit Form using Ajax.

Creating HTML Form

First of all, we need to create the Form in HTML and then we will use JavaScript to Submit the Form.

<form id="myForm" action="submit.php" method="POST">
 
</form>

In the above code, I have created an HTML form with an id myForm which will be submitted to “submit.php” file through POST method.

There are two methods available POST and GET.

Adding Input Fields to HTML Form

Now we will add Input Fields to our form.

[moptin id="3100"]
<form id="myForm" action="submit.php" method="POST">
 
  <input type="text" id="username" name="username" placeholder="Username"/>
 
  <input type="password" id="pwd" name="pwd" placeholder="Password"/>
 
  <input type="submit" id="submit_btn" value="Submit"/>
 
</form>

I have created three input fields.

  1. Text Field : Created a Text Input field with id “username”, Placeholder “Username” and name “username”.
  2. Password Field : Created a Password Field with id “pwd“, Placeholder “Password” and name “pwd“.
  3. Submit Button : Create a Submit button with id “submit_btn” and value “Submit“.

Form Submit using JavaScript

Coming to our topic.

As we have created our form, now we need to handle the Form Submission.

So, we will submit the form using JavaScript.

var myForm = document.forms["myForm"];

myForm.onsubmit = function(event){
  event.preventDefault(); //Prevents page from Reloading

  var username = document.getElementById("username"),
  pwd = document.getElementById("pwd");

}

JavaScript provides forms object to Select Form by Id.

I have created a variable myForm to select the Form using JavaScript’s forms object.

Then, I have defined a function to myForm.onsubmit handler.

JavaScript onsubmit() function handles Form Submission without refreshing the page.

And, then I have stored the input fields value in its respective variables.

JavaScript Form Validation

Now, we need to validate the form before submitting it.

var myForm = document.forms["myForm"];

myForm.onsubmit = function(event){
  event.preventDefault(); //Prevents page from Reloading

  var username = document.getElementById("username"),
  pwd = document.getElementById("pwd");

  //Validating Form

  if(username.value==""){

  //Alerting User that Username Field is Empty
  alert("Please Enter a Valid Username"); 

  }else if(pwd.value==""){

  //Alerting User that Username Field is Empty
  alert("Please enter a Valid Password");

  }else{
 
  //We have Validated our Form
  //We can proceed further

  }

}

I am checking the Username and Password field value. If it’s value will be empty, it will alert the user about it else it will proceed further.

You can use your own conditions to validate the form, like validating email, url, etc.

 

Submit Form using Ajax

After Validation of Form, we have to send the data to the server using ajax without refreshing page.

var myForm = document.forms["myForm"];

myForm.onsubmit = function(event){
  event.preventDefault(); //Prevents page from Reloading

  var action = this.getAttribute("action"), //Getting Form Action URL
  method = this.getAttribute("method"); //Getting Form Submit Method (Post/Get)

  var username = document.getElementById("username"),
  pwd = document.getElementById("pwd");

  /* ...Form Validation Code Goes Here... */

  //Submitting Form Using Ajax

  var data = new FormData(myForm);

  var http = new XMLHttpRequest();
  http.open(method,action,true);

  http.onload = function() {
  if (http.status == 200) {
  
  alert("Form Submitted");

  }
  };

  http.send(data); 

};

As I said above, I will use pure JavaScript to Submit Form using Ajax. I’ve not used a single line of jQuery code.

Now Let me define what we have done in the above code.

On the 5th and 6th line, we have stored form action and method attribute value.

And then we have skipped the Form Validation Code.

Then, we have created a new varible formdata instantiating with FormData() Object passing the myForm variable.

After that, I have created a variable http instantiating with XMLHttpRequest() Object.

PHP Code to Receive Form Data

Here’s a simple PHP code to recieve ajax form data.

$username = $_POST['username'];
$pwd = $_POST['pwd'];

//Now you can use these values anywhere in your code.

That’s all.

Hope you like this tutorial.

Shubham Kumar

Hey, I am Shubham and i love Blogging, Coding and exploring new things and obviously sharing my experience with you.

You may also like...

6 Responses

  1. Jorge says:

    ————————English / Ingles———————–

    Thank you! You really helped me.

    Just a couple of little “game-breaker” errors:
    1) It’s “(method, action, true)” instead of “(action, method, true)”.
    2) The function should’ve a parameter (like “…function(e){…”) and use “e.preventDefault();” so the form its not submitted on the traditional way.

    Excuse me about my english, i do what i can 🙂

    ————————Spanish / Español———————–

    Gracias! Realmente me ayudaste!.

    Solo un par de pequeños graves errores:
    1) Debería ser “(method, action, true)” en lugar de “(action, method, true)”.
    2) La función debería tener un parámetro (sería “…function(e){…”) y usar “e.preventDefault();” para que el formulario no sea enviado de la forma “tradicional”.

  2. googol says:

    Dude! You are a liar, it does refresh the page!!!!!!!!!!!!!!!!!!!!!!!!!!!

    • Jorge says:

      Hi, there are a couple of errors, you can check and research, it would be nice if you behave a little more polite to someone sharing knowledge.

  3. googol says:

    Where I can download your code?

    • Jorge says:

      I guest you could just:

      Select the code you wish to “download” -> Right click -> Copy… then go to your files and Right click -> Paste

Leave a Reply

Your email address will not be published. Required fields are marked *