AJAX call doesn't parse JSON - ajax

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.

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

ExtJS: How to hide specific data on store with filtering?

I want to hide a record on Grid that returns from server.
I've setted a filter on store and can reach that specific data but how I'll handle to hide/ignore this record?
fooStore: {
....
filters: [
function(item) {
let me = this;
let theRecord = item.data.status === MyApp.STATUS; //true
if (theRecord) {
console.log(theRecord); //True
console.log("So filter is here!!")
//How to hide/ignore/avoid to load this specific data record to load Grid??
}
}
]
},
Returned JSON;
{
"success": true,
"msg": "OK",
"count": 3,
"data": [
{
//Filter achives to this record and aim to hide this one; avoid to load this record.
"id": 102913410,
"status": "P"
},
{
"id": 98713410,
"status": "I"
},
{
"id": 563423410,
"status": "A"
}
]
}
I can't save my fiddle cause i don't have sencha forum's account so i give you my code :
Ext.application({
name : 'Fiddle',
launch : function() {
var model = Ext.create('Ext.data.Model', {
extend: 'Ext.data.Model',
fields: [
{name: 'id', type: 'int'},
{name: 'status', type: 'string'},
]
});
var store = Ext.create('Ext.data.Store', {
autoLoad: true,
model: model,
proxy: {
type: 'ajax',
url: 'data.json',
reader: {
type: 'json',
rootProperty: 'data'
}
},
filters: [function(item) {
if (item.data.status === "P") {
return true;
}
else {
return false;
}
}],
listeners: {
load: {
fn: function() {
console.log(this.getRange());
}
}
}
});
}
});
Also i create data.json like this :
{
"success": true,
"msg": "OK",
"count": 3,
"data": [{
"id": 102913410,
"status": "P"
}, {
"id": 98713410,
"status": "I"
}, {
"id": 563423410,
"status": "A"
}]
}
I thinks it's near to you'r code and after the loading of the store the filter work as you can this :
Here is sencha fiddle link : https://fiddle.sencha.com/#view/editor
If this can't work, i don't understand what the fuck doing...

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 in Chrome extension not working

Trying to send an ajax request in a chrome extension. I have confirmed the request returns a 200 response, it should just console.log to 'test'. I'm not sure if there's some async problems here? I have read chrome extension 'addListener' documentation.
content.js
chrome.runtime.sendMessage({greeting: "hello"}, function(response) {
console.log(response.farewell); //this is not working
return true;
});
background.js
require('./modules/communicate.js');
var communicate = new Communicate();
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
if (request.greeting === "hello") {
response = communicate.talk('http://127.0.0.1:5000/test', 'GET');
sendResponse({
farewell: response
});
return true; //doing this correctly?
}
});
communicate.js
Communicate = function() {
this.talk = function(url, method) {
$.ajax({
url: url,
method: method,
success: function(result) {
return result;
}
});
};
};
manifest.json
{
"manifest_version": 2,
"icons": { "128": "images/icon.png" },
"browser_action": {
"default_icon": "images/icon.png",
"default_popup": "html/popup.html"
},
"background": { "scripts": ["js/background.js"] },
"content_scripts": [{
"matches": [ "http://*/*", "https://*/*" ],
"js": [ "js/content.js" ]
}],
"permissions": [ "<all_urls>" ],
"web_accessible_resources": [ "js/*", "html/*", "css/*", "images/*" ],
"content_security_policy": "script-src 'self'; object-src 'self'"
}

error on loading json data

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

Resources