<!DOCTYPE html>
<html>

<head>
  <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js" data-semver="2.1.1" data-require="jquery@*"></script>
  <script src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js" data-semver="3.1.1" data-require="bootstrap@3.1.1"></script>
  <script src="//cdnjs.cloudflare.com/ajax/libs/jquery-mockjax/1.5.3/jquery.mockjax.min.js"></script>
  <script src="script.js"></script>
  <script src="jquery-form-serializer.js"></script>

  <link href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet" data-semver="3.1.1" data-require="bootstrap-css@3.1.1" />
  <link rel="stylesheet" href="style.css" />
</head>

<body>
  <h1>How to send bootstrap form using ajax request</h1>
  <div class="container">
    <div class="well">
      <form id="ajaxForm" class="form-vertical" role="form" autocomplete="off" method="POST" action="/ajaxRequest/">
        <fieldset>
          <div class="col-xs-12">
            <button class="btn btn-default pull-right" id="defaultData">Fill default data</button>
          </div>
          <div class="form-group col-xs-12 col-sm-6">
            <label for="firstname" class="control-label">First Name</label>
            <input type="text" class="form-control" name="firstname" id="firstname" placeholder="Enter First Name">
          </div>
          <div class="form-group col-xs-12 col-sm-6">
            <label for="lastname" class="control-lable">Last Name</label>
            <input type="text" class="form-control" name="lastname" id="lastname" placeholder="Enter Last Name">
          </div>
          <div class="form-group col-xs-12 col-sm-12">
            <label for="address" class="control-label">Address</label>
            <input type="text" class="form-control" name="address[street]" id="address_street" placeholder="Your street">
          </div>
          <div class="form-group col-xs-6 col-sm-6">
            <input type="text" class="form-control" name="address[city]" id="address_city" placeholder="Your city">
          </div>
          <div class="form-group col-xs-6 col-sm-6">
            <input type="text" class="form-control" name="address[zip]" id="address_zip" placeholder="Your zip code">
          </div>
          <div class="col-xs-12">
            <label class="control-label" for="emails">Email:</label>
            <div class="control-group" id="emails">
              <div class="controls">
                <div class="entry input-group form-group">
                  <span class="input-group-addon">@</span>
                  <input class="form-control" name="emails[0]" placeholder="add email" type="text">
                  <span class="input-group-btn">
                    <button class="btn btn-success btn-add" type="button">
                      <span class="glyphicon glyphicon-plus"></span>
                  </button>
                  </span>
                </div>
              </div>
            </div>
            <small>Press <span class="glyphicon glyphicon-plus gs"></span> to add another email :)</small>
          </div>
          <div class="pull-right">
            <br>
            <div class="btn-group col-xs-12">
              <button type="button" class="btn btn-default" id="sendQueryString">Query string</button>
              <button type="button" class="btn btn-primary" id="sendSerialized">Serialized form</button>
              <button type="button" class="btn btn-warning" id="sendPlainJSon">Plain json</button>
              <button type="button" class="btn btn-success" id="sendTreeJSon">Tree json</button>
            </div>
          </div>
        </fieldset>
      </form>
    </div>
  </div>
  <div class="container">
    <div class="well col-xs-12">
      <div class="control-label col-xs-12">
        <label>Data sent:</label>
      </div>
      <div class="col-xs-12">
        <textarea class="form-control" readonly id="dataSent">here: data sent...</textarea>
        <br>
      </div>
      <div class="control-label col-xs-12">
        <label>Result:</label>
      </div>
      <div class="col-xs-12">
        <textarea class="form-control" readonly id="results">Waiting to send request</textarea>
      </div>
    </div>
  </div>
</body>

