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"
Related
and thank you in advance for helping me.
I'm trying to make a POST where I pass the TOKEN in the URL and I want to pass another param too so I can save the info in the DB. I have this:
$("#btnAddCompany").click(function(e) {
var token = "123";
var companyValue = document.getElementById("companyValue").value;
var obj ={CompanyId: 4 ,Name: companyValue }
var postData = JSON.stringify(obj);
console.log(postData);
$.ajax({
type: "POST", //REQUEST TYPE
dataType: "json", //RESPONSE TYPE
contentType: "application/json",
data: postData,
url: "http://banametric.ddns.net/BanaMetricWebServices/BanaSov_WS.svc/CompanySave/"+token,
success: function(data) {
toastr.success("Lidl Adicionado!");
},
error: function(err) {
console.log("AJAX error in request: " + JSON.stringify(err, null, 2));
}
}).always(function(jqXHR, textStatus) {
if (textStatus != "success") {
alert("Error: " + jqXHR.statusText);
}
})
});
But I'm getting an 400 error (Bad Request) so I assume that I'm making something wrong, but I don't find out what. The error trace is this:
AJAX error in request: { "readyState": 4, "responseText": "\r\n
The server encountered an error processing the request. The
exception message is 'The incoming message has an unexpected message
format 'Raw'. The expected message formats for the operation are
'Xml', 'Json'. This can be because a WebContentTypeMapper has not been
configured on the binding. See server logs for more
details. The exception stack trace is: \r\n at
System.ServiceModel.Dispatcher.DemultiplexingDispatchMessageFormatter.DeserializeRequest(Message
message, Object[] parameters)\r\n at
It's error because of
The expected message formats for the operation are 'Xml', 'Json'.
So you can pass contentType in your ajax call
$.ajax({
....,
contentType: "application/json"
})
I am not sure, but it depends on what server wants to read from you.
Server does not want to read raw bytes, it wants xml or json
Try to add headers like
beforeSend: function(xhrObj){
xhrObj.setRequestHeader("Content-Type","application/json");
xhrObj.setRequestHeader("Accept","application/json");
},
in $.ajax() function
You need to set the content type header in your request to inform the server you're sending the data as JSON.
The error message is telling you that the server does not understand the content you're sending it - you have to give it a hint that the data is in a particular format, especially because, again as mentioned in the error message, it allows you to submit in more than one different format (JSON or XML in this case).
Adding
contentType: "application/json"
to the options in your $.ajax call should resolve the issue.
P.S. We can't see the signature of your controller method but it's possible you may also need to give your parameter a name within the JSON, e.g. something like data: JSON.stringify({ "companyValue": postData }); , but there's not enough info in your question to say for certain what the correct structure should be.
$("body").on("submit", ".example_form", function() {
$.ajax({
url: 'http://example.com/{ROUTE_URL}',
data: new FormData(this),
processData: false,
contentType: false,
/* OR contentType: "application/json; charset=utf-8"*/
type: 'POST',
dataType: "json",
success: function(data) {
console.log(data);
}
});
});
Instead of this
var postData = JSON.stringify(companyValue);
why don't you try this:
var obj ={token :token ,companyValue:companyValue }
And then make use of the json stringify function
var postData = JSON.stringify(obj);
After that in ajax call only change the url:
url: "http://webservice/CompanySave/"
I got an url let’s say abc its type is post. if I try to call it as $.ajax method post it is showing method not allowed 405 error. it I sent by method get it is working fine but the business is not done how to solve the issue?
js code:
$.ajax({
type: "POST",
url: url,
data: data,
beforeSend: function (request){
request.setRequestHeader("X-CSRF-TOKEN", token)
},
success: function(res){
console.log(res)
},
error: function(){
JSON.parse(this.error.arguments[0].responseText).error.message.value
},
dataType: "json"
});
You should use 'method' instead of 'type'. Try this:
$.ajax({
method: "POST",
url: url,
data: data,
beforeSend: function (request){
request.setRequestHeader("X-CSRF-TOKEN", token)
},
success: function(res){
console.log(res)
},
error: function(){
JSON.parse(this.error.arguments[0].responseText).error.message.value
},
dataType: "json"
});
Or you can use the jQuery.post method.
405 Method Not Allowed
The method specified in the Request-Line is not allowed for the resource identified by the Request-URI. The response MUST include an Allow header containing a list of valid methods for the requested resource. 405 Method Not Allowed
I'm trying to send an ajax POST request and I've set the content type to be application/json etc. But in the backend I keep getting 400 (BAD REQUEST). What's wrong with the code?
var data = {key0: 'val0', key1: 'val1'};
$.ajax({
type: "POST",
url: 'http://localhost:8000/api/users',
data: data,
success: function(data) {
console.log(data);
},
contentType: 'application/json',
dataType: 'json'
});
Flask:
#usersapi.route('/api/users', methods=['POST'])
def create_user():
#raise Exception(request.headers.get('Content-Type'))
d = dict(request.get_json())
You aren't sending JSON.
You've passed data an object, so it is being serialised as form data.
You need to explicitly convert it to JSON:
data: JSON.stringify(data),
I have trouble with a piece of ajax code. This is the error message I get from mod security:
/ajaxController.php?mod=catalog&op=ajaxSeenProducts HTTP/1.1
Access denied with code 400 (phase 2). Operator EQ matched 0 at
REQUEST_HEADERS. [file "/usr/local/apache/conf/modsec2.user.conf"]
[line "12"] [id "960012"] [msg "POST request must have a
Content-Length header"] [severity "WARNING"] [tag
"PROTOCOL_VIOLATION/EVASION"]
There is a module in the web shop I am working on, which shows the last viewed products, and the jquery code I have is this:
$('#seen_products_box').ready(function() {
$.ajax({
type: "POST",
url: "{HOME}ajaxController.php?mod=catalog&op=ajaxSeenProducts",
success: function(seenProducts) {
$('#seen_products_box').empty();
$('#seen_products_box').append(seenProducts);
}
});
});
While searching for the solution, I have found in various places that I need to set the
Content-length
parameter, but all I have found is in this format:
xmlHttp.setRequestHeader("Content-length", params.length);
Is there any way to set the request header in the code format I have provided above? I have already tried something like:
headers: {
"Content-Length": params.length
}
but with no result. Any help would be appreciated.
use code like:
var url = '{HOME}ajaxController.php?';
var data = "mod=catalog&op=ajaxSeenProducts";
$.ajax({
url: url,
data: data,
dataType: "html",
type:'post',
success:function(seenProducts){
$('#seen_products_box').empty();
$('#seen_products_box').append(seenProducts);
},
error:function(response){
}
});
you can use the beforeSend function to set the headers
$('#seen_products_box').ready(function() {
$.ajax({
type: "POST",
beforeSend: function (request)
{
request.setRequestHeader("Authority", authorizationToken);
},
url: "{HOME}ajaxController.php?mod=catalog&op=ajaxSeenProducts",
success: function(seenProducts) {
$('#seen_products_box').empty();
$('#seen_products_box').append(seenProducts);
}
});
});
or other way you can do it like
$('#seen_products_box').ready(function() {
$.ajax({
type: "POST",
headers: {"X-Test-Header": "test-value"},
url: "{HOME}ajaxController.php?mod=catalog&op=ajaxSeenProducts",
success: function(seenProducts) {
$('#seen_products_box').empty();
$('#seen_products_box').append(seenProducts);
}
});
});
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