Readystate 4, status 200 , parseerror - javascript

I am calling post request through ajax.It is working fine for small data but it gives Readystate 4,status 200,parse error for large data JSON.Following is my java script...
$.ajax({
url: '#Url.Action("GetCompanyTicketsGrid")',
dataType: "json",
type: "post",
data: { companyUserID: userId, globalRoleId: roleId },
success: function (res) {
$gridUser.empty();
var len = res.rows.length;
if (len > 0) {
$("#errorDiv").hide();
for (var i = 0; i < len; i++) {
//some work
}
}
else
$("#errorDiv").show();
},
error: function (a, b) {
alert("User Data: " + b);
}
});
When i return JSON with more than 5000 records then only i m getting that error.
Thanks in advance.

Related

Loop through an Array and access their properties in JavaScript in IE

I would like to use the same alert message to display all the messages at once.
function LoadData(obj) {
var ArrayData = $('input[type="hidden"][id^="li"]').map(function() {
return this.getAttribute("value");
}).get();
$.ajax({
data: {
GUID: JSON.stringify(ArrayData)
},
url: "/LoadOrder/LoadData",
contentType: "application/json; charset=utf-8",
dataType: "json",
cache: false,
success: function(result) {
if (result.length > 0) {
for (var item of result) {
alert("There are problems with your selections ${item.Desc} and ${item.EDesc}
.");
}
}
}
});
}
Expected result should be displayed like below only once.
Currently, the same message displays 3 times.
There are problems with your selections.
ABC - CDE
GFE- Test
Test1 - Test2
Is there any way to display all in once.
You could change the success callback so that you first create the list of messages as a string and then call the alert
success: function(result) {
if (result.length > 0) {
const problems = result.map(item => `${item.Desc} - ${item.EDesc}`).join('\n');
alert(`There are problems with your selections.\n${problems}`);
}
}
and without using arrow functions
success: function(result) {
if (result.length > 0) {
var problems = result.map(function(item) {
return `${item.Desc} - ${item.EDesc}`
}).join('\n');
alert(`There are problems with your selections.\n${problems}`);
}
}

increment a counter after each ajax insert then show it as a message

I am using Ajax for inserting data into MySQL with PHP, see my code below:
var c = 0;//initialize counter
function add(){
for (var i = 0; i < 10; i++) {
$.ajax({
type: "POST",
url: "insert.php",
data: {
id: id,
name: name,
email: email,
},
dataType: "json",
success: function (res) {
c++;//increment counter
},
});
}
alert(c);//display counter
}
what I want to do is show the alert (number of times the insert operation is done) after the for loop ends. I have did it like above code it does not work. it always shows zero.
Is there any way to done the same functionality?
this way works.
var c = 0;
async function add() {
for (var i = 0; i < 10; i++) {
await $.ajax({
type: "POST",
url: "https://upwork.codefusiontm.com/stack/002",
data: {
id: "id",
name: "name",
email: "email",
},
dataType: "json",
success: function (res) {
c++;//increment counter
},
});
}
}
$(() => {
add().then(() => {
console.log("=>",c)
})
})
You need to use promisse with the use of async and wait. You use async and create the add method as async
async function add() {
After that, you add await in $.ajax because only in this way ajax will only increment c++ only after the POST returns, this has to be done because you start several POST within the for, and so have to wait for the completion of each to be able to increment correctly.
await $.ajax({
In conclusion, you can finally get the value of variable c
$(() => {
add().then(() => {
console.log("=>",c)
})
})
Don't forget, the method call has to be made within document.ready
$(() => {
})
Consider the following.
var c = 0; //initialize counter
function add() {
for (var i = 0; i < 10; i++) {
$.ajax({
type: "POST",
url: "insert.php",
data: {
id: id,
name: name,
email: email,
},
dataType: "json",
success: function(res) {
c++;
if (i == 10) {
alert(c); //display counter
}
},
});
}
}
When you perform the last loop, i will be 9 and then incremented to 10. So we can check if i is equal to 10, and then we know the loop has ran the last time.

Ajax response looks undefined

I'm trying to get the ajax response and attribute it to a variable (let's say _has_weekend_hollidays) as follows:
JS Call:
_has_weekend_hollidays = checkWeekendHollidays( _i );
console.log ( checkWeekendHollidays( _i ) );
AJAX Call
$.ajax({
url: "./directory/ajax_check_weekend_hollidays.php",
type: "POST",
data: {
start_date: _date1,
final_date: _date2
}
}).done(function (_result) {
return ( _first_weekday == 0 || _last_weekday_id >= 6 || _result!="0" );
}).fail(function (_result) {
console.log("ERROR:" + _resultado);
});
The AJAX _result is OK but the return is not working.
So console.log shows undefined.
Any ideas?
Thanks in advance!
If you need the result to continue, do your work after the Ajax callback.
It's undefined because there are no variable return by Ajax:
{
url: "./directory/ajax_check_weekend_hollidays.php",
type: "POST",
data: {
start_date: _date1,
final_date: _date2
}
}
This line:
return ( _first_weekday == 0 || _last_weekday_id >= 6 || _result!="0" );
is not executed until Ajax is "Done".
It you wish to log the return data, use console.log in the return function.
Example:
$.ajax({
url: "./directory/ajax_check_weekend_hollidays.php",
type: "POST",
data: {
start_date: _date1,
final_date: _date2
}
}).done(function (_result) {
console.log(_first_weekday == 0 || _last_weekday_id >= 6 || _result!="0");
//do something else here too
}).fail(function (_result) {
console.log("ERROR:" + _resultado);
});

Only one alert for multiple execution in Ajax

I am working rails application.i need to get status of the each selected device.I am able to achieve this but after executing i am putting alert "Successfully created execution record".For every mac selection it is showing alert message.I need to give one alert in end of execution.I am calling display_result in call_endpoint method.Since it is an Ajax call,it is giving alert for every execution.i don't how to limit to single alert for this.
function display_result() {
$('#http_status').html("");
$('#http_status').append(result["response"].status);
if (result["response"].status == "404") {
console.log("HTTP 404");
$('#response_div').addClass("bs-callout-warning");
} else if (result["response"].status == "520") {
console.log("HTTP 502");
$('#response_div').addClass("bs-callout-danger");
} else {
console.log("HTTP 200");
$('#response_div').addClass("bs-callout-success");
if (result["response"].status == "200") {
// $('.loader').show();
$('#cover-spin').show();
$.ajax({
method: "GET",
dataType: "text",
url: "create_execution",
data: {
http_status: result["response"].status,
mac_address: mac,
},
success: function (execution_record_id) {
$('#cover-spin').hide();
alert('Successfully created execution record");
}
});
}
function call_endpoint() {
var values = new Array();
webpa = $('#Device-PA').is(":visible");
rpil = $('#Device-SN').is(":visible");
groupselect = $('#Group-Select').is(":visible");
parameter_name = $('#tr_object').val();
if (webpa) {
$.each($("input[name='checkBox[]']:checked").closest("td").next("td"), function () {
values.push($(this).text().trim())
});
m = values.length
} else {
$.each($("input[name='checkBox[]']:checked").closest("td").next("td"), function () {
values.push($(this).text().trim())
});
m = values.length
}
serialnumber = $('#pa_serialnumber').val();
oid = $('#sn_serialnumber').val();
protocol = {
pa: pa,
sn: sn,
}
if (pa) {
for (var i = 0; i < m; i++) {
(function () {
var macAdd = values[i];
$.ajax({
method: "GET",
url: "get_object",
dataType: "json",
data: {
parameter: parameter_name,
mac: macAdd,
protocol: protocol,
serialnumber: serialnumber,
},
success: function (result) {
console.log(result);
NProgress.done();
console.log("result for webpa");
display_result();
},
statusCode: {
404: function () {
console.log("Call failed");
}
}
});
})();
}
}
Below is changed code..
Copy below code as it is.
function display_result(total,current) {
$('#http_status').html("");
$('#http_status').append(result["response"].status);
if (result["response"].status == "404") {
console.log("HTTP 404");
$('#response_div').addClass("bs-callout-warning");
} else if (result["response"].status == "520") {
console.log("HTTP 502");
$('#response_div').addClass("bs-callout-danger");
} else {
console.log("HTTP 200");
$('#response_div').addClass("bs-callout-success");
if (result["response"].status == "200") {
// $('.loader').show();
$('#cover-spin').show();
$.ajax({
method: "GET",
dataType: "text",
url: "create_execution",
data: {
http_status: result["response"].status,
mac_address: mac,
},
success: function (execution_record_id) {
$('#cover-spin').hide();
if(total == current)
{
alert('Successfully created execution record");
}
}
});
}
}
}
function call_endpoint() {
var values = new Array();
webpa = $('#Device-PA').is(":visible");
rpil = $('#Device-SN').is(":visible");
groupselect = $('#Group-Select').is(":visible");
parameter_name = $('#tr_object').val();
if (webpa) {
$.each($("input[name='checkBox[]']:checked").closest("td").next("td"), function () {
values.push($(this).text().trim())
});
m = values.length
} else {
$.each($("input[name='checkBox[]']:checked").closest("td").next("td"), function () {
values.push($(this).text().trim())
});
m = values.length
}
serialnumber = $('#pa_serialnumber').val();
oid = $('#sn_serialnumber').val();
protocol = {
pa: pa,
sn: sn,
}
if (pa) {
for (var i = 1; i <= m; i++) {
(function () {
var macAdd = values[i];
$.ajax({
method: "GET",
url: "get_object",
dataType: "json",
data: {
parameter: parameter_name,
mac: macAdd,
protocol: protocol,
serialnumber: serialnumber,
},
success: function (result) {
console.log(result);
NProgress.done();
console.log("result for webpa");
display_result(m,i);
},
statusCode: {
404: function () {
console.log("Call failed");
}
}
});
})();
}
}
}
result and mac is not defined in display_result function. result appears intended to be the resulting value of jQuery promise object returned from $.ajax(). Am not certain what mac is indented to be.
You can substitute $.when() and $.map() for for loop, return a jQuery promise object from call_endpoint(), include error handling, chain .then() to call_endpoint() call to execute alert() once.
function call_endpoint() {
return $.when.apply($, $.map(values, function(macAdd) {
return $.ajax().then(display_result)
}))
}
callEnpoint()
.then(function() {
alert('Successfully created execution record');
}, function(jqxhr, textStatus, errorThrown) {
console.error(errorThrown)
});
function display_result(reuslt) {
..
if (if (result["response"].status == "200")) {
return $.ajax() // remove `alert()` from `success`
}
return;
}

javascript object properties passing to asp.net mvc JsonResult actionmethod always null

I been trying to pass the array of objects to JsonResult action method created on Controller class, I tried all possible solution from different answer but none work.
Here is my js function:
function CalculateCost() {
var distancecost = [];
//prepare the List<DistanceCost> object
for (i = 0; i < _SELECTED_POINTS.length; i++) {
console.log('point::' + _SELECTED_POINTS[i]);
let dist = {
PlaceId: _SELECTED_POINTS[i].place_id,
PointSequence: _SELECTED_POINTS[i].PointSequence,
controlId: _SELECTED_POINTS[i].controlId,
FromLatitude: (i == (_SELECTED_POINTS.length - 1)) ? _SELECTED_POINTS[0].geometry.location.lat() : _SELECTED_POINTS[i].geometry.location.lat(),
FromLongitude: (i == (_SELECTED_POINTS.length - 1)) ? _SELECTED_POINTS[0].geometry.location.lng() : _SELECTED_POINTS[i].geometry.location.lng(),
ToLatitude: _SELECTED_POINTS[i].geometry.location.lat(),
ToLongitude: _SELECTED_POINTS[i].geometry.location.lng(),
DistanceType: 'Mile',
DistanceCalculateType: (i == (_SELECTED_POINTS.length - 1)) ? 'TotalDistance' : 'PickDrop',
TotalPrice: '0',
TotalDistance: '0'
};
console.log(dist);
distancecost.push({
dist
});
}
$.ajax({
method: 'GET',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
url: '/Dashboard/CalculateDistanceAndPrice',
data: JSON.parse(JSON.stringify({ 'distanceCost': distancecost })),
success: function (response) {
console.log('DistanceCalculation Response:: ' + JSON.stringify(response));
},
error: function (response) {
console.log(response);
}
});
}
Here is the Jsonresult action method:
Edit:
As Nicholas suggested, I change the type but still its not working, AFAIK POST we use when we are inserting any data and PUT when updating any data but here I'm just fetching the data by calculating the distance between each point:
$.ajax({
method: 'POST',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
url: '/Dashboard/CalculateDistanceAndPrice',
data: JSON.stringify({ 'distanceCost': distancecost }),
success: function (response) {
console.log('DistanceCalculation Response:: ' + JSON.stringify(response));
},
error: function (response) {
console.log(response);
}
});
Edit:
I changed the object creation but still no luck:
var DistanceCost = new Object();
DistanceCost.PlaceId = _SELECTED_POINTS[i].place_id;
DistanceCost.PointSequence = _SELECTED_POINTS[i].PointSequence;
DistanceCost.controlId = "";//_SELECTED_POINTS[i].controlId,
DistanceCost.FromLatitude = (i == (_SELECTED_POINTS.length - 1)) ? _SELECTED_POINTS[0].geometry.location.lat() : _SELECTED_POINTS[i].geometry.location.lat();
DistanceCost.FromLongitude = (i == (_SELECTED_POINTS.length - 1)) ? _SELECTED_POINTS[0].geometry.location.lng() : _SELECTED_POINTS[i].geometry.location.lng();
DistanceCost.ToLatitude = _SELECTED_POINTS[i].geometry.location.lat();
DistanceCost.ToLongitude = _SELECTED_POINTS[i].geometry.location.lng();
DistanceCost.DistanceType = 'Mile';
DistanceCost.DistanceCalculateType = (i == (_SELECTED_POINTS.length - 1)) ? 'TotalDistance' : 'PickDrop';
DistanceCost.TotalPrice = '0';
DistanceCost.TotalDistance = '0';
try to remove quotations of distanceCost
+> data: JSON.parse(JSON.stringify({ distanceCost: distancecost }))

Categories

Resources