How to access 'Object' portion of JSON using Jquery? - javascript

I used console.table(someData) to output the object shows in the attaches image.
I used the following code to get the data:
var someData = GetJson('someurlthatreturnsjson');
function GetJson(Url) {
return $.ajax({
url: Url,
xhrFields: {
withCredentials: true
},
dataType: "json"
});
}
I tried:
var x = someData.readyState; // 1 was returned as expected.
var y = someData.Object; // undefined.
...so...
var z = someData.Object.responseJSON; // also undefined?
So how would I access elements within the Object portion of this json? Am I missing something?

As you return the $.ajax() call from getJSON(), the someData variable will contain the Deferred object containing the reference to the AJAX call.
To retrieve the response from that call from the Deferred object you can use any of the methods outlined in the documentation I linked to. I would suggest using then() in this case, as the handler function you define will receive the response as the first argument to the function, like this:
var someData = GetJson('someurlthatreturnsjson').then(response => {
// do something with the response here...
console.dir(response);
});
function GetJson(Url) {
return $.ajax({
url: Url,
xhrFields: {
withCredentials: true
},
dataType: "json"
});
}

Related

jQuery -- nesting ajax calls and using data from each call - wikipedia API

I am having problems in nesting ajax calls with jQuery to wikipedia api.
The HTML is simple, just an input form and a button:
<input id='search-input' type="text" class="form-control">
<button id="search-button" type="button" class="btn btn-primary">Search</button>
<div id ='outputDiv'></div>
THe search button has an event listener that fires a function that grabs data from wikipedia API:
...
searchBtn.addEventListener('click', searchwiki);
...
function searchwiki(){
let searchTermObjects =[]
let term = inputfield.value;
let titleUrl = search_term(term);
createWikiObject(titleUrl).then(function(){
searchTermObjects.forEach(function(elem){
addExtrctToObj(elem)
})
}).then(function(data){
append_result(searchTermObjects)
})
}
function createWikiObject(titleUrl){
return $.ajax({
type: "GET",
url: titleUrl,
dataType : 'jsonp',
async: true,
error : function(ermsg){
console.log('error in searching',ermsg)
},}).then(function(data){
for(let i = 0; i < data[1].length; i ++){
searchTermObjects.push({
'title': data[1][i].replace(/\s+/g, '_'),
'description': data[2][i],
'url': data[3][i],
})
}; // this for loop should push each result as an object to an array named searchtTermObjects, and i am planning to use this array in the next ajax call to add another property named extract to each object in array
}
);
}
function addExtrctToObj(obj){
console.log(obj)
return $.ajax({
type: "GET",
url: get_text(obj['title']),
dataType : 'jsonp',
async: true,
error : function(ermsg){
console.log('error getting text',ermsg)
}
}).then(function (data){
let pageID = Object.keys(data.query.pages);
if(data.query.pages[pageID].hasOwnProperty('extract')){
obj['extract'] = data.query.pages[pageID].extract;
}
// this function adds the extracted text for each article ,
// the searchTermObjects now looks something like:
/ [{'title':...,'url':...,'description':...,'extract':..},{...}]
})
};
function append_result(termsObjectsArray){
// this function should loop through the searchtermobjects and append leading text for each object in the array to the Output div under the button
for (let i = 0; i < termsObjectsArray.length; i++){
let newDiv = document.createElement('div');
HOWEVER, Object.keys(termsObjectsArray[i]) returns only three keys at this time, and doesn't see the extract key'
console.log(Object.keys(termsObjectsArray[i]))
newDiv.classList.add('wiki-result');
newDiv.innerHTML = termsObjectsArray[i]["extract"];
HERE is where i get error -- the inerHtml of newDiv has value UNDEFINED
outputDiv.appendChild(newDiv);
}
}
// the api calls are formed with these functions:
let base_url = "https://en.wikipedia.org/w/api.php";
function search_term(term) {
let request_url = base_url + "?action=opensearch&search=" + term + "&format=json&callback=?";
return request_url;
}
function get_text(term){
let request_url = base_url + "?action=query&prop=extracts&exintro=&format=json&titles=" + term; // explaintex= returns plaintext, if ommited returns html
return request_url;
}
afetr I console.log(searchTermObjects) i get what i need, the array with objects that have all 4 properties with correct names, but I don't understand why the append_result function doesn't see the 'extract' key.
Next to the logged object in the console is the 'i' sign that says 'Value below was evaluated just now' , and there I have what I wanted -- every search result as an object with title, url, description, and extract keys.
copy this code to your IDE to see if you can help me with finding solution.
I believe the issue you're having is that you're attempting to return a Deferred object, and there's nothing to return yet because of the deferral.
return $.ajax({
type: "GET",
url: get_text(obj['title']),
dataType : 'jsonp',
async: true,
error : function(ermsg){
console.log('error getting text',ermsg)
}
})
The async value is true, so the code is moving on before the request is finished, and you're getting a null value back.
Try setting async: false and see if you get a better response. As pointed out by Andrew Lohr in the comments, this is not a good way to solve the problem, it will only tell you if that is the problem.
If it is, then I would recommend not breaking the request up into multiple functions. You should just chain the AJAX calls, using the deferral approach. It would be structured like this:
$.ajax({ ... }).then(function(data){
// ... do something with the data ...
// Make your followup request.
$.ajax({ ... }).then(function(data) {
// ... finalize the response ...
});
});
Also consider using the context option in the ajax call to pass in a callback method that can be fired once the chain is complete.

extract object of responseJSON

