Error 415: x-www-form-urlencoded versus JSON - javascript

The web service accepts application/json, but $.ajax() with dataType : 'json' set just tries to send data as application/x-www-form-urlencoded. What's the trick here?

dataType: 'json' specifies that jQuery expects JSON back from the server (see docs). In order to specify that you are sending JSON, you need to add contentType: "application/json".
Furthermore, jQuery cannot convert an object into JSON for you. If you are passing any object to data, you need to stringify it yourself:
data: JSON.stringify(dataObject);

Related

jQuery ignores HTTP request method and appends weird URL parameters

I have a web service that expects POST requests carrying a JSON string in the body. I'm trying to use this web service using jQuery, but I have two problems :
1) jQuery seems to always use the GET method, no matter what I do ;
2) jQuery seems to append weird things into the URL.
The relevant pice of my code :
var WEB_SERVICE_URL = 'http://localhost/XXXX/';
// ...
$.post({
url: WEB_SERVICE_URL + 'GetConfigLabels/',
contentType: 'application/json; charset=utf-8',
dataType: 'jsonp',
data: JSON.stringify(data),
processData: false,
success: function(response) {
// Whatever
},
error: function(xhr, message) {
// Whatever
}
});
The developper tools of the browser (Firefox Quantum 60.0.2) shows me a weird URL :
http://localhost/XXXX/GetConfigLabels/?callback=jQuery331012146934861340841_1530707758905&{}&_=1530707758906
While the following was expected :
http://localhost/XXXX/GetConfigLabels/
Also the HTML file is openned as a file (using file:///) through the file system, hence the use of JSONP for cross domain.
I failed to find existing questions related to this issue. What could be causing this ? Thank you !
Please refer to the dataType : json section at http://api.jquery.com/jquery.ajax/ :
"json": Evaluates the response as JSON and returns a JavaScript
object. Cross-domain "json" requests that have a callback placeholder,
e.g. ?callback=?, are performed using JSONP unless the request
includes jsonp: false in its request options. The JSON data is parsed
in a strict manner; any malformed JSON is rejected and a parse error
is thrown. As of jQuery 1.9, an empty response is also rejected; the
server should return a response of null or {} instead. (See json.org
for more information on proper JSON format
overrding random name of callback using jsonpCallback :
jsonpCallback Type: String or Function() Specify the callback function
name for a JSONP request. This value will be used instead of the
random name automatically generated by jQuery. It is preferable to let
jQuery generate a unique name as it'll make it easier to manage the
requests and provide callbacks and error handling. You may want to
specify the callback when you want to enable better browser caching of
GET requests. As of jQuery 1.5, you can also use a function for this
setting, in which case the value of jsonpCallback is set to the return
value of that function.

what is the difference between application/json and json only?

I have seen return type json , application/json while working with ajax. I have tried both and found the same result. Please anyone let me know the difference between these two.
datatype: 'json'
datatype: 'application/json'
JQuery's datatype argument on the $.ajax method accepts either the name of a format (like json or xml) which jQuery knows how to parse, or a MIME type (like application/json), which jQuery can map back to a parseable type. In this case, jQuery is mapping application/json to json for you, because it's a common format.
The datatype argument is not what MIME type you expect from the server, but how jquery should parse the response.
The documentation for jQuery.ajax says:
dataType (default: Intelligent Guess (xml, json, script, or html))
Type: String
The type of data that you're expecting back from the server.
[...]
"json": Evaluates the response as JSON and returns a JavaScript object.

Sending form JSON data to server via AJAX

I want to manually send my form data in JSON format to the server.
I changed my form data to a JSON fomat below.
The data I have in my clients-side javascript is in JSON (ie{"firstname":"john","lastname":"smith"}
$.ajax({
type: 'POST',
url: "http://localhost:3000/UserRegistration",
dataType: 'application/json',
data: JSONData,
success: function(data) {
}
});
I am using body-parser and in my server.js code, I do console.log(req.body) but the data is shown in this format
{ '{"firstname":"john","lastname":"smith"}': '' }
It added more curly braces. Why is that? How can i access the data in the server side
You can just serialize the form and bodyparser will parse it into json for you.
$.post('http://localhost:3000/UserRegistration', form.serialize(), function(data) {
...
});
dataType: 'application/json' will expect json response from server
Set processData : false and contentType : 'application/json'[Ref]
processData: By default, data passed in to the data option as an object (technically, anything other than a string) will be processed and transformed into a query string, fitting to the default content-type "application/x-www-form-urlencoded". If you want to send a DOMDocument, or other non-processed data, set this option to false
contentType: When sending data to the server, use this content type. Default is "application/x-www-form-urlencoded; charset=UTF-8", which is fine for most cases. If you explicitly pass in a content-type to $.ajax(), then it is always sent to the server (even if no data is sent)
Please directly parsed your object to json. for example: JSON.Stringfy(obj)

JSON data handling from PHP array

I am using an AJAX request to dynamically fetch some data from a database. The data is returned back to AJAX after being put through the PHP function json_encode(). The returned value that I recieve from the AJAX request is as follows:
{"counter":1,"1":{"objectID":"1","objectType":"note","objectDate":"2015-10-10 19:55:26","objectTitle":"Test Note","objectContent":"Lorem ipsum dolor sit amet consecetur adpiscing...","objectColor":"white"}}
How would I go about splitting this data down into separate variables such as counter for where the {"counter":1 JSON object is? Also, how would I split the sub-arrays of the JSON data into individual javascript arrays?
All help would be much appreciated. Thanks.
All you need to do is set dataType to "json" in your ajax call then pass the result with success like:
$.ajax({
url: 'example.com',
dataType: 'json',
success: function(json) {
console.log(json);
}
});
From the jQuery.ajax() documentation
dataType:
"json": Evaluates the response as JSON and returns a JavaScript
object. Cross-domain "json" requests are converted to "jsonp" unless
the request includes jsonp: false in its request options. The JSON
data is parsed in a strict manner; any malformed JSON is rejected and
a parse error is thrown. As of jQuery 1.9, an empty response is also
rejected; the server should return a response of null or {} instead.
(See json.org for more information on proper JSON formatting.)
With a simple:
JSON.parse(data);
I have managed to achieve this.
Couldn't find this when originally researching.

Javascript automatically parsing nested object

This is more a question of procedure than anything else. I'm curious why this happens and I can't seem to find any documentation on this "feature" within the ECMA script documentation.
When I make an AJAX call within jQuery to my server, it returns the following JSON response to the page:
{"version":"v1","status":"OK","timestamp":"2013-02-14 10:32:45","data":"true","error":""}
With this string I have to call jQuery.parseJSON(string); to get it as an object, and the be able to reference it as an object.
However, when my server returns something like this:
{"version":"v1","status":"OK","timestamp":"2013-02-14 10:12:19","data":{"a":"asgsadfga","b":false,"c":[]},"error":""}
Javascript automatically loads this an an object without the need to parse. It would seem that because this example returns a nested object, despite the fact it was returned from the server as a string, Javascript will immediately recognize that, and parse the string for me.
Is this expected functionality, and if so, can anyone point me to the documentation of this?
EDITED:
Here is the offending AJAX call:
jQuery.ajax({
url: url,
type: 'GET',
async: false,
success: function (result) {
console.log(result)
}
Make sure that your server sets the proper Content-Type response HTTP header:
Content-Type: application/json
So that jQuery will automatically parse the JSON string returned by your server to a javascript object which will be passed as argument to your success callback.
Or if for some reason you've got some broken server side script which you have no control over you could set the dataType parameter to force jQuery to parse the result as JSON:
$.ajax({
url: '/script.cgi',
type: 'POST'
dataType: 'json',
success: function(result) {
// result will be a javascript object
}
});
But obviously the proper thing to do is to fix your server side script to return the proper Content-Type response header.
According to ajax() in jQuery API Documentation under dataType:
dataType (default: Intelligent Guess (xml, json, script, or
html))Type: String The type of data that you're expecting back from
the server. If none is specified, jQuery will try to infer it based
on the MIME type of the response (an XML MIME type will yield XML, in
1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string).
Hope this helps.
You should specify dataType to be json in your $.ajax call. dataType is the MIME you are expecting to receive from the server. contentType is what the server is expecting from you.

Categories