Ajax post call returns parsererror - javascript

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);

Related

Ajax error getting called instead of success

<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',

jQuery.get with data creates url with [object%20object]

I am trying to make a GET request using jQuery. Instead of jquery appending my data name/vale pairs to the end of my url, it is appending [object%20object].
I am using both the $.ajax and $.get functions. See $.ajax and $.get
In researching this issue, I have found suggestions to add processData: false and contentType: false to my settings object (which shouldn't matter), but these options do not fix my problem.
Can someone confirm that this is a bug? Could my endpoint be blocking my request? But if so, why would that affect the url params?
here is my code that I am trying.
HTML
<input name='email'/> <button class='btn-submit'>Submit</button>
JS
$('.btn-submit').click(function(e) {
e.preventDefault();
var email = $('[name=email]').val();
var data = {
"apitoken": 'MYTOKEN',
"listid": 1111,
"email": email
};
var endpoint = "https://myendpoint.com/";
$.ajax({
url: endpoint,
method: 'GET',
processData: false,
contentType: false,
data: data,
success: function (data, status, jqxhr) {
console.log('success', data, status);
},
error: function(jqxhr, status) {
console.log('error', jqxhr, status);
}
});
// THIS IS THE GET METHOD
$.get(endpoint, data, function(data, status, jqxhr) { console.log('success', data, status); });

send array to post ajax

i need send mi post in this format
{
"elements" : ["elem1", "elem2","elem3" ]
}
and i have created this array :
var miElem=["elem1", "elem2","elem3" ]
$.post({
url: 'url',
data: {"elements" : miElem} ,
dataType: 'json',
success: function(data) {
console.log(data)
}.bind(this),
error: function(xhr, status, err) {
console.log(err)
}.bind(this)
});
but dont work, the data send well, but the format is incorrect
Use $.ajax() like this.The use of $.post is not correct.Check the syntax for $.post.here https://api.jquery.com/jquery.post/
var miElem=["elem1", "elem2","elem3"];
$.ajax({
url: 'url',//give your url here
type:'POST',
data: {elements : miElem} ,
dataType: 'json',
success: function(data) {
alert('success');//test for successful ajax request
console.log(data);
},
error: function(xhr, status, err) {
alert('error');//test for unsuccessful ajax request
console.log(err);
}
});
You should used $.ajax instead of $.post.
In $.ajax don't use success and error parameters. Use .done(), .fail(), .. (http://api.jquery.com/jquery.ajax/) it's more comprehensive. You can use .then() if you want to use promise.
Datatype parameter is for response type.
Your request is failing because
you passed incorrect arguments to $.post() method.
you did not set type:'POST' if you intended to use $.ajax.
for $.post() do the following:
$.post('url', {elements: miElem}).done(function(data) {
console.log(data);
}).fail(function (error)
console.error(error);
});
for $.ajax do the following:
$.ajax({
type: 'POST',
url: 'url',
data: {elements: miElem},
success: function (data) {
console.log(data);
},
dataType: 'json'
});

Javascript - Handling a AJAX call response from a web service

I'm using Javascript and Jquery to call a web service. The service should return an object. If the object returned contains Result=0, I want to show an alert, and if it doesn't, I want to show a different alert.
My code is shown below. I've tried "if (data.Result)" and "if (data.Result=0)", and neither of them work and show the "stock added" popup message.
Any help would be appreciated.
Object returned:
data: Object
Booking: Object
BookingId: "28eec5f6-29a7-e411-941a-00155d101201"
BookingProductIds: null
BookingStatus: 2
CrossSellProducts: null
ErrorMessage: ""
Result: 0
Javascript code:
function generateOrder() {
ABC.TixService.AddStockProduct(null, null, productRequest, ticketingRequest, function (context, data) {
if (data.Result) {
alert("stock added");
}
else
alert("error");
});
AddStockProduct: function (context, bookingId, productRequests, request, action) {
$.ajax({
url: 'TixService.svc/AddStockProduct',
cache: false,
type: 'POST',
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify({ bookingId: bookingId, productRequests: productRequests, request: request }),
context: { context: context, action: action },
success: function (data) {
this.action(this.context, data.AddStockProductResult);
},
error: function (xhr, ajaxOptions, thrownError) {
ErrorResponse(xhr, thrownError);
}
});
},
Shouldn't the test be:
if(data.Result === 0){
alert('stock added');
}

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.

Categories

Resources