Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

php - How to submit a form with AJAX/JSON?

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

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

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;
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...