JavaScript issues with json data [duplicate] - javascript

This question already has answers here:
Access-Control-Allow-Origin error sending a jQuery Post to Google API's
(7 answers)
Closed 8 years ago.
I'm trying to fetch and parse json data so I could output it to a blank HTML file. The problem that keeps occurring to me is that if I fetch the data and parse it I get a Uncaught TypeError: Cannot read property 'SOCENGPRE' of undefined error. If I fetch the json data in dataType: "text" format I get the XMLHttpRequest cannot load <api url> No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. error. The website is on a local machine and I cannot edit the server to be cross-platformed because of person reasons. The code looks like this :
var myDataVar;
function main() {
$.ajax({
url: "http://api&leagues=SOCENGPRE&format=jsonp&callback=?",
dataType: "json",
success: function (data) {
myDataVar = $.parseJSON(data);
getUpcomingFixtures();
}
});
}
function getUpcomingFixtures() {
for (var i = 0; i <= myDataVar.SOCENGPRE.fixtures.length - 1; i++) {
console.log(myDataVar.SOCENGPRE.fixtures[i].id);
console.log(myDataVar.SOCENGPRE.fixtures[i].home_team + " vs " + myDataVar.SOCENGPRE.fixtures[i].away_team);
}
}
An example of the data being fetched looks like this :
{
"SOCENGPRE": {
"league_name": "Barclays Premier League",
"league_phid": null,
"league_type": null,
"fixtures": [{
"id": "64714",
"code": "SOCENGPRE",
"event_slug": "west_ham-tottenham-1401290",
"start": "1399117500",
"home_team": "West Ham",
"home_team_phid": null,
"home_team_logo": "\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t523.png",
"home_team_short": "",
"away_team": "Tottenham",
"away_team_phid": null,
"away_team_logo": "\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t498.png",
"away_team_short": "",
"phid": null
}, {
"id": "64711",
"code": "SOCENGPRE",
"event_slug": "manchester_u-sunderland-1401286",
"start": "1399125600",
"home_team": "Manchester U",
"home_team_phid": null,
"home_team_logo": "\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t20790.png",
"home_team_short": "Man U",
"away_team": "Sunderland",
"away_team_phid": null,
"away_team_logo": "\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t382.png",
"away_team_short": "",
"phid": null
}, {
"id": "64712",
"code": "SOCENGPRE",
"event_slug": "stoke-fulham-1401288",
"start": "1399125600",
"home_team": "Stoke",
"home_team_phid": null,
"home_team_logo": "\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t389.png",
"home_team_short": "",
"away_team": "Fulham",
"away_team_phid": null,
"away_team_logo": "\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t379.png",
"away_team_short": "",
"phid": null
}]
}
}
My goal is to just fetch the fixture id and the two teams competing. Any clue what I'm doing wrong?

Try using the below code , don't parse the JSON again as it is already handled, assuming string is your JSON object.
At beginning of script declare this variable result as array;
var result = [];
function getUpcomingFixtures() {
$.each( string , function ( i , val) {
$.each( val['fixtures'] , function ( k , fixturesData) {
result.push( { id: fixturesData.id ,
hometeam : fixturesData.home_team ,
awayteam : fixturesData.away_team
}
);
});
});
}

Related

Extract text from json response array from api.ai

