Requested JSON Parse Error when sending two variables values using $.ajax - json

The code below is inside script of view.cshtml
All I want to achieve is parse the values MinDate and MaxDate into my controller.
But I always get Requested JSON Parse Error. I used the variable MinDate and MaxDate in data {}
same error i even tried to pass the raw default MinDate and MaxDate into data {}
and I still got same error. What could the problem be?
// Add event listeners to the two range filtering inputs
$('#FromDate').on("keyup change", function () {
var MinDate = $.datepicker.formatDate("dd-mm-yy", $("#FromDate").datepicker("getDate"));
var MaxDate = $.datepicker.formatDate("dd-mm-yy", $("#ToDate").datepicker("getDate"));
$.ajax({
url: '/CAACAllExpense/LEADFilter',
data: { 'data1': "12-10-2019", 'data2': "14-10-2019" },
dataType: 'json',
success: function (data) {
alert(data.success);
},
error: function (jqXHR, exception) {
var msg = '';
if (jqXHR.status === 0) {
msg = 'Not connect.\n Verify Network.';
} else if (jqXHR.status == 404) {
msg = 'Requested page not found. [404]';
} else if (jqXHR.status == 500) {
msg = 'Internal Server Error [500].';
} else if (exception === 'parsererror') {
msg = 'Requested JSON parse failed.';
} else if (exception === 'timeout') {
msg = 'Time out error.';
} else if (exception === 'abort') {
msg = 'Ajax request aborted.';
} else {
msg = 'Uncaught Error.\n' + jqXHR.responseText;
}
$('#Error').html(msg);
},
});
});

data needs to be a string:
data = JSON.stringify({ 'data1': "12-10-2019", 'data2': "14-10-2019" })

Related

Uncaught SyntaxError: Unexpected number in kendo ui

I have kendo ui popup which sends a request to an action method. The action method returns json and then my code breaks in the kendo.all.min.js file and the error method says Uncaught SyntaxError: Unexpected number
My kendo code below:-
var cloudStore = new kendo.data.DataSource({
//batch: true,
pageSize: 25,
transport: {
create: {
url: "/Admin/AddCloudStore", //(/ControllerName/ActionName)
type: "POST"
},
update: {
url: "/Admin/UpdateCloudStore",
type: "POST"
},
parameterMap: function (data, operation) {
console.table(data);
var result = {};
// For update and create send the entire object
if (operation === "update" || operation === "create") {
return data;
//return JSON.stringify({ service: data });
}
return null;
}
},
schema: {
model: cloudStoreModel,
errors: "error"
},
error: function (e) {
console.log(e);
}
});
Am I suppose to return something else from the action? Any help on the issue would be appreciated
Edit: Okay seems like the problem is with what I am return from my .net action method. Adding my action method below:-
public ActionResult AddCloudStore(DataAccess.Model.domain_config_cloud store)
{
try
{
using (var context = new DataAccess.Model.CondadoMediaVault())
{
if (store.cld_cmp_key <= 0) store.cld_cmp_key = Session["sel_domain_key"].ConvertToLong();
var list = context.domain_config_cloud.Where(x => x.cld_cmp_key == store.cld_cmp_key && x.cld_is_active && x.cld_category == "primary").ToList();
if (list.Count > 0)
return Json("There is already a primary cloud store."); //returning string
long user_key = 0;
long.TryParse(Convert.ToString(Session["user"]), out user_key);
var maxKey = context.domain_config_cloud.OrderByDescending(x => x.cld_key).FirstOrDefault();
if (maxKey == null || maxKey.cld_key == 0)
return Json("Error"); //returning string
else
store.cld_key = maxKey.cld_key + 1;
context.domain_config_cloud.Add(store);
context.SaveChanges();
}
}
catch (Exception ex)
{
MediaVault.BLL.ErrorLoggging.DbExceptionLog.LogError(ex);
}
return Json(store); //returning object
}
So the kendo ui code breaks when a string is returned from the action method. If an object is returned the code does not break. What is the exact return type which is expected by kendo ui?

