Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

php - 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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...