example of form submit with ajax

by Gerald Gillespie

HTML

put cursor in either box hit enter to submit. hit multiple times if you want
<br/>
<form id="beta_signup_form" action="/echo/json/">
    <input type="text" name="beta" value="from beta" size="100" width="100%" />
</form>
<hr/>
<form id="twitter_sign_up" action="/echo/json/">
    <input type="text" name="twitter" value="from twitter" size="100" width="100%" />
</form>
<hr/>log box:
<br/>
<textarea id="log" cols=60 rows=30></textarea>

JavaScript

var valuesToSubmit = function ($e) {
    var o = {};
    $e = $e.find('input:first');
    if( $e.length == 0 ){ throw $.error('error'); return false; }
    o[$e.attr('name')] =$e.val() ;
    console.log(o);
    console.log(JSON.stringify(o));
    return {
        json: JSON.stringify(o),
        delay: 3
    };
}

function appendLog(str,extra){
var $log = $('#log');
    extra = extra ? '\n' : '';
    $log.val( $log.val() +'\n' +str+extra );
}

$(document).ready(function () {
    $('#beta_signup_form').submit(function () {
        var // valuesToSubmit = $(this).serialize(),
        $this = $(this);
        console.log($this.attr('action'));
        $.ajax({
            type: 'POST',
            dataType: 'json',
            url: $this.attr('action'), // what
            data: valuesToSubmit($this),

            }).done(function (data) {
            console.log("in the beta signup form success function!!!!");
            appendLog('from ' + $this.attr('id'),true);
            for(key in data){
                appendLog( key + ': '+data[key]);
            }
        })
            .fail(function () {
            console.log("--------> beta signup modal callback error");
        });
        return false; // prevents normal behaviour
        });
    });


$(document).ready(function () {
    $('#twitter_sign_up').submit(function () {
        var // valuesToSubmit = $(this).serialize(),
        $this = $(this);
        console.log($this.attr('action'));

        $.ajax({
            url: $this.attr('action'), // $(this).attr('action'), //submits it to the given url of the form
            data: valuesToSubmit($this),
            dataType: "json", // you want a difference between normal and ajax-calls, and json is standard
            type: 'POST'
        }).done(function (data) {
            console.log("in success for modal B...");
            appendLog('from ' + $this.attr('id'),true);
            for(key in data){
                appendLog( key + ': '+data[key]);
   ...