Search code examples
ajaxrequesttrigger.ioforge

forge.request.ajax post data as json


I have begun using trigger.io to make our jQuery mobile web app as a native build. The web app in its current form uses a plugin called janky.post to make cross-domain posts, submitting the data in json format - which is what our PHP based API expects.

I have started using forge.request.ajax instead in the native build which works for all the forms in the app except for one. The request doesn't appear to be submitted as a json encoded object, rather it is a standard $_POST array. This is not so much of a problem as I can modify the API to detect this, but the because the data submitted is multidimensional the method seems to be malforming the array, so that it is not structured as expected.

How do I correct this behavior in order to get the output I desire? Is there anyway for me to force a json submission for the form? If yes, are there any drawbacks to doing this? Would it prevent me from adding file uploads to this form submission in the future?

Example:

To expand on what I mean the process is as follows. On submit, the controllers format the form data into json and pass it to ajax method like so:

window.forge.ajax({
    type: 'POST',
    url: 'foo.com/bar',
    data: data,
    dataType: 'json',
    success: function( response ) {
        /* code omitted */
    });
});

The reason for this is because some of the data in the post doesn't come directly from the form itself, but is provided by additional models. The structure of data being posted is as follows:

{
    id: '23',
    date: '2012-08-30 00:00:00',
    name: 'Foo',
    items: [{
        description: 'Bar',
        quantity: '1',
        price: '20'
    }]
}

But when it is received as an array by our PHP based API the structure is as follows:

array(
    'id' => '23'
    'date' => '2012-08-30 00:00:00',
    'name' => 'Foo',
    'items' => array(
        0 => array( 'description' => 'Bar' ),
        1 => array( 'quantity' => '1' ),
        2 => array( 'price' => '20' )
    )
)

As you can see, each field that corresponds to a single item in the items array has been changed into its own array which is wrong, it should be:

 items = array(
     0 => array(
         'description' => 'Bar',
         'quantity' => '1',
         'price' '20'
     )
 )

Solution

  • As @Connorhd said, this was a bug in how we encoded objects inside arrays: I've fixed now - will deploy by end of week. Sorry for the inconvenience!