How to post json with amplify

1,372 views
Skip to first unread message

Ian Mckay

unread,
Nov 29, 2011, 9:49:42 PM11/29/11
to Amplify
Hi,

I have the following request

amplify.request.define("checkout#update", "ajax", {
url: "checkout/update/{orderId}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8"
});

I then use the request as so

amplify.request("checkout#update", { orderId: this.orderGuid(), items:
JSON.stringify(data) }, function (result) {
alert(data);
});

Which I would like to post JSON to my controller. Instead it is
posting url encoded values which breaks model binding. I have this
working with JQuery as so

$.ajax({
type: "POST",
url: 'checkout/update/' + this.orderGuid(),
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify(data),
success: function (data) {
alert(data);
}
});

This posts the json string back but amplify seems to get in the way,
unpack the json string and urlencode it. Any idea what i'm doing
wrong?

Thanks,

Ian

Eric Strathmeyer

unread,
Dec 6, 2011, 2:24:32 PM12/6/11
to ampl...@googlegroups.com
Hi Ian,

Have you tried not stringifying your data before you pass it off to Amplify?

amplify.request("checkout#update", { 
    orderId: this.orderGuid(), 
    items: data
  }, function (result) {
       alert(data);
});

I'm not sure if that will make a difference, but it's worth a try.

If that doesn't help, set up a JS Fiddle to show the expected/actual behavior, and we can help debug!

Ian Mckay

unread,
Dec 19, 2011, 2:01:49 PM12/19/11
to Amplify
Hi Eric,

Here is a fiddle. You can see that using jquery the request is made
and is sent as json. The amplify request sends as a url encoded string
with exactly the same data.

http://jsfiddle.net/Dvmna/5/

Thanks,

Ian

Ted Elliott

unread,
Dec 12, 2013, 7:39:46 PM12/12/13
to ampl...@googlegroups.com
You can subscribe to the preprocess event to fix the data before it gets sent in the request:

amplify.subscribe("request.ajax.preprocess", function (defnSettings, settings, ajaxSettings, ampXHR) {
    ajaxSettings.data = JSON.stringify(ajaxSettings.data);
    ajaxSettings.dataType = "json";
    ajaxSettings.contentType = "application/json";
});

This is called for every ajax request, but you can look at settings.requestId if you want to filter it down to certain calls.
Reply all
Reply to author
Forward
0 new messages