This one is really weird. I have multiple $.post()
in the code, but there is one don't know why sends the json parameters as x-www-form-urlencoded
instead and therefore doesn't work.
Here's the code:
$.post("/Route/SaveTransportProperties", { properties: JSON.stringify(propArray), currTravelBox: JSON.stringify(travelBoxObj), accessToken: getAccessToken()}, function(data) { //DO STUFF });
The XHR looks like this in Firefox:
Any ideas why is this happening? I also enforced the type as 'json' but doesn't work either.
One of the biggest differences between the two is that JSON-encoding the post usually preserves the data types of the values that are sent in (as long as they are valid JSON datatypes), whereas application/x-www-form-urlencoded will usually have all properties converted to strings.
To use it, we need to select the x-www-form-urlencoded tab in the body of their request. We need to enter the key-value pairs for sending the request body to the server, and Postman will encode the desired data before sending it. Postman encodes both the key and the value.
The application/x-www-form-urlencoded content type describes form data that is sent in a single block in the HTTP message body. Unlike the query part of the URL in a GET request, the length of the data is unrestricted.
Hence, it is advised to use x-www-form-urlencoded when you have to send form data e.g. most of the web form which asks you to enter values and use multipart/form-data when you have to upload files to the server as used here.
If you want to send the data as json then use the $.ajax function
You can specify type post and dataType json.
$.ajax({ url: "mydomain.com/url", type: "POST", dataType: "xml/html/script/json", // expected format for response contentType: "application/json", // send as JSON data: $.param( $("Element or Expression") ), complete: function() { //called when complete }, success: function() { //called when successful }, error: function() { //called when there is an error }, });
Taken from ajax documentation
http://api.jquery.com/jQuery.ajax/
contentTypeString Default: 'application/x-www-form-urlencoded; charset=UTF-8'
Because $.post() is for sending form-like requests. $.ajax is for sending whatever you want to. See contentType
in $.ajax
page for more information.
Quote:
When sending data to the server, use this content-type. Default is "application/x-www-form-urlencoded", which is fine for most cases. If you explicitly pass in a content-type to $.ajax() then it'll always be sent to the server (even if no data is sent). Data will always be transmitted to the server using UTF-8 charset; you must decode this appropriately on the server side.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With