Search code examples
jqueryajaxform

How to handle form submission using ajax (jQuery)


I've a php form

<form action="" method="POST">
    <input id="input1" name="key" type="text">
    <input id="input2" name="name" type="text">
    <button id="btn" type="button">Enter</button>
</form>

I want to submit the form using ajax so this is how I do it

$('#btn').click(function(){
    var input1 = $('#input1').val();
    var input2 = $('#input2').val();
    var pass = 'val1='+input1+'&val2='+input2;
    $.ajax({
        type: "POST",
        url: "process.php",
        data: pass,
        success: function(data){
          //success;
        }
     });
});

My problem is, when the form has several input items, I've to give an id for every item apart from retrieving it's value using $('#input1').val() and I think this is a cumbersome method.

So is there a way better than this to handle the form in ajax, probably which does not needing to give an id for every input item and instead retrieve the values at the processing file using the input item name just like a php normal form submission works using a submit button?


Solution

  • The jQuery Form plugin is very nice to handle such case.