dataType 'application/json' vs. 'json' [duplicate] - javascript

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
$.ajax - dataType
I am using jQuery 1.8.2, and for some reason 'application/json' does not work, but 'json' works as dataType to a standard jquery ajax call. Is this a glitch? A version related difference? or is there an established difference between the two?
$(document).ready(function() {
$.ajax({
type : "POST",
url : '<c:url value="/url.htm" >',
//dataType : "application/json", <-- does not work
dataType: 'json' // <-- works
success : function(data) {
// do something
},
error : function(data) {
// do something else
}
});
});

dataType takes json, it means the request expects a json response.
contentType takes application/json, it means the request is sending json data
You can send as well as expect json in a request e.g.
$.ajax({
type : "POST",
url : url,
contentType : "application/json",
dataType: 'json',
data: JSON.stringify({some: 'data'}),
success : function(data) {
// do something
},
error : function(data) {
// do something else
}
});
here you're sending json and expecting xml
$.ajax({
type : "POST",
url : url,
contentType : "application/json",
dataType: 'xml',
data: JSON.stringify({xmlfile: 'file.xml'}),
success : function(data) {
// do something
},
error : function(data) {
// do something else
}
});
and here you're sending x-www-form-urlencoded(jQuery automatically sets this for you), and expect json back
$.ajax({
type : "POST",
url : url,
dataType: 'json',
data: {id: '1'},
success : function(data) {
// do something
},
error : function(data) {
// do something else
}
});
contentType sets the ContentType HTTP request header, telling the server that the body of this request is of the given type.
dataType sets the Accept header to tell the server that this is the type of response we want e.g.
Accept:application/json, text/javascript, */*; q=0.01
but regardless of what type of response the server sends jQuery will still attempt to parse it as whatever type you set in the dataType field.

"application/json" is the correct mime type for json. The jquery dataType field, however, is expecting one of the following strings:
"xml"
"html"
"script"
"json"
"jsonp"

Per the json documentation, the correct dataType is "json".
http://api.jquery.com/jQuery.ajax/
Here are the options supported:
xml
html
script
json
jsonp
text

Related

Jquery ajax call wrong payload

I have some troubles whit jquery ajax call, infact I tried to perform a post call passing like data a string variable:
myVar = 'Hello';
$.ajax(
type: 'POST',
url : 'https://...',
data: myVar,
success : function(data) {
},
complite: function() {...},
error: function(err) {...}
)
If I inspect the http call I can see that the payload is:
'Hello': ""
I don't know how it is possible and how fix the problem.
jQuery, by default, will put a Content-Type: application/x-www-form-urlencoded header on data it sends via Ajax.
You, however, are passing a plain text string.
You need to either change the Content-Type to match the data you are sending or the data you are sending to match the Content-Type. (Or you could change both).
The important things are:
The data and content-type need to match
The server needs to be able to handle data in the format you are sending
So you might:
$.ajax({
type: 'POST',
url : 'https://...',
data: myVar,
contentType: 'text/plain'
// ...
})
or, since jQuery will encode objects as URL encoded data:
$.ajax({
type: 'POST',
url : 'https://...',
data: { myVar },
// ...
})
or, if you want multipart data:
const data = new FormData();
data.append('myVar', myVar);
$.ajax({
type: 'POST',
url : 'https://...',
data,
contentType: false // XHR will read the content-type from the FormData object (which it needs to do in order to determine the boundary paramater), putting 'false' here stops jQuery overriding it
// ...
})
or, for JSON
$.ajax({
type: 'POST',
url : 'https://...',
data: JSON.stringify(myVar), // This will be a JSON text representing a string
contentType: 'application/json'
// ...
})
i think you are passing payload in the wrong formate.
myVar = 'Hello';
$.ajax(
type: 'POST',
url : 'https://...',
data: {
'name':myVar
},
success : function(data) {
},
complite: function() {...},
error: function(err) {...}
)
On the server side you will get the value in the key 'name' you can fetch the value using 'name' key.

How to make a PUT JQuery Ajax request to JsonBlob

I'm trying to call a PUT request on JsonBlob but i get this error
"XML interpretation error: no root element found Address: https://jsonblob.com/api/jsonBlob/43c83fba-f591-11e8-85a9-1542923be246 Row number 1, column 1:"
Here is the function:
backup : function(data){
data = JSON.stringify(data);
console.log(data);
var url = "https://jsonblob.com/api/jsonBlob/43c83fba-f591-11e8-85a9-1542923be246";
$.ajax({
url: url,
type: "PUT",
data: data,
dataType: 'json',
error:function(xhr, status, e){
console.log(status)
}
});
The API's error message indicates that it is trying to parse your request as XML.
The documentation for the API shows a Content-Type header on the request:
HTTP/1.1 200 OK
Content-Type: application/json
Transfer-Encoding: chunked
{"people":["fred","mark","andrew"]}
You haven't included that.
Add it:
$.ajax({
url: url,
contentType: "application/json"

How can I set get request call type to 'document' [duplicate]

What is content-type and datatype in a POST request? Suppose I have this:
$.ajax({
type : "POST",
url : /v1/user,
datatype : "application/json",
contentType: "text/plain",
success : function() {
},
error : function(error) {
},
Is contentType what we send? So what we send in the example above is JSON and what we receive is plain text? I don't really understand.
contentType is the type of data you're sending, so application/json; charset=utf-8 is a common one, as is application/x-www-form-urlencoded; charset=UTF-8, which is the default.
dataType is what you're expecting back from the server: json, html, text, etc. jQuery will use this to figure out how to populate the success function's parameter.
If you're posting something like:
{"name":"John Doe"}
and expecting back:
{"success":true}
Then you should have:
var data = {"name":"John Doe"}
$.ajax({
dataType : "json",
contentType: "application/json; charset=utf-8",
data : JSON.stringify(data),
success : function(result) {
alert(result.success); // result is an object which is created from the returned JSON
},
});
If you're expecting the following:
<div>SUCCESS!!!</div>
Then you should do:
var data = {"name":"John Doe"}
$.ajax({
dataType : "html",
contentType: "application/json; charset=utf-8",
data : JSON.stringify(data),
success : function(result) {
jQuery("#someContainer").html(result); // result is the HTML text
},
});
One more - if you want to post:
name=John&age=34
Then don't stringify the data, and do:
var data = {"name":"John", "age": 34}
$.ajax({
dataType : "html",
contentType: "application/x-www-form-urlencoded; charset=UTF-8", // this is the default value, so it's optional
data : data,
success : function(result) {
jQuery("#someContainer").html(result); // result is the HTML text
},
});
From the jQuery documentation - http://api.jquery.com/jQuery.ajax/
contentType When sending data to the server, use this content type.
dataType 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
"text": A plain text string.
So you want contentType to be application/json and dataType to be text:
$.ajax({
type : "POST",
url : /v1/user,
dataType : "text",
contentType: "application/json",
data : dataAttribute,
success : function() {
},
error : function(error) {
}
});
See http://api.jquery.com/jQuery.ajax/, there's mention of datatype and contentType there.
They are both used in the request to the server so the server knows what kind of data to receive/send.

Trouble Accessing Ajax POST variable on Codeigniter end

I'm using jquery to make ajax calls. Basically I don't know how to access the data I'm sending to the server with a post request. I don't know what the variable is called or... something. I don't know!
Ajax functions:
function ajax_client(url, json) {
return $.ajax({
url: url,
type: 'POST',
data: json,
dataType: 'json'
});
}
function gather_records(data, inp_col, fetch_col, limit) {
var json = JSON.stringify({
"ids" : data,
"inp_col" : inp_col,
"fetch_col" : fetch_col,
"limit" : limit
});
return ajax_client(base_url+'ajax_port/gather_records', json);
}
Codeigniter Function:
public function gather_records()
{
$data = json_decode($this->input->post('ids'));
log_message('debug', $data);//null
return json_encode($data);//null :(
}
I'm having no trouble receiving data back from the server here (and accessing with jQuery), my problem is that I can't get the data I'm sending to codeigniter. I'm developing on MAMP if that makes any difference.
I've tried other variable names like,
$this->input->post('data');
$this->input->post('json');
None seem to work.
Thanks very much for any help I can get!
You don't need to do JSON.stringify({..
just pass an object, and everything will be fine. I mean:
function ajax_client(url, json) {
return $.ajax({
url: url,
type: 'POST',
data: json,
dataType: 'json'
});
}
function gather_records(data, inp_col, fetch_col, limit) {
var json = {
"ids" : data,
"inp_col" : inp_col,
"fetch_col" : fetch_col,
"limit" : limit
};
return ajax_client(base_url+'ajax_port/gather_records', json);
}
One more thing. You don't need to json_decode it in your PHP side. Because default contentType in jQuery is 'application/x-www-form-urlencoded; charset=UTF-8'
Change line
$data = json_decode($this->input->post('ids'));
to
$data = $this->input->post('ids');
But if you really want to send JSON, you can add contentType
return $.ajax({
url: url,
type: 'POST',
data: json,
contentType: 'application/json',
dataType: 'json'
});
dataType you have set is "The type of data that you're expecting back from the server." (http://api.jquery.com/jquery.ajax/)

Jsonp returned from ajax doesn't show on console

I'm calling a page (external, on other domain), with this code:
var instagram_container = $('div#instagram-answer');
if (instagram_container.length>0)
{
var url = 'http://www.xxxx.it/admin/get_instagram_token';
$.ajax({
type : 'GET',
url : url,
async : false,
jsonpCallback: 'jsonCallback',
contentType: 'application/json',
dataType: 'jsonp',
success: function(response)
{
console.log(response);
instagram_container.html(response.client_id);
},
error: function(e)
{
console.log(e);
}
});
}
I have answer with console.log(e) (basically it recognizes as error)?
Object { readyState=4, status=200, statusText="success", altri elementi...}
But in Firebug, under NET tab, I have the right answer...
This is the console. Line 19 is exactly the
console.log(e);
in error section.
My goal is obtain that Json. Thank you
Is your server returning plain text, or an actual JSON file? Jquery will ignore the response if the server returned a string instead of JSON.
The response type should be: "application/json"
EDIT:
I'd recommend you to use the basic jquery ajax call:
$.ajax({
url: "test.html",
cache: false
})
.done(function( response ) {
console.log(response);
});

Categories

Resources