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" : "[email protected]",
          "pass" : "testitbaby",
          "address" : {
            "street" : "street",
            "zip" : "12345",
            "city" : "city",
            "country" : "DE"
          },
          "createDate" : 1445885243494,
          "isUserActivated" : false
        }
7
  • do you want obj.toString()? Commented Nov 2, 2015 at 20:35
  • What do you mean by that? Commented Nov 2, 2015 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. Commented Nov 2, 2015 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! Commented Nov 2, 2015 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. Commented Nov 2, 2015 at 20:42

1 Answer 1

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 protected].

$.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).

Sign up to request clarification or add additional context in comments.

5 Comments

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!
@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.
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.
I overlooked your post! Sorry about that!
@sparkr: no problems, glad I could help out.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.