Simple get API call in jQuery - javascript

I have a url to which I need to make a get call. The url returns the following JSON response when run in POSTMAN.
{
"status": true,
"data": [
{
"id": 1,
"suggestion": "shirt"
},
{
"id": 2,
"suggestion": "jeans"
},
{
"id": 3,
"suggestion": "puma"
},
{
"id": 4,
"suggestion": "spykar"
}
],
"lastPageNumber": 0
}
I need to get the "suggestion" key's value and append to my list.
Following is my code to get the data and append its values to a list as shown.
jQuery.getJSON( url, function( response ) {
$.each(response.data ,function() {
$.each(this, function (key, value) {
if(key=="suggestion") {
$('#suggestions').append('<li class="suggestItem">'
+ '<a>' + value + '</a>' + '</li>'});
}
);
});
});
And this is the ul to which I have to append these list items.
<ul id="suggestions" style="position: absolute; list-style-type: none;">
However, I do not seem to get any data in response or maybe I am not traversing through the JSON array correctly. So, I need help in whether I have written the right code or not.
Also additional information:
I am running this project on localhost and the url is something http://example.anotherExample.net so does this also affect (I read something about cross domain in ajax).

You can try something like following
$.each(obj.data, function(){
$('#suggestions').append('<li class="suggestItem">' + '<a>' + this.suggestion + '</a>' + '</li>');
});

Related

Populate DataTables from json (not from ajax)

I am trying to populate datatable on click.
Initially I have this configuration:
var json = [];
var shippingMethodsTable = $("#shipping-methods-table").DataTable({
'data': json,
"columns": [
{ "data": "ShippingMethodId" },
{ "data": "MethodName"},
{ "data": "Code"},
{ "data": "ShippingTypeName" },
{ "data": "MaxWeight" }
]
});
After I click button I have json object of arrays:
json = ko.toJSON(data.shippingMethods); // I am using knockout.js to populate it
Result:
"[{"ShippingMethodId":2,"MethodName":"Priority Mail","Code":null,"ShippingTypeName":"Parcel","MaxWeight":"70 lbs"},{"ShippingMethodId":4,"MethodName":"Priority Mail Express","Code":null,"ShippingTypeName":"Parcel","MaxWeight":"70 lbs"},{"ShippingMethodId":5,"MethodName":"First-Class Mail","Code":null,"ShippingTypeName":"Parcel","MaxWeight":"13 oz"},{"ShippingMethodId":6,"MethodName":"USPS Retail Ground","Code":null,"ShippingTypeName":"Parcel","MaxWeight":"70 lbs"},{"ShippingMethodId":8,"MethodName":"Media Mail","Code":null,"ShippingTypeName":"Parcel","MaxWeight":"70 lbs"}]"
And then I am trying to update datatable
shippingMethodsTable.clear();
shippingMethodsTable.rows.add('{"data":' + json + '}');
shippingMethodsTable.draw();
But getting an error: Requested unknown parameter 'ShippingMethodId' for row 0, column 0
Method rows.add() expects array of object, rather than object.
So, try
shippingMethodsTable.clear();
shippingMethodsTable.rows.add(json);
shippingMethodsTable.draw();
instead.

Most efficient way to search large multi nested JSON dataset?

