error on loading json data - ajax

I am trying to load .json data into my web app and it never can achieve success.
It always returns the error function.
Here is my .js file:
$(document).ready(function () {
var output = $('#stage');
$.ajax({
url: 'http://www.haverhill-ps.org/ios/app/data/calendar-json.json',
dataType: 'json',
timeout: 5000,
success: function (data) {
$.each(data, function (i, item) {
var eventInfo = '<h1>' + item.month + '</h1>' + '<p>' + item.date + '<br>' + item.time + '</p>';
output.append(eventInfo);
});
},
error: function () {
output.text('There was an error loading the data.');
}
});
});
Here is the json data:
{
"month": "June", //November
"date": "10", //10
"time": "5PM", //5PM
}, {
"month": "July", //November
"date": "4", //10
"time": "1PM", //5PM
}
Then, within my html I have a div setup:
<div id="stage">Run here...</div>

the returned data is not valid json.
your are missing [and ] around the result and comments are not valid in json.
the , at the end of the last element of each object is also invalid. you can validate your json at e.g. http://jsonlint.com/
a valid json would look this way:
[{
"month": "June",
"date": "10",
"time": "5PM"
}, {
"month": "July",
"date": "4",
"time": "1PM"
}]

May be you would like to see what is the error, do it this way
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}

Related

DataTable can not pass parameters from Ajax to ASP.NET MVC controller

I have this problem when trying to pass a string parameter from DataTable with Ajax to an ASP.NET MVC controller: the parameter is not being sent.
I tried many forms of "data:" options. Please help me, I think I'm missing something important.
When (as a test) I initialize the parameter at the beginning of the controller with ttt="CO" everything goes fine!
$('#tblVacation').DataTable({
"ajax": {
"url": '/Vacation/LoadData2',
"contentType": "application/json;charset=utf-8",
"type": 'GET',
"dataType": 'JSON',
"data" : ' { ttt: "CO" }'
"dataSrc": "",
},
"columns": [
{ "data": "vacationId", width: "5%" },
{ "data": "operatorId", width: "3%" },
{ "data": "operator", width: "10%" },
{ "data": "type", width: "3%" },
]
});
And the controller is:
[HttpGet]
public ActionResult LoadData2(string ttt)
// ttt="CO";
{
List<Vacation> data = null;
try
{
data = DB.Vacations.Include(x => x.Operator).ToList();
var result = data.Select(x => new Vacation_VM
{
VacationId = x.VacationId,
OperatorId = x.OperatorId,
Vacation_doc = x.Vacation_doc,
Operator = x.Operator.Name,
Type = x.Type,
}).Where(m => m.Type == ttt);
return new JsonResult(result);
}
catch (Exception ex)
{
ViewBag.Message = ex.Message;
}
return new JsonResult(null);
}
I also tried with
var entity = {
ttt: "CO"
}
var dataToSend = JSON.stringify(entity);
and
"data": function () {
return dataToSend;
},
but it's still not working. I will need in the future to pass multiple parameters.
Thanks a lot, I will appreciate any advice.
Replace the ajax call part with the followings:
"ajax": {
type: 'GET',
url: '/Vacation/LoadData2',
data: { ttt: "CO" },
dataType: 'JSON',
async: true,
cache: false,
},

Datatables.net is not loading any data using AJAX