Nested AJAX call in React redux

So I'm working on some demoware and I have two AJAX calls, the first is just a last modified date, to let me know whether to fetch data from the second. This works, but I feel like there's a smarter way to do this for real applications, and I'm just a UI monkey trying to come up in the world, any advice is much appreciated.
componentDidMount() {
this.getJson();
setInterval(this.getJson.bind(this), 1000);
}
getJson() {
const el = this;
const isModified = (date) => {
let mod = false;
if (this.state.lastModified == date) {
console.log('no change');
} else {
mod = true;
console.log({
'previously modified': this.state.lastModified,
'newly modified': date
});
el.setState({lastModified: date});
}
return mod;
}
this.serverRequest = $.ajax({
url: 'URL_LAST_MODIFIED',
success: function(result) {
const lastModified = $.parseJSON(result).LastModifiedDateTime;
if (isModified(lastModified)) {
$.ajax({
url: 'URL_DATA',
success: function(result2) {
const result2Obj = $.parseJSON(result2);
el.setState({data: result2Obj});
},
error: function(xhr, status, err) {
alert(err.toString());
}
})
}
},
error: function(xhr, status, err) {
}
});
}
I think it is realted to this:
https://github.com/reactjs/redux/issues/1676
The idea is create a action for the first ajax call... and on success dispatch another action to execute the second call.

JSON data from web method for Donut chart

I am trying to provide a json string to google pie chart but every time its saying that json format is invalid. I have tried numerous ways to provide json string.
Please follow the code.
//ASP code
function drawDonutChart(chartType) {
//alert('Under Donut Chart');
var objCombo = {};
objCombo.siteURL = window.location.protocol + "//" + window.location.host + _spPageContextInfo.siteServerRelativeUrl;
objCombo.chartType = chartType;
var jsonData = $.ajax({
type: "POST",
contentType: 'application/json',
url: 'Dashboard.aspx/GetDonutChartData',
data: JSON.stringify(objCombo),
//beforeSend: function () { alert("before send"); },
//complete: function () { alert("complete"); },
success: function (data) {
var donutChartData = new google.visualization.DataTable(data.d);
var options = {
legend: 'right',
pieSliceText: 'value',
pieHole: 0.4,
chartArea: {
width: 300, left: 20, top: 20, right: 20, bottom: 10
}
};
if (donutChartData.getNumberOfRows() > 1) {
var donutChart = new google.visualization.PieChart(document.getElementById('programmatic_DonutChart'));
donutChart.draw(donutChartData, options);
}
else {
document.getElementById('programmatic_DonutChart').innerHTML = "No data to display!";
}
},
error: function (data) {
if ($("meta[name=debug]").attr("content") == "true") {
//Full Error when debugging
var errDoc = window.open();
errDoc.document.write(data.responseText);
errDoc.document.close();
}
else {
// generic error message for production use
alert("An unexpected error occurred.");
} return false;
}
});
return false;
}
//Web Method
[WebMethod]
public static string GetDonutChartData(string siteURL, string chartType)
{
string jsonData = "{'cols': [{'id':'','label':'Topping','pattern':'','type':'string'},"+
"{'id':'','label':'Slices','pattern':'','type':'number'}"+
"],'rows': [{'c':[{'v':'Mushrooms','f':null},{'v':3,'f':null}]},{'c':[{'v':'Onions','f':null},{'v':1,'f':null}]},{'c':[{'v':'Olives','f':null},{'v':1,'f':null}]},{'c':[{'v':'Zucchini','f':null},{'v':1,'f':null}]},"+
"{'c':[{'v':'Pepperoni','f':null},{'v':2,'f':null}]}]}";
//return list;
return jsonData;
}
//Error Message:
Uncaught Error: Invalid JSON string: "{'cols': [{'id':'','label':'Topping','pattern':'','type':'string'},{'id':'','label':'Slices','pattern':'','type':'number'}],'rows': [{'c':[{'v':'Mushrooms','f':null},{'v':3,'f':null}]},{'c':[{'v':'Onions','f':null},{'v':1,'f':null}]},{'c':[{'v':'Olives','f':null},{'v':1,'f':null}]},{'c':[{'v':'Zucchini','f':null},{'v':1,'f':null}]},{'c':[{'v':'Pepperoni','f':null},{'v':2,'f':null}]}]}"
Please help!!

