Fetch data from a complex JSON - javascript

I'm new to javascript and JSON and I've been given a task to complete. Please find the JSON in the following link,
http://pastebin.com/0BY3eptF
According to me the above is a very complex JSON.
I'm trying to fetch the out from a WSDL via ajax
success: function(api) {
console.log(api.SearchResult); // trying to fetch information on SearchResult object
}
This doesn't work. I would like to learn how to iterate each JSON string loop. I also see an array which is WSResult[]. A neat javascript with explanation will help me a lot. Thank you.

Some web services return content type as plain text instead of json, you have to manually convert into json. below code will help you do the same.
success: function(api) {
if (api.constructor === String) {
api = JSON.parse(api);
}
console.log(api.SearchResult);
}
To loop through api.SearchResult.Result.WSResult array, please find below code
$(api.SearchResult.Result.WSResult).each(function (index, val) {
// here val is single object of WSResult array
});

success: function(api) {}, here, api is still a string, you have to parse it to JSON first:
success: function(api) {
var api = JSON.parse(api);
console.log(api.SearchResult); // trying to fetch information on SearchResult object
}

Not a complete answer, but some useful pointers:
$ajax({
url: 'http://myURL',
// specify the datatype; I think it overrides inferring it from the document MIME type
dataType: 'json',
success: function (api) {
// provided your data does come back as a JSON document
// you should be able to access api.SearchResult
},
error: function( jsXHR, textStatus, errorThrown) {
// always have an error handler, so you can see how it went wrong.
}
);
Read the section on dataType here, as it may solve your problem

Related

Getting null in return when executing Ajax request

Ajax request is executing, but it returns not curent_day variable but null.
Js:
$.ajax({
url: 'planing/next-day',
data: {new_curent_day: $('.owl-item.center .slide_day').text()},
dataType: 'json',
type: 'POST',
success: function(curent_day) {
alert(curent_day);
},
error: function(xhr, status, error) {
alert(xhr.responseText + '|\n' + status + '|\n' +error);
}
});
Controller:
public function actionNextDay() {
if (Yii::$app->request->isAjax){
$this->planing_model->curent_day = Yii::$app->request->post('new_curent_day');
return Json::encode($this->planing_model->curent_day);
}
}
May be the problem is your are sending the POST data as JSON so your not able get it through
Yii::$app->request->post('new_curent_day');
Try this they have updated JSON parser set and to get the JSON value through yii.
Error in accessing post json data in yii2
Use the Javascript console and debugger in your browser to see what $('.owl-item.center .slide_day') contains. Make your API endpoint log what it gets in the post variables.
The typos in variable names make me worry that you might refer to the wrong thing. planing has two n's, curent has two r's. This code looks consistent at least but if I came across this code I would suspect current and curent got mixed up.

Using JSONP and I have 'ReferenceError: data not defined'

I've got a problem with displaying JSON data called via JSONP. I've got a complex JSON file delivered cross domain via a URL and I'm quite the novice at JSON and ajax. I followed a JSONP article here at https://learn.jquery.com/ajax/working-with-jsonp/ and that worked a treat. Now I am trying to iterate through the JSON object and display data in the HTML page after following this question How do I iterate through this JSON object in jQuery? and I'm not going anywhere. The data is not defined and I'm not sure what I am doing wrong:
// Using LibCal and JSONP
$.ajax({
url: "https://api2.libcal.com/1.0/room_bookings_nickname/?iid=3356&group_id=12306&key=92a47e5c854dee620cca071648c3fc41",
// The name of the callback parameter, as specified by the YQL service
jsonp: "callback",
// Tell jQuery we're expecting JSONP
dataType: "jsonp",
// Tell LibCal what we want and that we want JSON
data: {
q: "select Room name,booked timeslots,booking name from LibCal room bookings",
format: "json"
},
// Work with the response
success: function( response ) {
console.log( response ); // server response
}
});
$.each(data.bookings, function(index, element) {
alert(element.timeslots.room_name);
});
I hope it's an obvious fix to a more advanced user our there :)
Thats because your data object doesn't exist. The data key you're referring to is a on the object you're passing to the $.ajax method.
You need to execute your function inside the success callback in order for it make any sense.
$.ajax({
...
// keep all your original stuff
...
success: function( response ) {
var data = response;
$.each(data.bookings, function(index, element) {
alert(element.timeslots.room_name);
});
}
});
I did the request like this. You need to go one level more to access the array to loop.
var json_url = "https://api2.libcal.com/1.0/room_bookings_nickname/?iid=3356&group_id=12306&key=92a47e5c854dee620cca071648c3fc41"
$.ajax({
url: json_url,
crossDomain:true,
dataType:"jsonp"
}).done(function(response) {
// at the end of request
//Yours --->response.bookings
//Mine --->response.bookings.timeslots
//access the array to loop
var rooms = response.bookings.timeslots;
$.each(rooms, function(index, element) {
create_elem(element.room_name, index);
});
});
Here is a working version in jsFiddle - https://jsfiddle.net/9e746pkh/
Hope this helps.

Building a json tree structure

I will be passing a json string to a servlet via an ajax request :
function add() {
$.ajax({
url: "pathToServlet" ,
dataType: "text",
data: ({
name : 'myJsonString'
}),
success: function(data) {
alert('returned!!');
});
}
To build up this json string I have a listener which when fired appends a new piece of json to string :
var json = "";
json += "{ new json ..... }"
Is this the correct way to build up the jSon String ? Should I be using jQuery methods to create a json object(if they exist) and add elements to it and then convert the json object to a string instead of creating the json string myself ?
What I would recommend doing is building up an object, and then when you're ready to send it to the server, serialize the object via JSON.stringify.
So for instance, you might have an object called data:
var data = {};
...to which you might periodically add properties:
data.foo = "bar";
data.stuff = {nifty: "stuff"};
Or perhaps data is an array:
var data = [];
...to which you add things:
data.push({nifty: "stuff"});
Then, when you're ready to send it:
function add() {
$.ajax({
url: "<%=savePortlet%>" ,
dataType: "text",
data: {
name : JSON.stringify(data)
},
success: function(data) {
alert('returned!!');
});
}
Because you're passing an object into ajax, you don't have to worry about URL-encoding the JSON string; jQuery will do it for you.
JSON.stringify is defined as part of ECMAScript5 and suppoted natively by many browsers, but of course many of us have to support outdated versions of browsers. In those cases, you can get a "JSON shim" to add JSON.stringify to an environment that doesn't have it. One of those is available from the originator of JSON, Douglas Crockford, on his github page.
If using jQuery you can use jquery-json, a really handy plugin to handle JSON with JavaScript and jQuery.
Usage:
var jsonString = $.toJSON(myObject);

Get json data from Api

i am using the third party api for getting the Address on the basis of postcode . it returns the json data .
below is the api that i am calling but i am not sharing the datakey that i am using .
i am accessing this in jquery not using any server side scripting languages .
$.getJSON("http://www.simplylookupadmin.co.uk/JSONservice/JSONSearchForAddress.aspx?datakey=data key &postcode=CM129BY&callback=?", function () {
alert("aaa");
});
also using the other code like
// jQuery.ajax({
// type: 'GET',
// url: 'http://www.simplylookupadmin.co.uk/JSONservice/JSONSearchForAddress.aspx?datakey=data key&postcode=CM129BY?jsoncallback=?',
// dataType: 'json',
// success: function (data) {
// alert('success');
// }
// });
but i am getting the error
Error: invalid label
Source File: http://www.simplylookupadmin.co.uk/JSONservice/JSONSearchForAddress.aspx?datakey=datakey&postcode=CM129BY&callback=jQuery17209661092291729644_1335505434728&_=1335505437637
Line: 2, Column: 2
Source Code:
"found":"1",
please advice its very urgent
Thanks
naveen Kumar GUpta.
I think you may be missing any Quotes.Please check it once again.
I think the postcode you are searching is not found in the Database.
I got it.
It is the JSON result string is invalid as JSON, open the URL http://www.simplylookupadmin.co.uk/JSONservice/JSONSearchForAddress.aspx?datakey=data key &postcode=CM129BY&callback=? with web browser I got the content:
{
"found":"1",
"credits_display_text":"Cannot find FULL PAF license(credits or users)",
"accountadminpage":"https://www.simplylookupadmin.co.uk/WebAccountLogin.aspx?doid=1&coid=30&Pay=yes",
"errormessage":"Search denied! Cannot find FULL PAF license(credits or users)",
"maxresults":"0",
"recordcount":"0",
"records"]}
At the end of it, "]" is not needed.

jQuery AJAX and JSON Performance Query

I am storing some JSON data in a text file to query using jQuery Ajax in my page. Currently, my text file contains around 10 facets of data (which could contain an additional 30 facets of data). The JSON data contains a questions and answers to those questions.
In my JavaScript files, I have setup different functions to get specific bits of data.
For example:
function GetAnswer(questionName) {
var correctAnswer = null;
jQuery.ajax({
type: "GET",
url: "../content/questions.txt",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: "",
async: false,
success: function (result) {
$.each(result, function (i, q) {
if (q.questionID == questionName) {
correctAnswer = q.correctAnswer;
return false;
}
});
},
error: function () { },
complete: function () { }
});
return correctAnswer ;
}
As you can see from my code-snippet, I am looping through my JSON to get the data I need. I have other functions coded in a similar fashion to get the question type, question name etc.
What I am finding is that I am calling these functions one after another to get the data I need. I think the way I am querying my JSON data is not good from a performance point-of-view since I am looping through the whole of my JSON dataset until I find a match.
Is there a better way to query my JSON data?
NOTE: I am having to use a text file to store questions due to restrictions of the technology I am using (SCORM 1.2).
Looping through your JSON object is relatively quick. What is slow (comparatively) is loading in that text file each time (though it may be cached).
Either way, I would suggest loading in the JSON either the first time the user initiates a question/answer situation, or just load it in on page load (you can do it asynchronously) and store it for later use.
Example of the latter:
jQuery(document).ready(function(){
var questions = '';
jQuery.ajax({
type: "GET",
url: "../content/questions.txt",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: "",
async: false,
success: function (result) {
questions = result;
},
error: function () { },
complete: function () { }
});
function GetAnswer(questionName) {
var correctAnswer = null;
$.each(questions, function (i, q) {
if (q.questionID == questionName) {
correctAnswer = q.correctAnswer;
return false;
}
});
return correctAnswer ;
}
});
The problem is that you have async set to false. This is bad. This halts the browser while it waits for your requests, and will cause the performance to feel very laggy.
Why not change the structure of your Q&A object to include an id for each question, and make the id an attribute in the object? Then you could pass the id to GetAnswer() and just have it go directly to the right question by referencing the correct attribute? The object could look like this:
{"myQuiz" :
"Q1" :
{ "q" : "What color was George Washington's white horse?",
"a" : "White"
},
"Q2" :
{ "q" : "In what city would you find the Leaning Tower of Pisa?",
"a" : "Pisa"
}
}
If this is assigned to result, and an id of Q2 was passed to GetAnswer(id), you could easily return result.myQuiz[id].a;
As an alternative, if the order of the questions is consistent, you could use an object that contains an array of q and a pairs, and refer to them by index rather than id.
Why not move the logic to a server-side script like PHP that can take in POST parameters and perform the queries against the JSON set and return only the record(s) you wish to receive. Or, if you are intent on keeping this in all js, you could simply store the JSON (as long as it is non-sensitive data) in a local variable and query against it locally.
You could make somekind of mechanism on the server to load data. Then you could send parameters like QuestionName and filter data. This will lower payload sent on the wire.

Categories