How to submit a form using AJAX / JSON?

Currently, my AJAX works as follows:

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

It works fine on code. When I click on the "One" link , one.php is executed , and the line "One" is loaded into the DIV workspace .

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, one.php should print the value of the text field in the workspace of the DIV.

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

How to encode js to submit a form using AJAX / JSON.

thank

+5
4

:

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

.

Ajax :

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

- , - success ( ), load:

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

, , : data .

.

+8

:

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

$.ajaxSubmit jQuery Form. ,

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

, AJAX, .

+2
source

You can submit the form using jQuery $.ajaxas follows:

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

All Articles