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

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

Related

IE SCRIPT1002 match function returns error

I have a problem, my code works correctly in all browsers except IE.
IE returns me SCRIPT1002 Syntax error.
This line:
if(data.responseText.match(/Произошла.*/)) {
On next code:
localRequest: function(period, adapter, adapterType, errText){
let _this = this;
let iRow = rowInfo.iRow;
let aboutRow = rowInfo.aboutRow;
queryState = $.ajax({
type: 'get',
url: 'api/ds/cs',
dataType: 'json',
data: {
period: period,
adapter: adapter,
adapterType: adapterType,
errText: errText,
subject: iRow.value,
body: aboutRow.value
},
}).done(function (data) {
}).fail(function(data){
**if(data.responseText.match(/Произошла.*/)) {**
let errText = data.responseText.split(')',)
let errNumb = errText[0].split('(',)
alert('Не удалось сформировать проишествие: ' + errText[1] + ' №' + errNumb[1])
} else {
alert(data.responseText);
}
})
},

Function is returning value before running inner actions

Using SharePoint's PreSaveAction() that fires when the Save button is clicked, I am trying to run checks and manipulate fields before the form is saved. If PreSaveAction() returns true, the form will be saved and closed.
function PreSaveAction() {
var options = {
"url": "https://example.com/_api/web/lists/getbytitle('TestList')/items",
"method": "GET",
"headers": {
"Accept": "application/json; odata=verbose"
}
}
$.ajax(options).done(function (response) {
var actualHours = response.d.results[0].ActualHours
var personalHours = $("input[title$='Personal Hours']").val();
var regex = /^\d*\.?\d+$/ // Forces digit after decimal point
if (personalHours && regex.test(personalHours)) { // Run if input is not blank and passes RegEx
if (response.d.results[0].__metadata.etag.replace(/"/g, "") == $("td .ms-descriptiontext")[0].innerText.replace("Version: ", "").split('.')[0]) {
// Run if item's data from REST matches version shown in form
addChildItem(id, title, personalHours, actualHours)
}
}
});
return true; // firing before request above begins
}
The function is returning as true before running the jQuery AJAX call which runs addChildItem() that manipulates fields within the form and posts relevant data to a separate list.
function addChildItem(id, title, personalHours, actualHours) {
$.ajax({
method: "POST",
url: "https://example.com/_api/web/lists/getbytitle('ChildList')/items",
data: JSON.stringify({
__metadata: {
'type': 'SP.Data.ChildListListItem'
},
ParentID: id,
Title: title,
HoursWorked: personalHours
}),
contentType: "application/json;odata=verbose",
headers: {
"Accept": "application/json; odata=verbose",
},
success: function (data) {
console.log("success", data);
var actualHoursNum = Number(actualHours);
var personalHoursNum = Number(personalHours);
$("input[title$='Actual Hours']").val(actualHoursNum + personalHoursNum);
$("input[title$='Personal Hours']").val('');
// Input is getting cleared on save but shows previous number when form is opened again
},
error: function (data) {
console.log("error", data);
}
});
}
This is causing the form to accept the field value manipulations but only after the save and before the automatic closure of the form.
I need PreSaveAction() to wait until after addChildItem() is successful to return true but I'm not sure how to do this. I have tried using a global variable named returnedStatus that gets updated when addChildItem() is successful but the return value in PreSaveAction() still gets looked at before the jQuery AJAX call is ran.
How can I solve this?
I got a similar case by setting async: false to add user to group in PreSaveAction.
Original thread
<script language="javascript" type="text/javascript">
function PreSaveAction() {
var check = false;
var controlName = 'MultiUsers';
// Get the people picker object from the page.
var peoplePickerDiv = $("[id$='ClientPeoplePicker'][title='" + controlName + "']");
var peoplePickerEditor = peoplePickerDiv.find("[title='" + controlName + "']");
var peoplePicker = SPClientPeoplePicker.SPClientPeoplePickerDict[peoplePickerDiv[0].id];
if (!peoplePicker.IsEmpty()) {
if (peoplePicker.HasInputError) return false; // if any error
else if (!peoplePicker.HasResolvedUsers()) return false; // if any invalid users
else if (peoplePicker.TotalUserCount > 0) {
// Get information about all users.
var users = peoplePicker.GetAllUserInfo();
for (var i = 0; i < users.length; i++) {
console.log(users[i].Key);
var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/sitegroups(22)/users";
$.ajax({
url: requestUri,
type: "POST",
async: false,
data: JSON.stringify({ '__metadata': { 'type': 'SP.User' }, 'LoginName': '' + users[i].Key + '' }),
headers: {
"accept": "application/json;odata=verbose",
"content-type": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val()
},
success: function(data) {
console.log('User Added');
check = true;
},
error: function (error) {
console.log(JSON.stringify(error));
check = false;
}
});
}
}
} else {
console.log('No user');
}
return check;
}
</script>

Passing jQuery variables to Controller via AJAX

I am trying to send the variables from the GetTelephoneFunction to the AJAX query so it can reach the controller, but what I have tried does not work. Please help and thank you.
jQuery:
$.ajax({
type: "POST",
url: "/Status/GetUrlSource",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ "url": $("#urlInput").val(), "user": $("#user").val(), "pass":$("#pass").val(),"freq": $("#freqInput").val() }),
dataType: "html",
success: function (result, status, xhr) {
//Code
}
function GetUrlTelePhone(html, status, result) {
var geturlUser = url.split('?username=')[1].split('&password')[0];
var geturlPass = url.split("&password=")[1];
var getUrlMain = url.split("?")[0];
var geturlParameters = url.split("aspx")[1];
}
Controller
public string GetUrlSource(string url, string freq, string user, string pass)
{
//user = user.Substring(0, 10) != "?" ? "?" + user : user;
//pass = pass.Substring(0,20) != "&" ? "&" + pass : pass;
url = url.Substring(0, 4) != "http" ? "http://" + url : url;
string htmlCode = "";
using (WebClient client = new WebClient())
{
try
{
htmlCode = client.DownloadString(url);
}
catch (Exception)
{
return "Not Found";
}
}
//SqlConnect(url);
Hangfire(url,freq,user,pass);
return htmlCode;
}

How To Test Unstructured Javascript/JQuery

I'm faced with trying to add testing to a lot of code like the following. I know I can use mockjax to to intercept the ajax calls. But I don't how to test the $.ajax({...}) calls in isolation. I'd appreciate a good refactoring approach, but I'd also like to avoid rewriting the entire app.
I've gotten a start in other areas using qunit, and I like it. But I'm open to other suggestions too. How should I proceed?
function submitSync(repFrom, continuousRep, storedPassword) {
// var repTriggered = false;
if (repFrom !== '' && (storedPassword !== null || storedPassword !== "")) {
var secureHome = "http://" + homeUser + ":" + storedPassword + "#" + window.location.host + "/" + homeURL;
var theSource = repFrom.split("/");
var singleDocumentReplication = (theSource.length === 5);
/*
* DELETE existing replications. There will normally be no more than 1.
* Do not delete replications for application updates.
* Note that we don't allow the user to create continuous replications.
*/
$.getJSON(currentHost + '/_replicator/_all_docs', function (data) {
$.each(data.rows, function (i, theRow) {
$.ajax({
url: currentHost + '/_replicator/' + theRow.id,
type: "GET",
dataType: 'json',
async: false,
contentType: "application/json",
success: function (doc) {
if (doc._id !== "_design/_replicator" && (typeof doc.source !== 'undefined' && !doc.source.match(onlineBase + '/' + remoteDB))) {
$.ajax({
url: "/_replicator/" + doc._id + "?rev=" + doc._rev,
type: "DELETE",
contentType: "application/json",
success: function () {
console.log('Replication deleted: ' + doc._id + '?rev=' + doc._rev);
}
});
}
}
});
});
});
if (singleDocumentReplication) {
var theDoc = theSource[4];
var repFromBase = repFrom.substr(0, repFrom.indexOf(theDoc) - 1);
$.ajax({
url: "/_replicator",
type: "POST",
data: JSON.stringify({ "source": repFromBase, "target": secureHome,
"userCtx": { "name": homeUser, "roles": ["_admin", homeUser] },
"continuous": continuousRep,
"retries_per_request": 10,
"http_connections": 3,
"doc_ids": [theDoc]
}),
contentType: "application/json",
error: function () {
dialog(libLang.noSync);
},
success: function (message) {
if (message) {
dialog(libLang.synced);
}
repTriggered = true;
}
});
} else {
$.ajax({
url: "/_replicator",
type: "POST",
data: JSON.stringify({ "source": repFrom, "target": secureHome,
"userCtx": { "name": homeUser, "roles": ["_admin", homeUser] },
"continuous": continuousRep,
"retries_per_request": 10,
"http_connections": 3
}),
contentType: "application/json",
error: function () {
dialog(libLang.noSync);
},
success: function (message) {
if (message) {
dialog(libLang.synced);
}
repTriggered = true;
}
});
}
}
}
Looks like you've got a ton of code duplication. My recommendation would be to put your ajax calls into modules and pass the $.ajax as a dependency.
So:
function myModule(ajaxDependency, anyOtherDependency) { }
This way in your unit test you simply check to make sure your dependecies behave a certain way. And it looks like it will eliminate all your DRY issues.

Readystate 4, status 200 , parseerror

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.

Categories

Resources