I am trying to get some data from an API and load into Datatables (datatable.net). I have completed the code as per guide and it doesn't load at all.
AJAX completes the request successfully.
Code below:
function loadTable(api) {
$.ajax({
url: api,
type: 'GET',
dataType: 'json',
"dataSrc": "",
beforeSend: function () {
console.log('\"Data collection\" query operation triggered')
$(".overlay").show(); //We are showing loading spinner here
},
headers: { Authorization: 'Basic XXXX },
success: function (data, textStatus, xhr) {
//Populate Table
$('#datatable').DataTable({
"columns": [
{ "data": "DataObjectName" },
{ "data": "SourceObject" },
{ "data": "IndnexType" },
{ "data": "ObjectType" },
{ "data": "FeedType" },
{ "data": "BusinessUnit" },
{ "data": "VersionId" },
{ "data": "Unit" },
{ "data": "Unit" },
],
"bDestroy": true
})
console.log('\"Data collection\" query operation succesfully completed');
},
error: function (xhr, textStatus, errorThrown) {
console.log('\"Data collection\" query operation failed. Error : ' + errorThrown);
showNotification('top', 'right', 'Error while performing ' + operation + '. Error : ' + errorThrown, 'danger');
},
complete: function () {
$(".overlay").hide(); //We are showing loading spinner here
console.log('\"Data collection\" query operation task completed');
}
});
}

Render HTML of an AJAX response

I'm using Select2 AJAX remote option to fetch data:
$('#t').select2({
ajax: {
url: '../ajax/results.php',
data: function (params) {
return {
search: params.term,
page: params.page || 1
};
}
}
});
So far so good, result are returned like this (please notice the <small> tag):
{
"results": [
{
"id": "1",
"text": "Doe Joe, <small>Mr.</small>"
},
{
"id": "2",
"text": "Smith Anne, <small>Mrs.</small>"
},
{
"id": "3",
"text": "Rossi Mario, <small>Mr.</small>"
},
...
],
"pagination": {
"more": false
}
}
In the <select>, the <small> tag is printed as-is, instead of being parsed.
Select2 docs says that HTML are not rendered by default and that the rendered result must be wrapped in a jQuery object to work, but no further example is given.
All the examples that involve templateResult, indeed, does not give feedback on how to pass AJAX result (i.e. https://select2.org/dropdown#templating )
Please, any help?
The templating example is right, I just need to wrap everything in a <span> tag for it to work:
function formatItem (item) {
if (!item.id) {
return item.text;
}
return $('<span>' + item.text + '</span>');
}
$('#t').select2({
ajax: {
url: '../ajax/results.php',
data: function (params) {
return {
search: params.term,
page: params.page || 1
};
}
},
templateResult: formatItem,
templateSelection: formatItem
});

Why do I get error message on wikipedia api?

Can someone tell me what is wrong this code?
$.ajax({
"url":"https://en.wikipedia.org/w/api.php?",
"dataType": "jsonp",
"action": "opensearch",
"format": "json",
"search": "new york",
"namespace": "0",
"limit": "3",
"formatversion": "1",
success: function(response){
console.log(response);
}
});
Why do I get the following error message?
Refused to execute script from 'https://en.wikipedia.org/w/api.php?&callback=jQuery111105448874468459555_1518288921946&_=1518288921947' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled.
Thank you.
The following are not ajax parameters (instead they are api parameters):
"action": "opensearch",
"format": "json",
"search": "new york",
"namespace": "0",
"limit": "3",
"formatversion": "1",
You can pass those values as query string, changing your url from:
"url":"https://en.wikipedia.org/w/api.php?",
to:
"url":"https://en.wikipedia.org/w/api.php?"+ $.param(apiParams),
where the api parameter is:
var apiParams = {action: 'opensearch', search: 'new york', limit: 3, namespace: 0, formatversion: 1, format: 'json'};
or you can use the data parameter like:
data: apiParams,
The snippet:
var apiParams = {action: 'opensearch', search: 'new york', limit: 3, namespace: 0, formatversion: 1, format: 'json'};
$.ajax({
"url":"https://en.wikipedia.org/w/api.php?" + $.param(apiParams),
"dataType": "jsonp",
//data: apiParams,
success: function(response){
console.log(JSON.stringify(response));
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

AJAX call doesn't parse JSON

I have the following piece of JSON:
[
{
"number": "0",
"name": "Russell Westbrook",
"attemptedFG": [
{
"x": "333",
"y": "97",
"made": "true",
"assisted": "false"
},
{
"x": "571",
"y": "389",
"made": "true",
"assisted": "false"
}
],
"attemptedFT": [
{
"made": "true"
},
{
"made": "false"
}
],
"rebounds": "5",
"assists": "8",
"steals": "2",
"blocks": "1",
"turnovers": "3",
"fouls": "4"
}
]
and I'm trying to parse it with this AJAX call using ReactJS:
loadStatsFromServer: function() {
$.ajax({
url: this.props.url,
dataType: 'json',
success: function(data) {
this.setState({data: data});
}.bind(this),
error: function(xhr, status, err) {
console.error(this.props.url, status, err.toString());
}.bind(this)
});
}
All the values in the JSON are still stringified after the AJAX call succeeds. The server sends back a response header with 'Content-Type', 'application/json' so I'm not sure why it's not parsing.
Server-side call:
app.get('/stats.json', function(req, res) {
fs.readFile('stats.json', function(err, data) {
res.setHeader('Content-Type', 'application/json');
res.send(data);
});
});
Thanks a bunch.
When you send a stringified json object from server to client, you need to parse that object to readable javascript object. So, you need to parse json in success event of ajax request:
success: function(data) {
var result = $.parseJSON(data);
}
Now result is a javascript readable object.

Resources