I am trying to built chatbot that fetches json response from api.ai. I need to display messages part from below json response.
{
"id": "ae66f8e4-a047-478a-8108-8b0147610f18",
"timestamp": "2017-09-28T05:02:03.552Z",
"lang": "en",
"result": {
"source": "agent",
"resolvedQuery": "hi",
"action": "",
"actionIncomplete": false,
"parameters": {},
"contexts": [],
"metadata": {
"intentId": "d2f3c8bd-fc1b-4b6b-9d3d-08b6be93364e",
"webhookUsed": "false",
"webhookForSlotFillingUsed": "false",
"intentName": "greetings"
},
"fulfillment": {
"speech": "Hi.Please enter your query.",
"messages": [
{
"type": 0,
"speech": "Hi.Please enter your query."
}
]
},
"score": 1
},
"status": {
"code": 200,
"errorType": "success"
},
"sessionId": "saurabh"
}
Below is the sample piece of code, but it is unable to fetch speech from messages part in spokenResponse variable.
function prepareResponse(val) {
var debugJSON = JSON.stringify(val,undefined, 2);
var spokenResponse = val.messages.speech;
respond(spokenResponse);
debugRespond(debugJSON);
}
I get below error:
script.js:33 Uncaught TypeError: Cannot read property 'speech' of undefined
at prepareResponse (script.js:33)
at Object.success (script.js:21)
at i (jquery-3.2.1.min.js:2)
at Object.fireWith [as resolveWith] (jquery-3.2.1.min.js:2)
at A (jquery-3.2.1.min.js:4)
at XMLHttpRequest.<anonymous> (jquery-3.2.1.min.js:4)
However, when I try to fetch source from result part it fetches correctly.
var spokenResponse = val.result.source;
I am new to ajax and Json, Kindly help.
You have to access messages via the fulfillment property. Note that messages contains an array of objects, so in order to get to the speech property of the first object, you have to access the object in the first index.
var spokenResponse = val.fulfillment.messages[0].speech;
If you wanted to iterate through all messages (assuming you have more than one message):
var messageArr = val.fulfillment.messages;
var speechArr = [];
for (var i = 0; i < messageArr.length; i++) {
speechArr.push(messageArr[i].speech);
}
This will give you an array of speech messages.

Values from a JSON response in ajax returning as undefined

I'm having some problems when trying to retrieve values from a JSON response sent via the $.post() method in jQuery. Here is the script:
var clickedName = $('#customerId').val();
$.post("/customer-search", { name: clickedName }).done( function(response) {
var results = $.parseJSON(response);
console.log(results);
$('#account-name').html(results.firstname + ' ' + results.lastname);
$('#email').html(results.email);
$('#telephone').html(results.telephone);
if (results.fax) {
$('#fax').html(results.fax);
} else {
$('#fax').html('n/a');
}
$('#personal').fadeIn();
return false;
});
Just to explain, I'm using twitter typeahead in a Symfony2 project, and basically this script will fire when a name is clicked (selected) from the list after typing. The customer-search URL runs a search of the database as follows:
$q = $request->request->get('name');
$em = $this->getDoctrine()->getManager();
$customer = $em->getRepository('AppBundle:Oc73Customer')->findLikeName($q);
$addresses = $em->getRepository('AppBundle:Oc73Address')->findByCustomerId($customer[0]['customerId']);
$results = array();
$results['customer'] = $customer;
$results['addresses'] = $addresses;
return new Response(json_encode($results));
Which will successfully return a Json encoded response, and the value of 'response' which is printed in the console (as per the jquery above) is:
{
"customer": [{
"firstname": "Mike",
"lastname": "Emerson",
"email": "xxxx#xxxx.co.uk",
"telephone": "01234 5678910",
"fax": null,
"password": "8e1f951c310af4c20e2cd6b68dee506ac685d7ae",
"salt": "e2b9e6ced",
"cart": null,
"wishlist": null,
"newsletter": 0,
"addressId": 84,
"customerGroupId": 1,
"ip": null,
"status": 1,
"approved": 1,
"token": null,
"dateAdded": {
"date": "2016-02-16 12:59:28.000000",
"timezone_type": 3,
"timezone": "Europe/Berlin"
},
"availCredit": null,
"customerId": 75
}],
"addresses": [{}]
}
I am trying to retrieve the customer details by using the method I always use, so to get the firstname, I use results.firstname where results is a parsed JSON string, as written in my jQuery response.
However, all I get from results.firstname is undefined, even when it clearly is defined. So, basically, I'm wondering what I am doing wrong?
Hope someone can shed some light on my problem.
The properties you're trying to access are objects in the customer array, not on the parent object itself. Assuming that the response only ever contains one customer object then you can use result.customer[0], like this:
$.post("/customer-search", { name: clickedName }).done(function(response) {
var results = $.parseJSON(response);
var customer = response.customer[0];
$('#account-name').html(customer.firstname + ' ' + customer.lastname);
$('#email').html(customer.email);
$('#telephone').html(customer.telephone);
$('#fax').html(customer.fax ? customer.fax : 'n/a');
$('#personal').fadeIn();
});
If it's possible that multiple customer objects will be returned in the array the you would need to amend your code to loop through those objects and build the HTML to display them all - without using id attributes.
I was able to access it like "results.customer[0].firstname"
var cus =
{
"customer": [{
"firstname": "Mike",
"lastname": "Emerson",
"email": "xxxx#xxxx.co.uk",
"telephone": "01234 5678910",
"fax": null,
"password": "8e1f951c310af4c20e2cd6b68dee506ac685d7ae",
"salt": "e2b9e6ced",
"cart": null,
"wishlist": null,
"newsletter": 0,
"addressId": 84,
"customerGroupId": 1,
"ip": null,
"status": 1,
"approved": 1,
"token": null,
"dateAdded": {
"date": "2016-02-16 12:59:28.000000",
"timezone_type": 3,
"timezone": "Europe/Berlin"
},
"availCredit": null,
"customerId": 75
}],
"addresses": [{}]
}
alert(cus.customer[0].firstname);

