Ajax error getting called instead of success - javascript

<script>
function editComment(id) {
var content = $('#Content').val();
var modelData = { 'Id': id, 'Content': content };
$.ajax({
type: 'POST',
dataType: 'json',
url: '#Url.Action("EditC", "Comment")',
data: JSON.stringify({ model: modelData }),
contentType: 'application/json',
success: function () {
alert("YES");
},
error: function () {
alert("Error");
}
});
}
</script>
Here the server is returning 200 OK, but for some reason the error function is getting called. Both type and contentType seem to be correct. Any idea how to fix this?
Edit:
After adding
error: function (xhr, textStatus, error) {
console.log(xhr.responseText);
console.log(xhr.statusText);
console.log(textStatus);
console.log(error);
}
this is what is being logged:
parsererror
parsererror
SyntaxError: Unexpected end of JSON input
at parse (<anonymous>)
at ajaxConvert (jquery-3.4.1.js:9013:19)
at done (jquery-3.4.1.js:9483:15)
at XMLHttpRequest.<anonymous> (jquery-3.4.1.js:9785:9)

Moving to an answer for future readers...
The server is indeed returning a successful response, but an empty successful response:
return new HttpStatusCodeResult(200);
However, the client-side code is expecting valid JSON:
dataType: 'json',
As a result, after the successful response is received, internally the jQuery code attempts to parse that response as JSON and that fails, resulting in triggering the error callback.
Since there's no response body (and in most cases even when there is, as long as the server returns the correct MIME type), you don't need or want to specify a dataType in the jQuery AJAX operation. Simply remove this part:
dataType: 'json',

Related

how to detect a server error into a jquery ajax call?

I use Jquery to parse an json from url: the code is like this:
function fetchdata() {
var statusUrl = '/api/desk/j/';
$.ajax({
url: statusUrl,
dataType: "json",
type: 'post',
success: function(response) {
alert('ok');
},
error: function(xhr, status, error) {
var err = JSON.parse(xhr.responseText);
alert(err.message);
}
});
}
everything works fine, but if the server is not reachable I'm not able to detect it: I tried to do something in error: function, but seems that the code in error is fired only if the json has an error
have you got some ideas?
thank you!
You need to test the statusText from the jQuery textStatus response object. You can take advantage of your browser's developer console to inspect this object. You can expand the properties and methods for your perusal, however you wanna use it. Just click on the returned message of the console.log() to see these properties and methods that you wan't to use for error detection.
function fetchdata() {
var statusUrl = '/api/desk/j/';
$.ajax({
url: statusUrl,
dataType: "json",
type: 'post',
success: function(response) {
alert('ok');
},
error: function(textStatus) {
console.log(textStatus);
console.log(textStatus.statusText, textStatus.status);
}
});
}
fetchdata();

Ajax POST error (400 BAD REQUEST)

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/"

Ajax post call returns parsererror

I submit the reactjs form as mentioned below,
submit(){
if(this.checkRequiredField()){
$.ajax({
url: '/api/Accounts',
dataType: 'json',
type: 'POST',
data: {
Name: this.state.name,
StartDate :this.state.startDate,
EndDate : this.state.endDate,
UserCount: this.state.userCount
},
success: function(data, status, xhr) {
console.log('data added successfully');
}.bind(this),
error: function(xhr, status, err) {
console.error(status, err.toString());
}.bind(this)
})
}
The above ajax post will call the respective Web Api post method, where the data got inserted successfully to the db.
After it posts the data, the program doesn't return to the success function, instead it calls error function and logs the error
parsererror SyntaxError: JSON.parse: unexpected end of data at line 1
column 1 of the JSON data
when I checked the xhr.status, the value is 201 and statustext is Created.
Why the above ajax post call returns parsererror? how to fix this issue?
The problem is with the dataType mentioned in the ajax call.
The post method is not returning any json data,
by changing the dataType :'json' to dataType:'text' fixed the issue.
Thanks Jaromanda X and Mathew Jibin for your inputs
If you are not expecting a JSON format return, you may need to remove that instead.
submit(){
if(this.checkRequiredField()){
$.ajax({
url: '/api/Accounts',
type: 'POST',
data: {
Name: this.state.name,
StartDate :this.state.startDate,
EndDate : this.state.endDate,
UserCount: this.state.userCount
},
success: function(data, status, xhr) {
console.log('data added successfully');
}.bind(this),
error: function(xhr, status, err) {
console.error(status, err.toString());
}.bind(this)
})
}
just a suggestion,
if you want to return a json from controller you can pass a custom message from controller, like saved successfully, keeping your same ajax code
success: function(data, status, xhr) {
console.log(data.ResponseText );
}
controller:
based on condition
return Json(new { success = true,
ResponseText = "saved successfully" }, JsonRequestBehavior.AllowGet);

Internal Server Error when response text from ajax POST call is big

I am using an ajax call like the following:
$(function () {
$.ajax({
type: 'POST',
url: 'frmHistoryReportFinal.aspx/GetDataTable',
data: json_data,
contentType: 'application/json;charset=utf-8',
dataType: 'json',
success: function (responseText) {
if (responseText.d == "")
return;
parsedData = JSON.parse(responseText.d);
alert(parsedData);
count = 0;
},
error: function (xhr, textStatus, errorThrown) {
//process the error
alert(xhr);
alert(textStatus);
alert(errorThrown);
}
});
});
When I have a small set of data returned from my C# codebehind. The ajax call functions well. But when I have a json string with larger data, say 200 records returned then the ajax call gives error("Internal Server Error").
Please help me resolve the issue as I usually need to handle large datasets.

Ajax returns error, but it works

I'm running an application using Ajax and Sinatra. I want to send a POST parameter into my app.rb file.
My app.rb
post '/game/moves' do
#square = params[:square]
puts #square
content_type :json
{ :success => 'Data successfully transmitted' }.to_json
end
My view
$.ajax({
url: 'moves',
data: {square:square},
type: 'POST',
dataType: 'json',
success: function() {
alert("Success");
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest + textStatus + errorThrown);
}
});
It returns the alert "[object Object]error", but on my console, I see that I successfully retrieved the POST parameter. So it works, but I can't get into the "success" part of the code, and instead I'm getting on the error part.
I also tried to replace the json type by the html type, and removed the return value on my app.rb file, to no avail (exact same error).
I found a working solution. Here, I successfully retrieve the params on top ofgetting the "It works !" alert. That was what I wanted.
As you can notice, I don't set "async" to false. I don't know why I have to do that, nor why it doesn't work when I don't. I don't mind if it is set to false, for it works, but if someone can tell me the possible reason, it would still help me. Thanks.
Here's the full code (the function send is called in an obstrusive way (with a one-line html onclick), because I need the params xi and yi)
The view
function send(xi,yi) {
info = [];
info[0] = xi;
info[1] = yi;
$.ajax({
type: 'POST',
url: 'moves',
dataType: 'text',
async: false,
data: {square:info},
success: function(token) {
alert(token)
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest, textStatus, errorThrown);
}
});
}
App.rb
post '/game/moves' do
if params[:square]
"It works !"
end
end

Categories

Resources