</html>
$(document).ready(function() {

  function ajaxCallRequest(f_method, f_url, f_data) {
    $("#dataSent").val(unescape(f_data));
    var f_contentType = 'application/x-www-form-urlencoded; charset=UTF-8';
    $.ajax({
      url: f_url,
      type: f_method,
      contentType: f_contentType,
      dataType: 'json',
      data: f_data,
      success: function(data) {
        var jsonResult = JSON.stringify(data);
        $("#results").val(unescape(jsonResult));
      }
    });
  }
  
  $(document).on('click', '.btn-add', function(event) {
    event.preventDefault();
    var controlForm = $('.controls');
    var currentEntry = $(this).parents('.entry:first');
    var newEntry = $(currentEntry.clone()).appendTo(controlForm);
    newEntry.find('input').val('');
    controlForm.find('.entry:not(:last) .btn-add')
            .removeClass('btn-add').addClass('btn-remove')
            .removeClass('btn-success').addClass('btn-danger')
            .html('<span class="glyphicon glyphicon-minus"></span>');
            
    var inputs = $('.controls .form-control');
    $.each(inputs, function(index, item) {
      item.name = 'emails[' + index + ']';
    });
  });
  
  $(document).on('click', '.btn-remove', function(event) {
    event.preventDefault();
    $(this).parents('.entry:first').remove();
    var inputs = $('.controls .form-control');
    $.each(inputs, function(index, item) {
      item.name = 'emails[' + index + ']';
    });
  });
  
  $(document).on('click', '.btn-remove', function(event) {
    e.preventDefault();
    alert('remove');
  });

  $("#sendQueryString").click(function(event) {
    event.preventDefault();
    var form = $('#ajaxForm');
    var method = form.attr('method');
    var url = form.attr('action') + 'queryString/';
    var data = $(form).serialize();
    console.log(data);
    ajaxCallRequest(method, url, data);
  });
  $.mockjax({
    url: '/ajaxRequest/queryString/',
    type: 'POST',
    contentType: 'text/json',
    responseTime: 0,
    response: function(settings) {
      var data = settings.data;
      var arrayData = data.split('&');
      var jsonData = {}, paramvalue = '';
      for (i = 0; i < arrayData.length; i++) {
        paramvalue = arrayData[i].split('=');
        jsonData[paramvalue[0]] = paramvalue[1];
      }
      this.responseText = jsonData;
    }
  });

  $("#sendSerialized").click(function(event) {
    event.preventDefault();
    var form = $('#ajaxForm');
    var method = form.attr('method');
    var url = form.attr('action') + 'serialized/';
    var arrayData = $(form).serializeArray();
    var data = JSON.stringify(arrayData);
    
    console.log(data);
    ajaxCallRequest(method, url, data);
  });
  $.mockjax({
    url: '/ajaxRequest/serialized/',
    type: 'POST',
    contentType: 'text/json',
    responseTime: 0,
    response: function(settings) {
      var data = settings.data;
      this.responseText = data;
    }
  });

  $("#sendPlainJSon").click(function(event) {
    event.preventDefault();
    var form = $('#ajaxForm');
    var method = form.attr('method');
    var url = form.attr('action') + 'plainjson/';
    var jsonData = {};
    $.each($(form).serializeArray(), function() {
      jsonData[this.name] = this.value;
    });
    var data = JSON.stringify(jsonData);
    console.log(data);
    ajaxCallRequest(method, url, data);
  });
  $.mockjax({
    url: '/ajaxRequest/plainjson/',
    type: 'POST',
    contentType: 'text/json',
    responseTime: 0,
    response: function(settings) {
      var data = settings.data;
      this.responseText = data;
    }
  });

  $("#sendTreeJSon").click(function(event) {
    event.preventDefault();
    var form = $('#ajaxForm');
    var method = form.attr('method');
    var url = form.attr('action') + 'treejson/';
    var jsonData = $(form).serializeObject();
    console.log(jsonData);
    ajaxCallRequest(method, url, jsonData);
  });

  $.mockjax({
    url: '/ajaxRequest/treejson/',
    type: 'POST',
    contentType: 'text/json',
    responseTime: 0,
    response: function(settings) {
      var data = settings.data;
      this.responseText = data;
    }
  });
  
  $("#defaultData").click(function(event) {
    event.preventDefault();
    $('#firstname').val('Mortadelo');
    $('#lastname').val('Filemon');
    $('#address_street').val('Rua del Percebe 13');
    $('#address_city').val('Madrid');
    $('#address_zip').val('28010');
    $("[name='emails[0]']").val('superintendencia@cia.es');
  });

});

/* Styles go here */

### Some of the topics covered in this sample:
1. Bootstrap forms
2. Complex structure data:
  3. Fields using numerical indexed keys: field[0], field[1], ...
  4. Fields using nested keys: field[key1][key11], field[key1][key12], ...
5. Dynamic input field creation
6. Form serialization to JSon object:
  7. JQuery query string serialization
  8. JQuery standard serialization
  9. JQuery enhance serialization
  10. Custom json serialization
11. Faking ajax request
Copyright (c) 2014, Miguel Maquieira
All rights reserved.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
 - Redistributions of source code must retain the above copyright notice, this 
 list of conditions and the following disclaimer.
 - Redistributions in binary form must reproduce the above copyright notice, this
list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
 - The names of its contributors will not be used to endorse or promote products
derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE
/*
Copyright (c) 2011 Paul Macek

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

https://github.com/macek/jquery-serialize-object
*/

(function($) {
  $.fn.serializeObject = function() {

    var self = this,
      json = {},
      push_counters = {},
      patterns = {
        "validate": /^[a-zA-Z][a-zA-Z0-9_]*(?:\[(?:\d*|[a-zA-Z0-9_]+)\])*$/,
        "key": /[a-zA-Z0-9_]+|(?=\[\])/g,
        "push": /^$/,
        "fixed": /^\d+$/,
        "named": /^[a-zA-Z0-9_]+$/
      };
      
    this.pair = function(base, key, value) {
      base[key] = value;
      return base;
    };

    this.push_counter = function(key) {
      if (push_counters[key] === undefined) {
        push_counters[key] = 0;
      }
      return push_counters[key]++;
    };

    $.each($(this).serializeArray(), function(index, item) {

      // skip invalid keys
      var name = item.name;
      if (!patterns.validate.test(name)) {
        return;
      }

      var key;
      var keys = name.match(patterns.key);
      var value = item.value;
      var reverse_key = name;

      while ((key = keys.pop()) !== undefined) {

        // adjust reverse_key
        reverse_key = reverse_key.replace(new RegExp("\\[" + key + "\\]$"), '');

        // push
        if (key.match(patterns.push)) {
          value = self.pair([], self.push_counter(reverse_key), value);
        }

        // fixed
        else if (key.match(patterns.fixed)) {
          value = self.pair([], key, value);
        }

        // named
        else if (key.match(patterns.named)) {
          value = self.pair({}, key, value);
        }
      }

      json = $.extend(true, json, value);
    });

    return json;
  };
})(jQuery);