Search code examples
phpjqueryajaxformssubmission

Form submit without refresh using jquery/ajax if page have more than one form


Hi all I know that its very easy to submit a form without refreshing if there is only one form on the page but what about if there are more than one form on the page. Im using the following code for form submission and it works ok if there is only one form on the page. How can I change it to make it work when there are multiple forms on the page. Thanks in advance.

function processForm() { 
        $.ajax( {
            type: 'POST',
            url: form_process.php,
            data: 'user_name=' + encodeURIComponent(document.getElementById('user_name').value),
            success: function(data) {
                $('#message').html(data);
            }
        } );
}

<form action="" method="post" onsubmit="processForm();return false;">
<input type='text' name='user_name' id='user_name' value='' />
<input type='submit' name='submit' value='submit'/>
</form>
<div id='message'></div>

Solution

  • Just customize your function and add params like formid to get form data within the function to pass processForm("id of the form");

    function processForm(formId) { 
        //your validation code
        $.ajax( {
                type: 'POST',
                url: form_process.php,
                data: $("#"+formId).serialize(), 
                success: function(data) {
                    $('#message').html(data);
                }
            } );
        }
    
    <form action="" id="form1" method="post" onsubmit="processForm('form1');return false;">
    <input type='text' name='user_name' id='user_name' value='' />
    <input type='submit' name='submit' value='submit'/>
    </form>
    
    <form action="" id="form2" method="post" onsubmit="processForm('form2');return false;">
    <input type='text' name='user_name' id='user_name' value='' />
    <input type='submit' name='submit' value='submit'/>
    </form>
    <form action="" id="form3" method="post" onsubmit="processForm('form3');return false;">
    <input type='text' name='user_name' id='user_name' value='' />
    <input type='submit' name='submit' value='submit'/>
    </form>
    <div id='message'></div>