Invalid JSON,Unexpected Token [duplicate]

This question already has an answer here:
AngularJS $http.post error Unexpected token F
(1 answer)
Closed 7 years ago.
I'm trying to send JSON data to server using angular, But getting JSON.parse error in firefox and Unexpected token in chrome.
It works sometime and throws error sometime.
I consider it is because of the timestamp I'm using to create some keys.
{
"genericformfieldId": "1",
"userId": "2",
"formData": {
"_1443551400000": [
{
"mValue": "HARYANA",
"type": "DropDown",
"name": "selectState"
}
],
"_1443637800000": [
{
"mValue": "CHHATTISGARH",
"type": "DropDown",
"name": "selectState"
}
],
"_1443810600000": [
{
"mValue": "sac",
"type": "SingleLineText",
"name": "departureFrom"
}
]
}
}
Please suggest.
Adding code for posting data
$http({
method: 'POST',
url: Url,
headers: { "Content-Type": "application/json" },
data: formData
})
.success( function( response, status, headers, config ) {
console.log( response );
if( response ) {
deferred.resolve( response );
}
})
.error( function( response, status, headers, config ) {
deferred.reject( null );
});
If you JSON.parse an object the "Unexpected token o" is thrown simply because you are trying to parse object.toString(), which is [object Object]. Try to JSON.parse('[object Object]'); ;)
This should work for you
var data = '{
"genericformfieldId": "1",
"userId": "2",
"formData": {
"_1443551400000": [
{
"mValue": "HARYANA",
"type": "DropDown",
"name": "selectState"
}
],
"_1443637800000": [
{
"mValue": "CHHATTISGARH",
"type": "DropDown",
"name": "selectState"
}
],
"_1443810600000": [
{
"mValue": "sac",
"type": "SingleLineText",
"name": "departureFrom"
}
]
}
}';
JSON.parse(data);
This answer https://stackoverflow.com/a/12719860/1868660 explains
Unexpected token ILLEGAL(…) issue
You must clean input json.
Check this:
https://jsfiddle.net/am190cv5/
Here's the source:
var s = '{"genericformfieldId": "1","userId": "2","formData": {"_1443551400000": [{"mValue": "HARYANA","type": "DropDown","name": "selectState"}],"_1443637800000": [{"mValue": "CHHATTISGARH","type": "DropDown","name": "selectState"}],"_1443810600000": [{"mValue": "sac","type": "SingleLineText","name": "departureFrom"}]}}';
var result = JSON.parse(s);
console.log(result);
Open the console and look the result.

