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

Categories

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

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

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...