I solved a synchronous problem with ajax that way to use deferred function.
I get as an response now big object with statusResponse etc etc inside.
My JSONP Objects are also successfully stored in responseJSON Object. How Can I extract it or save it in another variable ?
var web = new webService();
web.init(app.info);
and here the class
function webService() {
this.init = function(app) {
var d = this.connect(app).done(function(){});
console.log(d);
}
this.connect = function(app) {
console.log(app);
return $.ajax({
url: 'working url',
dataType: 'jsonp',
jsonp: 'jsoncallback',
timeout: 5000
});
}
}
.done() is going to be called when the data has returned (but through a parameter). So, make sure you add a parameter to your callback function then inspect it for whatever you want out of it.
this.connect(app).done(function(mydata){
// mydata = the response object
// grab whatever information you want from it here.
});

Why is AJAX/JSON response undefined when used in Bootstrap typeahead function?

I created a function that makes a jquery AJAX call that returns a JSON string. On its own, it works fine -- and I can see the JSON string output when I output the string to the console (console.log).
function getJSONCustomers()
{
var response = $.ajax({
type: "GET",
url: "getCustomers.php",
dataType: "json",
async: false,
cache: false
}).responseText;
return response;
};
However, when I set a variable to contain the output of that function call:
var mydata = getJSONCustomers();
, then try to use it within my Twitter-Bootstrap TypeAhead function (autocomplete for forms):
data = mydata;
console.log(data);
I get an 'undefined' error in my console.
Below is a snippet of this code:
$(document).ready(function() {
var mydata = getJSONCustomers();
$('#Customer').typeahead({
source: function (query, process) {
customers = [];
map = {};
data = mydata;
console.log(data);
// multiple .typeahead functions follow......
});
Interesting here, is that if I set the data variable to be the hardcoded JSON string returned from the AJAX function, everything works fine:
data = [{"CustNameShort": "CUS1", "CustNameLong": "Customer One"}]
How can I use the JSON string within my typeahead function?
.responseText returns a string. You have to parse the string first to be able to work with the array:
var mydata = JSON.parse(getJSONCustomers());
That being said, you should avoid making synchronous calls. Have a look at How do I return the response from an asynchronous call? to get an idea about how to work with callbacks/promises.
The problem is that the Ajax request hasn't had the chance to complete before typeahead is initialised, so typeahead is initialised with an uninitialised mydata variable. Also, as of jQuery 1.8+ async: false has been deprecated and you need to use the complete/success/error callbacks.
Try this:
function getJSONCustomers(callback) {
$.ajax({
type: "GET",
url: "getCustomers.php",
dataType: "json",
cache: false,
success: callback
});
};
And then you could do something like:
getJSONCustomers(function(mydata) {
// mydata contains data retrieved by the getJSONCustomers code
$('#Customer').typeahead({
source: function (query, process) {
customers = [];
map = {};
console.log(mydata);
// multiple .typeahead functions follow......
});
});
So your code completes the Ajax call before initialising the typeahead plugin.

Getting list back from ajax jsonp callback

I am making an ajax call via jquery with a jsonp callback function. The callback gets called and generates a list for me that I need to return to the original alling function and assign to a variable. However, it is not getting passed back. I know I am doing something wrong or misunderstanding how this flow works. Could somebody please point me in the correct direction? Here is the (abbreviated) code:
function() {
..build url...
var multiTargets = getMultiMetrics(url);
...do stuff with list...
}
getMultiMetrics = function(url) {
$.ajax({
url: url,
jsonp : true,
jsonpCallback: 'metricCallback',
cache: true,
dataType : 'jsonp',
async: false
});
};
metricCallback = function(data) {
var items = [];
for (var i = data.length - 1; i >= 0; i--) {
items.push(data[i].target);
};
return items;
};
Try not use quotes in
jsonpCallback: metricCallback,
This parameter must be function instead of a string

How to create jquery ajax as separate function?

I want to create a separate function to get specific data from Facebook graph JSON.
For example, I have the load() and called getNextFeed() function.
The getNextFeed works correctly. Except that returning value of aString is not successful.
When I pop alert(thisUrl). It said undefined.
Note: I am new to Javascript and Jquery. Please give me more information where I did wrong. Thank you.
function load()
{
$(document).ready(function() {
var token = "AccessToken";
var url = "https://graph.facebook.com/me/home?access_token=" + token;
var thisUrl = getNextFeed(url);
alert(thisUrl); // return undefined
});
function getNextFeed(aUrl)
{
$.ajax({
type: "POST",
url: aUrl,
dataType: "jsonp",
success: function(msg) {
alert(msg.paging.next); // return correctly
var aString = msg.paging.next;
alert(aString); // return correctly
return aString;
}
});
}
The problem is that $.ajax() is an ansynchronous function, means, when called, it returns in the same instance, but an ajax call is done in a separate thread. So your return vaule of $.ajax() is always undefined.
You have to use the ajax callback function to do whatever you need to do: Basically you already did it correctly, just that return aString does not return to your original caller function. So what you can do is to call a function within the callback (success()), or implement the logic directly within the success() function.
Example:
function load()
{
$(document).ready(function() {
var token = "AccessToken";
var url = "https://graph.facebook.com/me/home?access_token=" + token;
getNextFeed(url);
alert('Please wait, loading...');
});
function getNextFeed(aUrl)
{
$.ajax({
type: "POST",
url: aUrl,
dataType: "jsonp",
success: function(msg) {
alert(msg.paging.next); // return correctly
var aString = msg.paging.next;
alert(aString); // return correctly
do_something_with(aString);
}
});
}

Categories