What is the most efficient way to search a large dataset of JSON (Up to 27k entries) using jQuery or JS. I'd like to create a search field that runs the function on keyup.
So if a users starts typing it returns all values that match the title, along with the link for that title.
My JSON is nested alphabetically A-Z. Example below
"Numbers": [
{
"Title": "20th Century Period Pieces",
"Link": "#"
},
{
"Title": "20th Century",
"Link": "#"
}
],
"A": [
{
"Title": "Action Comedies",
"Link": "#"
},
{
"Title": "Action",
"Link": "#"
}
],
"B": [
{
"Title": "British",
"Link": "#"
},
{
"Title": "Borderline",
"Link": "#"
}
],
// And so forth
I'm aware this may cause the browser to freeze up searching such a large list on every keyup so I might have to revert to a search button and loading animation.
Any help is much appreciated.
You could implement a Tree-Structure which would allow you to search more efficient, tho I do not think this is what you want to do. You could also have a backend handle the search and give the results, this is what I would do. So have PHP process the search query and return a new JSON set. Your last option is to just let the browser freeze.
I would prefer the PHP-solution. The loading animation can just wait until PHP returned the data and then show it. This uses the server to process the request, so nothing will freeze - it's a really good solution in my opinion.
For the user, I'd suggest the following: Register keystrokes and give it a "timeout". As soon as the user didn't type for 500ms, query the PHP-script. You can do this via XMLHttpRequest and parse the result using JSON.parse. No need for jQuery here at all.
Personally I think you should send all that data to the client anyway, if you create an API for the data and filter it via an AJAX request, which returns the filtered result. Looking at your example data, it seems that this isn't user specific, so pulling the data from the database / wherever and caching it seems to be the best solution.
jQueryUI Autocomplete has an example on how to achieve this here
This is their example, making an AJAX request whenever the user has typed in a minimum of 3 characters:
$( "#city" ).autocomplete({
source: function( request, response ) {
$.ajax({
url: "http://gd.geobytes.com/AutoCompleteCity",
dataType: "jsonp",
data: {
q: request.term
},
success: function( data ) {
response( data );
}
});
},
minLength: 3,
select: function( event, ui ) {
log( ui.item ?
"Selected: " + ui.item.label :
"Nothing selected, input was " + this.value);
},
open: function() {
$( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
},
close: function() {
$( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
}
});
You don't have to use jQuery Autocomplete, but you get the idea.
Create a map with a structure that is easier to search
var map = [];
(function _search(o) {
if ( typeof o !== 'object' ) return;
if (Array.isArray(o)) {
o.forEach(function(item) { _search(item) });
} else if ('Title' in o) {
map.push(o);
} else {
for (var key in o) {
if ( typeof o[key] === 'object' ) {
if ( Array.isArray(o[key]) ) {
o[key].forEach(function(item) { _search(item) });
} else {
_search(o[key]);
}
}
}
}
}(obj));
Then you can just filter the map
var result = map.filter(function(obj) {
return obj.Title.toLowerCase().indexOf(SearchValue.toLowerCase()) === 0;
});
FIDDLE

How to manipulate JSON object to remove root key within Javascript?

I have a json url that returns data in the format
{
"photos" : [
{
"id": 1, "image":"https://path/to/my/image/1.jpg"
},
{
"id": 2, "image":"https://path/to/my/image/2.jpg"
}
]
}
I'm using the json in a javascript function, and need to manipulate it to remove the root key. i.e. I want something that looks like
[
{
"id": 1, "image":"https://path/to/my/image/1.jpg"
},
{
"id": 2, "image":"https://path/to/my/image/2.jpg"
}
]
I've been hacking around with various approaches, and have referred to several similar posts on SO, but nothing seems to work. The following seems like it should.
var url = 'http://path/to/my/json/feed.json';
var jsonSource = $.getJSON( url );
var jsonParsed = $.parseJSON(jsonSource);
var jsonFeed = jsonParsed.photos
What am I doing wrong?
A couple of issues there.
That's invalid JSON, in two different ways. A) The : after "photos" means that it's a property initializer, but it's inside an array ([...]) when it should be inside an object ({...}). B) There are extra " characters in front of the images keys. So the first thing is to fix that.
You're trying to use the return value of $.getJSON as though it were a string containing the JSON text. But $.getJSON returns a jqXHR object. You need to give it a success callback. That callback will be called with an object graph, the JSON is automatically parsed for you.
Assuming the JSON is fixed to look like this:
{
"photos": [
{
"id": 1,
"image": "https://path/to/my/image/1.jpg"
},
{
"id": 2,
"image": "https://path/to/my/image/2.jpg"
}
]
}
Then:
$.getJSON(url, function(data) {
var photos = data.photos;
// `photos` now refers to the array of photos
});

getjson obj name and iterate child obj's

I'm fresh to js and web dev for that matter and am looking for some help.
I'm trying to grab enough information to format and make another request. This is what i have so far
JavaScript
$( document ).ready(function(sb_shows) {
$.getJSON( "http://<myname>/api/<apikey>/?cmd=shows&callback=?", function(shows_obj) {
//$.each(shows_obj, function(key, value) {
if ( shows_obj.result == "success") {
document.write(shows_obj.result);
$.each(shows_obj.data, function(key, value) {
$.each(this.cache function(key, value) {
document.write( "<p> "+value.banner+"<p>");
});
document.write( "<p>"+value.show_name+" - "+value.tvrage_id+ "<p>");
});
}
else {
document.write("fail..");
}
});
});
JSON Sample
{
"data": {
"72023": {
"air_by_date": 0,
"cache": {
"banner": 1,
"poster": 1
},
"language": "en",
"network": "HBO",
"next_ep_airdate": "",
"paused": 0,
"quality": "SD",
"show_name": "Deadwood",
"status": "Ended",
"tvrage_id": 3267,
"tvrage_name": "Deadwood"
},
"72231": {
"air_by_date": 1,
"cache": {
"banner": 1,
"poster": 1
},
"language": "en",
"network": "HBO",
"next_ep_airdate": "2013-09-13",
"paused": 0,
"quality": "HD720p",
"show_name": "Real Time with Bill Maher",
"status": "Continuing",
"tvrage_id": 4950,
"tvrage_name": "Real Time With Bill Maher"
},
},
"message": "",
"result": "success"
}
What i'm hoping to achieve is grab the id under data (e.g. 72023 and 72231), I originally thought i'd be able to do something like
$(this).parent()
Its a object however and that doesn't appear to work
Also I'd like to be able to iterate through the sub obj's, something like below
$.each(shows_obj.data, function(key, value) {
$.each($(this).cache function(key, value) {
document.write( "<p> "+value.banner+"<p>");
});
document.write( "<p>"+value.show_name+" - "+value.cache.banner+ "<p>");
});
Any and all recomendations/suggestions will be appreciated. Please explain suggestions, i'm kinda slow:)
In your first $.each() call on the data object, your key is actually the ID number you'r e looking for. Google quickly gave me an introduction to JSON which might help you out.
As per the jQuery.each documentation the this keyword is the same as the value keyword. Your $.each($(this).cache, ...) should simply be $.each(this.cache, ...) or $.each(value.cache, ...) as you're not traversing the dom ($(..)) but passing an object to the $.each() function. Just like in the earlier case if you traverse this.cache you would have your callback be called twice:
// first
key => banner
value => 1
// second
key => poster
value => 1
If you would've just wanted the banner from the cache the thing to do would've been: value.cache.banner in your original $.each(shows_obj.data, ...)

Getting Open Graph object ID from page URL

how can I get the Facebook Object ID paired to a page from the page itself?
For example, I asked directly for the Object ID 325186347604922 and i got:
<pre>
{
"url": ".../ricetta-bigne_salati.htm",
"type": "ricettepercucinare:recipe",
"title": "Bignè salati",
"image": [
{
"url": ".../magazine/wp-content/uploads/2013/03/101-150x150.jpg",
"width": 150,
"height": 150
}
],
"description": "Gli ingredienti e la procedura per preparare la ricetta Bignè salati.",
"data": {
"course": "Antipasto",
"foreign_id": 130400
},
"updated_time": "2013-03-28T10:12:17+0000",
"id": "325186347604922",
"application": {
"id": "118665634826424",
"name": "Ricettepercucinare.com",
"url": "https://www.facebook.com/apps/application.php?id=118665634826424"
}
}</pre>
But how, for example, this page http://www.ricettepercucinare.com/ricetta-bigne_salati.htm could know its own ID?
Thank you.
Its not currently possible to look up an object ID from the URL - although it should be.
It should be possible using:
http://graph.facebook.com/?id=http://www.ricettepercucinare.com/ricetta-bigne_salati.htm
but this isn't working.
Please raise a bug at developers.facebook.com/bugs
What about this guy's solution: http://blog.odbol.com/?p=9
function facebookGetIdForUrl(url, callback) {
//see http://developers.facebook.com/docs/reference/fql/object_url/
FB.api({
method: 'fql.query',
query: "SELECT id FROM object_url WHERE url = '" + url + "'"
}, function(response) {
callback(response[0].id);
});
}
facebookGetIdForUrl("http://facebook.com", function (id) {
alert("Facebook ID = " + id);
});
It's possible with FQL:
select id, url from object_url where url in ('http://www.watchth.is/movies/9166-baraka')
See it in the Graph API Explorer, or simply use this ajax call: https://graph.facebook.com/fql?q=select%20id%2C%20url%20from%20object_url%20where%20url%20in%20('http%3A%2F%2Fwww.watchth.is%2Fmovies%2F9166-baraka')&format=json&suppress_http_code=1
Thanks to Rees' response to a similar question

Categories