Mapping http response from node to json file

I am working on a solution where the web server (node with express) will be using request package to fetch data from a web api.
The data return (if contains validation error status code), will be matched again the value and return the corresponding error message. How could it be achieve?
It would be something like this:
var options = {
method: 'POST',
url: 'apiUrl'
}
var response = function (error, response, body) {
if(!error && response.statusCode == 200){
res.jsonp(body);
} else {
if (body.language == 'en') {
// map the reponse body error status code to en.json
} else if (body.language == 'jp')
// map the response body error status code to jp.json
}
}
request({
options, response
})
Default body response for validation error
{
'language': 'en',
'error': [{ 'ErrorCode': '1000', 'ErrorCode': '1001'}]
}
Final body response (after processing)
{
'language': 'en',
'error': [{'ErrorMessage': 'Invalid data format', 'ErrorMessage': 'Invalid Password'}]
}
Resource file for different language of validation (static in server)
en.json
{
'1000': 'Invalid date format',
'1001': 'Invalid password',
'1002': ...
'1003': ...
...
'1999': ...
}
jp.json
{
'1000': 'japan translation',
'1001': 'japan translation 2',
'1002': ...
'1003': ...
...
'1999': ...
}
Here you see how to it.
I'm using fs module to open the JSON file. and I'm using map to convert the errorCode array to errorMessage array
var response = function(error, response, body) {
if (!error && response.statusCode == 200) {
res.jsonp(body);
} else {
// Set defaut language.
if (!body.language.match(/en|jp|iw/)) body.language = 'en'
// You must specify default language for security reasons.
// Open the file, and convert to JSON object
var j = JSON.parse(
require('fs').readFileSync(__dirname + '/' + body.language + '.json')
)
res.jsonp({
language: body.language,
// Convert error:[{errorCode}] array to the messages from the JSON
error: body.error.map(function(v) {
return j[v.ErrorCode]
})
})
}
}

How to return result from function that has an $.ajax call

I'll say right off the bat that this question seems to address the same situation, but for the life of me I'm not seeing what the solution/answer is there. Perhaps someone just needs to "spell it out" more clearly for me!
I have the following function:
function CheckIfUrlExists(checkUrl) {
var exists = '';
$.ajax({
type: 'POST',
url: '../scripts/branchAdmin.php',
data: {checkUrl: checkUrl},
cache: false,
success: function(response) {
console.log('response: ' + response);
if (response === 'true') {
exists = 'true';
} else if (response === 'false') {
exists = 'false';
}
},
error: function(response) {
// return false and display error(s) from server
exists = 'false';
}
});
console.log('exists: ' + exists); // always displays empty string, regardless of what the php script returns
return exists;
}
And I'm calling it with this:
var exists = CheckIfUrlExists($tr.find('input.editUrl').val());
if (exists === 'false') {
//if (!CheckIfUrlExists($tr.find('input.editUrl').val())) {
// New URL entered, verify user want to save it
$('#confirmAddNewUrlDialog').data('row', $tr).dialog('open');
... // code to handle result
}
How can I get the "CheckIfUrlExist() function to return a true or false (or any value for that matter) so I can use it in the above code?
Make the ajax call async option to false. then you'll get the result.
see the link https://stackoverflow.com/a/1531710/399414
$.ajax({
type: 'POST',
async: false,
url: '../scripts/branchAdmin.php',
...