How to submit a form with AJAX/JSON?

2019-01-25 18:27发布

问题:

Currently my AJAX is working like this:

index.php

<a href='one.php' class='ajax'>One</a>    
<div id="workspace">workspace</div>

one.php

$arr = array ( "workspace" => "One" );
echo json_encode( $arr );

ajax.js

jQuery(document).ready(function(){
    jQuery('.ajax').live('click', function(event) {
        event.preventDefault();
        jQuery.getJSON(this.href, function(snippets) {
            for(var id in snippets) {
                jQuery('#' + id).html(snippets[id]);
            }
        });
    });
});

Above code is working perfectly. When I click link 'One' then one.php is executed and String "One" is loaded into workspace DIV.

Question:

Now I want to submit a form with AJAX. For example I have a form in index.php like this.

<form id='myForm' action='one.php' method='post'>
 <input type='text' name='myText'>
 <input type='submit' name='myButton' value='Submit'>
</form>

When I submit the form then one.php should print the textbox value in workspace DIV.

$arr = array ( "workspace" => $_POST['myText'] );
echo json_encode( $arr );

How to code js to submit the form with AJAX/JSON.

Thanks

回答1:

Submitting the form is easy:

$j('#myForm').submit();

However that will post back the entire page.

A post via an Ajax call is easy too:

$j.ajax({
    type: 'POST',
    url: 'one.php',
    data: { 
        myText: $j('#myText').val(), 
        myButton: $j('#myButton').val()
    },
    success: function(response, textStatus, XMLHttpRequest) {  
        $j('div.ajax').html(response);
    }
});

If you then want to do something with the result you have two options - you can either explicitly set the success function (which I've done above) or you can use the load helper method:

$j('div.ajax').load('one.php', data);

Unfortunately there's one messy bit that you're stuck with: populating that data object with the form variables to post.

However it should be a fairly simple loop.



回答2:

Here is my complete solution:

jQuery('#myForm').live('submit',function(event) {
    $.ajax({
        url: 'one.php',
        type: 'POST',
        dataType: 'json',
        data: $('#myForm').serialize(),
        success: function( data ) {
            for(var id in data) {
                jQuery('#' + id).html(data[id]);
            }
        }
    });
    return false;
});


回答3:

Have a look at the $.ajaxSubmit function in the jQuery Form Plugin. Should be as simple as

 $('#myForm').ajaxSubmit();

You may also want to bind to the form submit event so that all submissions go via AJAX, as the example on the linked page shows.



回答4:

You can submit the form with jQuery's $.ajax method like this:

$.ajax({
 url: 'one.php',
 type: 'POST',
 data: $('#myForm').serialize(),
 success:function(data){
   alert(data);
 }
});