jQuery / Tumblr - parsing JSON data - javascript

I'm trying to read Tumblr informations via the JSON API (and recuperate the total numbers of post for a blog)
My JS code looks like this:
$.getJSON("http://demo.tumblr.com/api/read/json?callback=?", function(json) {
$('.counter').html(json.posts-total);
});
but doesn't work.

Try:
$.getJSON("http://demo.tumblr.com/api/read/json?callback=?", function(json) {
$('.counter').text(json["posts-total"]);
});
Since - is an operator, JavaScript would otherwise try to subtract total from json.posts.
You can see this working in this JSFiddle

not worked with tumblr but an easier way to use jQuery to get json data is
$.get( "http://demo.tumblr.com/api/read/json", {callback:"?"}, function(data){
alert( data.posts-total )
}, "json");
maybe a different approch will help, also the console of firebug is very valiuable in seeing why an ajax request hasn't worked. Maybe check that too firebug->console
if none of this helps shoot back a little more info and will see what else can be a miss..

Related

Use Javascript to receive variable from remote php file?

I need to retrieve a variable from a remote php file using javascript. I'm doing this using phonegap so same origin policy doesn't apply. I guess I need to use json / ajax but I can't find any tutorials that show me how to do this.
Is it as simple as having this in a php file:
<?php
$var = 'stuff';
echo json_encode( $var );
?>
And something like this in my application:
$.getJSON('mysite.com/test.php', function( data ) {
$.each( data, function( i, entry ) {
alert( entry );
});
Or is this totally the wrong approach? Any help would be great, thanks.
so for starters here are the docs on JQuery's ajax & the docs for JQuery's getJSON; and finally a slightly dated but decent tutorial explaining the basics on how to get started with raw .JSON files.
typically when I am dealing with JSON i am interacting with a web API; and most of the time they are RESTful api's at that... creating one is slightly more complex than what you have there but your thought process is on track.
here is a working access point to the google finance stock quotes api running a query on microsoft:
http://finance.google.com/finance/info?client=ig&q=MSFT
and an example of a json call (using jsonp for accessing an external url):
$.ajax({
url: 'http://finance.google.com/finance/info?client=ig&q=MSFT',
dataType: 'jsonp',
success: function(data){
console.log( data );
}
});
to make things easier i would try and break the work into two steps... first get a handle on accepting data from a api you know is functioning (ie google finance above)... and then move on to the next step of trying to write your own WebAPI in php (eg say you wanted to build your "variable" into a database or something a bit more useful than a flat php file). this way you can debug a bit easier with less hair loss
I'm using jquery and
I used to do like this in my PHP (if using json):
<?php
$var = 'stuff';
echo '{"var":"'.$var.'"}';
?>
it would return to a json.
and the ajax :
$.ajax({
url : "mysite.com/test.php",
dataType : "json",
data :"",
type : "POST",
success :
function (data){
alert(data.var);
}
});
(data and type in the ajax are not needed if you just want to get json from "mysite.com/test.php");

How do I assign a JSON response from this API I'm using to elements on my page?

I'm trying to use the API from https://developer.forecast.io and I'm getting a JSON response, this is the first time I'm using an API and all I really need to know is, how do I assign the JSON response I get back from their API to elements on my page. Thanks!
This is done with a script-tag in my header:
script(src='https://api.forecast.io/forecast/APIKEY/LAT,LON')
http://api.jquery.com/jQuery.ajax/ you need to add a success callback, at the bottom of that page are examples you can look at.
EDIT
ok i saw that you are using a script tag with the request, since the api is outside your current domain you need to make a JSONP request
$(document).ready(function(){
$.ajax({
url: 'https://api.forecast.io/forecast/APIKEY/LAT,LON',
dataType: 'jsonp',
success: function(data){
//do whatever you want with the data here
$("body").append(JSON.stringify(data));
}
});
});
off course you need to make some tweaks to that piece of block but you get the idea
What you're looking for is DOM manipulation. DOM is the HTML Document Object Model, an object representation of the HTML comprising a document. There are a lot of ways to go about this, but one of the more popular Javascript libraries for performing this task is jQuery. See their help documentation category on manipulation for more information.
OK, based on your clarification, you're not yet using AJAX. I say "not yet", because you're going to need to. Again, I'll recommend jQuery for that, and their own documentation as the best resource. For a simple "get", your easiest option is the getJSON method.
So, at a very simple level you might do something like:
$(function(){
$.getJSON('url_to_api', function(data) {
$("#SummaryBox").append("<div>" + data.hourly.summary + "</div>");
}
});

How to get data using jsonp?

I'm trying to fetch some text from http://www.ikea.com/us/en/catalog/products/10176292
using jsonp.
To test if it works this is what I did
$.getJSON("http://www.ikea.com/us/en/catalog/products/10176292?format=json&jsoncallback=?",function(data) {
$('h1').text(data.modified);
});
This doesn't work so it's probably no valid but all the jsonp documentation I've found on google use either twitter or flickr API as examples. I'm pretty sure IKEA doesn't have an API so those methods don't really help me.
However this does work and returns text from flickr
$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?id=25053835#N03&format=json&jsoncallback=?",function(data) {
$('h1').text(data.title);
});
I'm attempting this because I saw this example http://www.foxycart.com/whos-using-foxy/case-studies/modernash and it appears to work with jsonp fetching text data from ikea. I don't need anything as complex, just to be able to retrieve some simple text.
Can someone please point me in the proper direction or give some tips.
Thanks
The link to Ikea isn't JSON so you can't pull from it. It looks like Ikea doesn't have a public API. So, you won't be able to get any data from them to use.
For Flickr you are on the right track. Here is how you can do it.
$.ajax({
dataType: 'jsonp',
url: 'http://api.flickr.com/services/feeds/photos_public.gne?id=25053835#N03&format=json&jsoncallback=?',
success: function(data){
console.log(data);
}
});
If you want to get the title you would do data.title and so on.
You can supplement your getJSON with ajax (see official docs here - http://api.jquery.com/jQuery.getJSON/), then it is super easy to declare JSONP.
$.ajax({
dataType: "jsonp",
url: 'http://api.flickr.com/services/feeds/photos_public.gne?id=25053835#N03&format=json&jsoncallback=?',
data: data,
success: function( data ) {
$('h1').text(data.modified);
});
Edit: #Matt Ball is right. Before you use something like the ajax call above you need to make sure that the URL that you are using is returning actual json. You should be able to navigate to the desired URL and see the raw JSON. Then all the above function will do is fetch and parse accordingly.
It looks to me like they are just scraping data from the site. All the product information is stored in the html and they are adding that to an object into their own cart.
Since the you drag the image to their bookmarklet I looked at the data stored in the image # http://www.ikea.com/us/en/catalog/products/20011408/#/80193735 :
<img id="productImg" src="/us/en/images/products/lack-side-table__0115088_PE268302_S4.JPG" border="0" alt="LACK Side table IKEA The high-gloss surfaces reflect light and give a vibrant look. Easy to assemble. Low weight; easy to move." title="LACK Side table - high gloss red, 21 5/8x21 5/8 " - IKEA" width="500" height="500" class="mn_global_shadow ui-draggable" style="width: 244px; display: inline-block; height: 244px; left: 0px; top: 0px;">
In the title we get the name, finish, color, and size.
The price and quantity are held in id's/classes which seem standard across the entire site.
How it all works beyond that I haven't looked at, but it doesn't seem too complex.
Hope this helps.
You probably need to provide some custom headers. Wireshark is your friend

Songkick API Using JQuery

I'm having issues gathering data using JSON on the Songkick API. I'm really new to jQuery and Javascript so please forgive me if this looks really crude. I've spent some time trying to research the proper syntax I need but I just keep ending back up at square one.
What im trying to do is make the request using jQuery and then add the results into my HTML in an list. Any help anyone can give me would be fantastic.
Here's what I have so far.
<script>
$.getJSON("http://api.songkick.com/api/3.0/artists/3950031/calendar.json?apikey={apikey}",
function(data){
var events = data['resultsPage']['results']['event'];
for (var i=0;i < events.length; i++) {
$("#events").append('<li>'+events[i]['displayName']+'</li>');
}
});
</script>
Thanks!
sorry i took so long to get back, i left the office about the time you replied last night
here is what I came up with:
$(document).ready(function() {
$.ajax({
url: "http://api.songkick.com/api/3.0/artists/480448/calendar.json?apikey=APIKEY&jsoncallback=?",
dataType: "jsonp", // <== JSON-P request
success: function(data){
$.each(data["resultsPage"]["results"]["event"], function(i, entry){
$("#events").append('<li>'+entry.displayName +'</li>');
});
}
});
});
I think the issue you were having was with JSON, JSON is subject to the same origin policy (which I read about on here ( $.getJSON not working ). Instead you have to use JSON-P adding
&jsoncallback=?
at the end of the URL tells Songkick to send it as a JSON-P request. This was the main issue.
Other issues included minor coding errors: there was an extra ( in your append string, I also used $.Each as appose to a for loop but either would work, hope this helps and you may want to take your API code off if the fix worked :) Just change API Key to your key and it should be fine (i also changed the band to chevelle as the other one had no entries)

Problems using jQuery AJAX to parse XML

I'm not a very experience programmer and have been learning HTML/CSS/JS on the fly. I've been trying to parse XML using jQuery AJAX methods with absolutely no luck.
Here is my code in use: http://jsfiddle.net/Kb5qj/1/
And here is my code in plain sight:
$(document).ready(function() {
var divid = "#xmlcontent"
function parseXML(xml) {
$(divid).empty();
$(xml).find("CD").each(function() {
var artist = $(this).find("ARTIST").text();
var title = $(this).find("TITLE").text();
$(divid).append("<li>" + artist + " - " + title + "</li>");
});
}
function printError() {
$(divid).html("An error occurred");
}
$.ajax({
type: "GET",
url: "www.w3schools.com/ajax/cd_catalog.xml",
dataType: "xml",
success: parseXML,
error: printError
});
});
I don't know what the problem could be. I have written and re-written and copy/pasted that $.ajax call many many times, but no matter what I do nothing ever happens. Help me please?
like I mentioned it will fail on jsfiddle as they dnt actually send the get request. here is the api on how to achieve the same: http://doc.jsfiddle.net/use/echo.html
If you try the same on your local system it will fail probably cos you are making a cross domain request and your browser natively blocks such requests. That is where jsonp comes it to play its to retrieve json data over cross domains..
You can hack it a little to do the same for js.. here is a SO post about the same: Is there an existing tool for jsonp like fetching of xml in jquery?
With a little bit of fudging, everything in the parsing seems to work fine. Check out this JSFiddle.
You can't use get requests from JSFiddle, but I mocked up the XML into HTML. You may want to try placing your XML document into the DOM to help suss your issue.

Categories

Resources