Attempting to parse or assign JSON response: Response is read as [object Object] [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
Using Flickr API, Javascript/JQuery, and AJAX, I have the follow code:
function getRequest(arguments)
{
var requestinfo;
$.ajax({
type: 'GET',
url: flickrurl + '&'+ arguments + '&jsoncallback=jsonCallback',
async: false,
jsonpCallback: 'jsonCallback',
dataType: 'jsonp',
success: function (json)
{
requestinfo = json;
//Parse attempt requestinfo = $.parseJSON(json);
//Old method return json;
}
});
return requestinfo;
}
When the response is received and I attempt to assign the json (the response) data to the variable, requestinfo, (or even if I do a straight 'return json' line) I get an error indicating the returned value is undefined. Upon fooling with the success function, I notice that any attempts to parse the response fails due to 'json' being read as [object Object] instead of the JSON response.
Is the response already in array format? If not, how can I get it to that point?
Here is an example JSON response (there are multiple types as different requests are needed to receive all needed information (Flickr API):
{
"collections": {
"collection": [
{
"id": "122388635-72157643471284884",
"title": "Test Gallery 2",
"description": "Test 2",
"iconlarge": "/images/collection_default_l.gif",
"iconsmall": "/images/collection_default_s.gif",
"set": [
{
"id": "72157643471292484",
"title": "Set 1",
"description": ""
}
]
},
{
"id": "122388635-72157643469075734",
"title": "Test Gallery 1",
"description": "Bing Photos",
"iconlarge": "http://farm3.staticflickr.com/2888/cols/72157643469075734_b9a37df67c_l.jpg",
"iconsmall": "http://farm3.staticflickr.com/2888/cols/72157643469075734_b9a37df67c_s.jpg",
"set": [
{
"id": "72157643469056814",
"title": "Test Gallery 1",
"description": "Bing Backgrounds"
}
]
}
]
},
"stat": "ok"
}
So how do I pass the received data to other functions without a disruption in the data?
Code should be much like below
success: function (collections)
{
$.each(collections,function(index,item){
var i=0;
$.each(item.conllection[i],function(index,item){
alert(item.id);
i++;
});
});

Mixed array with json - parsing issue

I am doing a youtube api call, and I get back a var result = JSON.stringify(response, '', 2); which looks like :
{
"kind": "youtube#searchListResponse",
"pageInfo": {
"totalResults": 1000000,
"resultsPerPage": 5
},
"items": [
{
"id": {
"kind": "youtube#video",
"videoId": "DEne4AoX_RU"
},
"kind": "youtube#searchResult",
"snippet": {
"publishedAt": "2012-11-22T22:36:15.000Z",
"thumbnails": {
"default": {
"url": "https://i.ytimg.com/vi/DEne4AoX_RU/default.jpg"
},
"medium": {
"url": "https://i.ytimg.com/vi/DEne4AoX_RU/mqdefault.jpg"
},
"high": {
"url": "https://i.ytimg.com/vi/DEne4AoX_RU/hqdefault.jpg"
}
}
}
},
{
"id": {...}
The full object response returns correctly in my console but I want to retrieve thumbnails url and display it as an li-tagged html list
So I tried first to fetch in a list all the snippet entries :
var obj = $.parseJSON(result);
$.each(obj, function() {
output += this.snippet + + "<br/>";
});
console.log(output);
But I have an message in my console : Uncaught TypeError: Cannot read property 'length' of undefined. What am I missing ? Btw, I don't understand why there are still brackets in the json stringified result (if someone could advise some good doc to understand how to parse JSON, would be great:))
You should be looping over items:
$.each(obj.items, function() {
output += this.snippet ...
});
What you receive is JSON, you shouldn't stringify it.
Remove this line
var result = JSON.stringify(response, '', 2);
and simply do
var obj = $.parseJSON(response);
you want to iterate over items,
snippet is an object literal,
+ + is not valid javascript.

Categories

Resources