I have this code, it does an AJAX call to Wikipedia, asking for results of a given query (var searchText):
function main() {
$(".btn").click(function() {
$("#iframe").attr('src', 'https://en.wikipedia.org/wiki/Special:Random');
$(".embed-container").css('visibility', 'visible');
});
function wikiAjax (searchURL) {
return $.ajax({
url: searchURL,
jsonp: "callback",
dataType: 'jsonp',
xhrFields: {
withCredentials: true
}
});
}
$(".search-form").submit(function() {
event.preventDefault();
var searchText = $('#search').val();
var searchURL = "https://en.wikipedia.org/w/api.php?format=json&action=query&generator=search&gsrsearch=" + searchText + "&gsrlimit=15&prop=extracts&exsentences=3&exintro=&explaintext&exlimit=max&callback=JSON_CALLBACK";
console.log(searchURL);
var wikiResponse = wikiAjax(searchURL);
wikiResponse.done(function(data) {
console.log(data);
}).fail(function(err) {
alert("The call has been rejected");
});
});
}
$(document).ready(main);
But it returns me a strange object:
Could someone please help me?
you've the right response from Wikipedia, check your query parameters, specially this one
var searchText = $('#search').val();
which value you are testing with, if you entered something like "2sasd23sda" you'll get this object response.
The Ajax call needs to have 3 parameters. There is JSON data in the 3rd param. Try it with this jsfiddle.
wikiResponse.done(function(error, success, data) {
console.log(data.responseJSON.query.pages);
})
This is the correct response for a query that has no matches. the issue is most likely the search value you are appending.
Below are two result sets, one using a term that yields no response the other using Test.
Response with no results:
No Results
Response with results:
Results
Related
Challenge:
While on URL1(random wikipedia page), make an ajax request to URL2(100 most common words wikipedia page), format a list out of the returned data to be used later.
I have to run this from the console while on "URL1"
example:
Navigate to URL1
Open Console
paste code
hit enter
So far I have been able to grab the entire html source while on URL1 with the following:
$.ajax({
url: 'https://en.wikipedia.org/wiki/Most_common_words_in_English',
type: 'GET',
dataType: 'html',
success: function (response) {
console.log(response); // works as expected (returns all html)
}
});
I can see in the console the entire HTML source -- I then went to URL2 to figure out how to grab and format what I needed, which I was able to do with:
var array = $.map($('.wikitable tr'),function(val,i){
var obj = {};
obj[$(val).find('td:first').text()] = $(val).find('td:last').text();
return obj;
});
console.log(JSON.stringify(array));
Now this is where my issue is -- combining the two
$.ajax({
url:'https://en.wikipedia.org/wiki/Most_common_words_in_English',
type:'GET',
dataType:'html',
success: function(data){
// returns correct table data from URL2 while on URL2 -- issue while running from URL1
var array = $.map($('.wikitable tr'),function(val,i){
var obj = {};
obj[$(val).find('td:first').text()] = $(val).find('td:last').text();
return obj;
});
console.log(JSON.stringify(array));
};
});
Im guessing this is due to the HTML I want to map is now a string, and my array is looking for HTML elements on the current page which it of course would not find.
Thanks
Simple fix here! You're exactly right, it's not parsing the html you return, so just tell jQuery to convert it into an object it can use $(data) and use that to find what you need.
In essence, your 'document' now becomes $(data) which you will use as the source of all your queries.
$.ajax({
url: 'https://en.wikipedia.org/wiki/Most_common_words_in_English',
type: 'GET',
dataType: 'html',
success: function(data) {
var myVar = data;
Names = $.map($(myVar).find('.wikitable tr'), function(el, index) {
return $(el).find('td:last').text()
});
console.log(Names);
}
});
this is my first question here! New to using Ajax, and have hit an issue that maybe someone could catch what I am doing wrong.
var featuredList;
$.ajax({
url: "myurl",
type: 'GET',
success: function(result){
featuredList = JSON.stringify(result);
alert(result);
$.each( result, function( key, value ) {
alert('not working');
});
},
error: function(){alert('error');}
});
I have gone this path before with no issues, this time around I cannot get inside the loop. The alert(result) is returning my data just fine.
Thanks!
Hi,
Hope this might help you to process JSON data received from AJAX request, try below code:
jQuery.ajax({
url:'myurl',
dataType: "json",
data:{
classId:'C001'
},
type: "GET",
success: function(data) {
for (var j=0; j < data.length; j++) {
//syntax to get value for given key
//data[j].yourKey
var userId = data[j].userId;
var name = data[j].name;
var address = data[j].address;
}
}
});
Thanks,
~Chandan
As per your code try doing this:it should work
var data = JSON.parse(result);//here result should be json encoded data
$.each( data, function( key, value ) {
alert(value);
});
Use jQuery promises, gives you more semantic and readable code
var featuredList;
$.getJSON("myurl", {"optional": "data"})
.done(function(data){
// successful ajax query
$.each( data, function( key, value ) {
// do whatever you want with your iterated data.
});
});
.fail(function(){
// catch errors on ajax query
});
I do it this way
$.getJSON('url',
function(dataList) { // on server side I do the json_encode of the response data
if(dataList !== null) {
$.each(dataList, function(index, objList ) {
// rest of code here
});
}
});
Hope this works for you as well.
function getArray(){
return $.getJSON('url');
}
var gdata = [];
getArray().then(function(json) {
$.each(json, function(key, val) {
gdata[key] = val ;
});
console.log(gdata);
I had the Same Problem It took 2 days to got the solution.
You have to resolve the promise and return the json object to access the value.
You could easily do this using the open source project http://www.jinqJs.com
/* For Async Call */
var result = null;
jinqJs().from('http://.....', function(self){
result = self.select();
});
/* For Sync Call */
var result = jinqJs().from('http://....').select();
You can also use $.Json to get your solution , here is an example
$.getJSON('questions.json', function (data) {
$.each(data,function(index,item){
console.log(item.yourItem); // here you can get your data
}
}
You can use or print Index if you want it. Its show the data index.
Hope it may help you, I am exactly not sure its your requirement or not, But i have tried my best to solve it.
This will work as the result from ajax call is a string.
$.each($.parseJSON(result), function( key, value ) {
alert('This will work');
});
A newbie here working with FourSquare API. I'm not sure if I'm doing this correctly, but I need to pull in data from a search via "https://developer.foursquare.com/docs/venues/search". However, along with that I'd like to have more details about each venue such as their hours of operation and other details about the venue aside from the generic contact and name. What I've done is nested an ajax call-the search api and then within search venue, do another venue detail search.
$.when(
$.ajax({
url: "https://api.foursquare.com/v2/venues/search?limit=4&"+$this.settings.key+"&ll="+$this.currentLocation.coord+"&intent=checkin",
data: inputData,
dataType: "json",
success: function(res, req) {
var data = res.response.venues;
$('.results').find('.loading').addClass('hide');
$.each(data, function(index, venue) {
return $.ajax({
url: "https://api.foursquare.com/v2/venues/"+venue.id+"?"+$this.settings.key,
dataType: 'json',
success: function(res, req) {
data[index].details = detail = res.response.venue;
}
});
});
}
})
).then(function(data) {
var results = data.response.venues;
console.log(JSON.stringify(results));
});
Any help will be much appreciated, thanks!
Use done()
var request1 = $.get(...);
var request2 = $.get(...);
$.when(request1 , request2 ).done(function() {
// when both are completed
});
Check out the async Javascript library. Pass an array of venue IDs as the first argument into async.each and that should get you started. async.waterfall can also help you handle the case where you need to pass data from one asynchronous function to the next.
I am more of a java developer and am having difficulty with javascript callback. I am wondering if any experts here would help me out of my struggle with this code.
I am trying to pull our locations from db and populating in an array. On first load i am trying to refresh all locations and I am having trouble to control the flow of execution and loading values. Below is the code and I have put in the output at the end.
JQUERY CODE:
// load all locations on first load.
refreshLocations();
$("#locInput").autocomplete({source: locationData});
}); // end of document.ready
// function to refresh all locations.
function refreshLocations() {
getLocationArray(function(){
console.log("firing after getting location array");
});
}
// function to get the required array of locations.
function getLocationArray() {
getJsonValues("GET", "getLocalityData.php", "", getLocalityFromJson);
}
// function to pick up localities from json.
function getLocalityFromJson(json){
if (!json) {
console.log("====> JSON IS NOT DEFINED !! <====");
return;
} else {
console.log("json is defined so processing...");
var i = 0;
$.each(json.listinginfo, function() {
var loc = json.listinginfo[i].locality;
locationArray[i] = loc;
console.log("added location ->" + locationArray[i]);
i++;
});
}
//return locationArray;
}
// function to get raw json from db.
function getJsonValues(type, url, query, getLocalityFromJson) {
var json;
// if the previous request is still pending abort.
if (req !== null)
req.abort();
var searchString = "";
if (query !== "") {
searchString = "searchStr" + query;
}
console.log("searchString : (" + query + ")");
req = $.ajax({
type: type,
url: url,
data: searchString,
contentType: "application/json; charset=utf-8",
dataType: "text",
success: function(result) {
json = JSON.parse(result);
console.log("========start of json
return============");
console.log(JSON.stringify(json));
console.log("========end of json
return============");
//return json;
}
});
getLocalityFromJson(json);
return json;
}
the output from above code is as follows:
searchString : () (18:25:36:473)
at locality1.php:74
====> JSON IS NOT DEFINED !! <==== (18:25:36:518)
at locality1.php:48
========start of json return============ (18:25:37:606)
at locality1.php:83
{"listinginfo":[{"listing":"1","locality":"birmingham"},
{"listing":"2","locality":"oxford"}]} (18:25:37:624)
at locality1.php:84
========end of json return============ (18:25:37:642)
at locality1.php:85
>
Help will be greatly appreciated.
call getLocalityFromJson(json); inside your success callback
function getJsonValues(type, url, query, getLocalityFromJson) {
var json;
// if the previous request is still pending abort.
if (req !== null)
req.abort();
var searchString = "";
if (query !== "") {
searchString = "searchStr" + query;
}
console.log("searchString : (" + query + ")");
req = $.ajax({
type: type,
url: url,
data: searchString,
contentType: "application/json; charset=utf-8",
dataType: "text",
success: function(result) {
json = JSON.parse(result);
console.log("========start of json return============");
console.log(JSON.stringify(json));
console.log("========end of json return============");
//return json;
getLocalityFromJson(json);
}
});
}
You need to call getLocalityFromJson(json) and return json inside your ajax success function. Ajax requests are asynchronous, there's no guarantee that the request will be finished by the time you get to the lines getLocalityFromJson(json); return(json); where they are currently.
The call back functions from a jquery ajax call is complete, failure, success, etc..
Success is called after a request is successful,
Failure is called if theres something like an error 500, or a 404, or w/e.
Complete is Always called after a ajax call.
If you want your code to just follow sequence like in java, throw async: false into your ajax call.. but I wouldnt' recommend this as it defeats the purpose of using this method, and also locks up your browser.
You should make sure you are waiting for the request to finish before moving on - so put code in the success function that you want to run AFTER the request has finished fetching your data.
I think you need to remember Ajax is running async, so you need to follow this thread to execute your refresh.
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);
}
});
}