0

Using the following code, I'm able to generate an array, but I would like to construct a complex JSON object that looks like this:

<script>

    $('document').ready(function() {
        var $myform = $("#myform"),
            $userData = $myform.find('#userInfo'),
            $adressData = $myform.find('#adressInfo'),
            $btnSubmit = $myform.find('button');

        $btnSubmit.on('click', function (event) {
            event.preventDefault();
            var formData = $myform.serializeArray(),
                obj = {};

            for(var i=0;i<$userData.length;i++){
                obj[formData[i].name] = formData[i].value;
            }
            $.ajax({
                url: '/create/user',
                type: 'post',
                contentType: "application/json",
                data: $myform.formAsJson(),
                success:function(){
                    alert("Great! Everything's OK!");
                },
                error: function(){
                    alert("Booo, something wrong :(");
                }

            });
            return false;
        });
    })
</script>

Here is the actual JSON structure that I would like to have:

{
          "firstName" : "first name ",
          "lastName" : "last name",
          "email" : "some@test.com",
          "pass" : "testitbaby",
          "address" : {
            "street" : "street",
            "zip" : "12345",
            "city" : "city",
            "country" : "DE"
          },
          "createDate" : 1445885243494,
          "isUserActivated" : false
        }
joesan
  • 13,963
  • 27
  • 95
  • 232
  • do you want `obj.toString()`? – Ari Nov 02 '15 at 20:35
  • What do you mean by that? – joesan Nov 02 '15 at 20:36
  • it will convert object to string. `obj` is your variable that is containing object. `toString()` is a function which will convert your object to string. – Ari Nov 02 '15 at 20:38
  • But how to get the complex JSON structure in the first place? My code above would not work as it would just produce just an array, but I want the city, zip, street and country nested inside the outer JSON! – joesan Nov 02 '15 at 20:39
  • Why do you need to do it as a JSON object? Most APIs will accept `x-www-form-urlencoded` format, which is what `.serialize()` produces. – Barmar Nov 02 '15 at 20:42
  • oh..., sorry, I thought it was "From", instead of "Form". A bit fuzzy here..! – Ari Nov 02 '15 at 20:45
  • check this out http://stackoverflow.com/questions/1184624/convert-form-data-to-javascript-object-with-jquery – Ari Nov 02 '15 at 20:51

1 Answers1

1

For readability, I would create an object yourself. There's no point in serializing a form into an array if the format of the array is not what you want. And, there's no point in serializing a form into an array, only to loop through it and create an object of the same dataset. You may as well just create a custom object and keep it simple.

var obj = {
    firstName: $('#firstName').val(),
    lastName: $('#lastName').val(),
    address: {
        street: $('#street').val(),
        zip: $('#zip').val()
    }
}

And then, in your AJAX options, use $.param() to serialize the form data for sending. $.param() creates URL encoded strings like name=paparazzoKid&email=papkid@pap.com.

$.ajax({
    url: '/create/user',
    type: 'post',
    data: $.param(obj),
    success:function(){},
    error: function(){}
});

$.param() - "Create a serialized representation of an array, a plain object, or a jQuery object suitable for use in a URL query string or Ajax request."

http://api.jquery.com/jquery.param/

This is a screenshot from JSFiddle with FireBug open. It shows the object I created and the post data that was sent.

enter image description here

To access the POSTed string of parameters in PHP, you would simply do this:

$userStreet = $_POST['address']['street']

If you need JSON format for your server pages, just encode the POST data to JSON on your server page. In PHP, it's a simple as:

json_encode($_POST).

TheCarver
  • 19,391
  • 25
  • 99
  • 149
  • I o not want the parameters to be part of the url. I definitely want this to be part of the POST body! Having these as part of the url parameters is a no go! – joesan Nov 03 '15 at 04:15
  • @sparkr: Where on earth did you get the idea that parameters are in the URL? You can see the URL it requested with '404 not found' next to it - that is the only URL it requested. If it was a GET request, the parameters would be in the URL like you said, not with POST. The URL encoded string it creates (under "source" in my Firebug) is just a URL encoded string of parameters that it posts with the request. – TheCarver Nov 03 '15 at 11:09
  • http://api.jquery.com/jquery.post/ - Under the "data" section it says: "PlainObject or String. A plain object or string that is sent to the server with the request.". The "source" is the string it sends. Mine is a URL encoded string and yours is JSON formatted string - there's no difference. – TheCarver Nov 03 '15 at 11:13
  • I overlooked your post! Sorry about that! – joesan Nov 03 '15 at 11:21
  • @sparkr: no problems, glad I could help out. – TheCarver Nov 03 '15 at 11:28