Ajax form submit

What we need

  • A html form containing some input fields.
  • jQuery.(I am using jquery-2.1.1.js)
  • JavaScript file(myscript.js) where we will write JavaScript code for form submit.

Now our html code will be like this

<body>
    <script src="jquery-2.1.1.js"></script>
    <form method="post" action="save.php" >
        <input type="file" name="myfile">
        <input type="text" name="name" placeholder="Your Name">
        <input type="submit" value="Save">
    </form>
    <script type="text/javascript" src="myscript.js"></script>
</body>

Now our myscript.js will be like this.

$(document).on("submit", "form", function(event)
{
    event.preventDefault();
    $.ajax({
        url: $(this).attr("action"),
        type: $(this).attr("method"),
        dataType: "JSON",
        data: new FormData(this),
        processData: false,
        contentType: false,
        success: function (data, status)
        {
            //code after success
        },
        error: function (xhr, desc, err)
        {
            //code any error happened
        }
    });
});

Now if we click on the save button or submit the form we will see it will submit the form with Ajax request.
Ajax response will be received by success function to data variable.
This Ajax submit will work for file input too.We can receive files at server side.

Note

  • Only For HTML-5(FormData)supported browsers
  • We can Improve our code without using jQuery
  • To form no need to add attribute  enctype="multipart/form-data"
Bookmark the permalink.

Leave a Reply

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