Trying to read the Google Calender JSON Data using JQuery - javascript

I am trying to read the google calendar events from the JSON response but nothing happens.
I have tried the code from here but that too is not working. I am adding the code to my CMS and when I check on the front end, nothing appears. I even tried running this fiddle http://jsfiddle.net/bGdhD/ but this also doesn't provide any response.
My google calendar URL is
https://www.google.com/calendar/feeds/varun.luthra.72%40gmail.com/public/full?alt=json-in-script&max-results=25&singleevents=false&futureevents=true&sortorder=descending&orderby=starttime
<script>
var event = '';
var gclaData = 'https://www.google.com/calendar/feeds/varun.luthra.72%40gmail.com/public/full?alt=json-in-script&max-results=25&singleevents=false&futureevents=true&sortorder=descending&orderby=starttime';
$.getJSON(gclaData,function(data){
$.each(data.feed.entry, function(i, entry){
event += '<div class="eventHolder">';
event += '<div class="eventTime">'+ entry.gd$where[0].startTime+"</div>";
event += '<div class="eventName">'+ entry.title.$t + "</div>";
event += '<div class="eLink">'+ entry.link[0].href + "</div>";
event += '</div>';
});
$('#output').html(event);
});
</script>
<div id="output"></div>
Also, could this be a cross domain issue?

It's not a cross domain problem, because the response includes the Cross Origin Resource Sharing header:
access-control-allow-origin:*
The problem is the response is a JSONP response and so includes a callback function. This makes it invalid JSON (unless you strip the callback).
Option 1: If you set &callback=? in the URL, jQuery will treat the response as JSONP:
var gclaData = 'https://www.google.com/calendar/feeds/varun.luthra.72%40gmail.com/public/full?alt=json-in-script&max-results=25&singleevents=false&futureevents=true&sortorder=descending&orderby=starttime&callback=?';
Option 2: Use $.ajax() and strip the callback:
gdata.io.handleScriptLoaded(
Also strip the closing parenthesis and semicolin );. This leaves you with a valid JSON response, which needs to be decoded from a string to a Javascript object using JSON.parse() or similar.
Also, there doesn't appear to be an entry array or object in the response, so you need to modify your success event accordingly.
Last point, this will not work:
entry.gd$where[0]
If the variable name has special characters, use the [] notation:
entry['gd$where'][0]

Related

How do I change the link JQuery requests relating to the url?

At the moment I have the top of the code like this:
$.getJSON(' https://api.roleplay.co.uk/v1/player/' + "END-LINK", function(data)
What I want is that the "END-LINK" bit will be the end of my url - for example, if my url is www.link.com/player.html/76561198062083666 I want it to add those numbers at the end to the jquery request so it will get the api "https://api.roleplay.co.uk/v1/player/76561198062083666"
I think what you want is to retrieve the ID from the link and send it to the API.
var endLink = window.location.href.substr(window.location.href.lastIndexOf('/') + 1)
$.getJSON(' https://api.roleplay.co.uk/v1/player/' + endLink, function(data){...})
In order to query your player ID, you would assign it to a local variable, and then pass that local variable to your .getJSON() function just as you have, expect without the quotes:
var end_link = 76561198062083666;
$.getJSON('https://api.roleplay.co.uk/v1/player/' + end_link, function(data) {
console.log(data);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Note that I have replaced END-LINK with end_link, as you cannot have hyphens in variable names (the parser will treat it as subtraction).
Also note that you will be unable to retrieve your information through .getJSON(), as RolePlay.co.uk is transmitting a No 'Access-Control-Allow-Origin' header, meaning they disallow people from querying it in accordance with Cross Origin Resource Sharing (CORS).
This is typically handled on the server, but considering you don't have access, you can bypass it by adding the argument --disable-web-security to your browser launcher.
Hope this helps! :)
Obsidian Age told you very well what you can do to solve your problem.
If I'm not wrong, you want to send the local variables from the link to the API, and you can do it in this way:
var endLink = window.location.href.substr(window.location.href.lastIndexOf('/') + 1)
$.getJSON(' https://api.roleplay.co.uk/v1/player/' + endLink, function(data){
console.log(data);
}
);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

jQuery Parse JSON Response

I am successfully Posting to a PHP file, and getting a good response. The part I cannot seem to get is parsing it out then displaying it on my page. Here is my javascript in a validate handler:
submitHandler: function(form) {
var formData = $(form).serialize();
$.post('http://test.php', formData, function(data) {
if(data.success) {
$('#load').show();
var response = i;
$('#load').hide();
//var msg = '';
for(var i = 0; i < x.flights.length; i++) {
msg += '<span>';
msg += '<p>Flight Number: ' + x.flights[i].flight_number + '</p>';
msg += '<p>Cost: ' + x.flights[i].cost + '</p>';
msg += '</span>';
}
//this is were I think it should display. but It's not working
$('#load').html(msg);
Here is my json response:
success
true
message
"Success"
flights
[Object { flight_number="334", cost="983.40", departure_city="Kearney Regional Airpor...arney, Nebraska - (EAR)", more...}]
0
Object { flight_number="334", cost="983.40", departure_city="Kearney Regional Airpor...arney, Nebraska - (EAR)", more...}
flight_number
"334"
cost
"983.40"
departure_city
"Kearney Regional Airport, Kearney, Nebraska - (EAR)"
arrival_city
"Chadron Muni Airport, Chadron, Nebraska - (CDR)"
departs
"2014-03-19 04:33:00"
arrives
"2014-03-19 08:12:00"
duration
"219"
adult_seats_available
"2"
senior_seats_available
"1"
I know you you are not seeing the JSON response, but I can see it in FF firebug. I'm new to jQuery/JSON, and I just want to print the response to my page. Thanks in advance.
Look into JSON.stringify(data) doc I don't know where you want to display your JSON but if you just want to see what it is open up the debugger and console.log(JSON.stringify(data)); should do it.
You are using post method and it may default return xml, json, script, text, html. So you are getting the data from post method.
Try looking at https://api.jquery.com/jQuery.post/
And if you want to access it, then you can use JSON.stringify(data) to show json as a string. And to access data from json you can use dot(.) notation.
There's a couple of things to look at here.
First you're adding your html (ie msg) to the #load element ($('#load').html(msg);) but earlier in the code you're hiding it ($('#load').hide();). So I think this will answer your main question; i.e. remove the the line $('#load').hide(); or add $('#load').show(); after the line $('#load').html(msg);.
Still not seeing anything? Then perhaps the response isn't as corrent as you're claiming so perhaps an easier way to check what's been assigned to msg is to alert the html alert(msg); <- make this call after you've built your html.
So aside from this is the use of the #load element you seem to be using it to hold a loading gif but also assigning it the response via the content of msg. Perhaps you need to separate the use of the elements so that the #load element is for the loading gif and you add another element for the response. so you're code is more like this.
html
<div id="load" class="hide"><img src="loading-animation.gif">...</div>
<div id="post-response" class="hide alert"><div>
where the hide class is display none and alert class represents an style for a response alert.
js
submitHandler: function(form) {
// show the loading gif before we make the
// post data and wait for an async response
$('#load').show();
...
$.post('http://test.php', formData, function(data) {
if(data.success) {
// post-back has completed so lets hide the animation
$('#load').hide();
// your code to build html msg
// assign and show the response element
$('post-response').html(msg);
$('post-response').show();
...

script tag hack + how do I communicate after the second level of AJAX

I want to provide an embeddable javascript which will get a script from my server . Which in turn will get some details from the user(the page which which has my embeddable js) and put it back onto my server . How do i go about achieving this .
This is the embeddable js i provide .
<script>
(function() {
read="This is the data which is entered by the user";
var istreet = document.createElement('script'); istreet.type = 'text/javascript'; istreet.async = true;
istreet.src = 'http://xyz.com/a.php;
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(istreet);
})();
</script>
And this is the code on http://xyz.com/a.php
$('<div id="content"></div>').appendTo('body');
$('#content').html('
Some html to inject to the page\'s dom .
');
$.get("http://xyz.com/process.php?dataToProcess="+read,function(data){
alert(data);
});
But I see that the $.get("http://xyz.com/process.php?dataToProcess="+read,function(data){
// leads to a cross domain ajax request
I do not want to solve the cross domain ajax problem .
I want to be able to communicate between the two parties(the one with the embeddable script and my server) seamlessly .
If all you need to do is a GET request, you can use JSON-P(http://en.wikipedia.org/wiki/JSON#JSONP).
In your JavaScript, the syntax would be something like this:
$.getJSON("http://xyz.com/process.php?dataToProcess=" + encodeURIComponent(read) + "&callback=?",
function(result){
alert(result);
});
The "callback=?" property tells JQuery that this is a JSON-P request. JQuery will substitute some arbitrary string for the "?" (more details here: http://api.jquery.com/jQuery.getJSON/).
To make this work properly, you also need to change your process.php handler. The PHP handler should first read the value of the "callback" query parameter, and then wrap the response in that value.
For example, if $.getJSON() sends the parameter "callback=abcd" to the php page, the php page should return:
abcd({"data": "json object with the result"});
A few things to note:
Be sure to escape any user data you send to the server using encodeURIComponent();
If process.php modifies user data, you should be careful when using GET requests, as that could lead to XSRF attacks (http://en.wikipedia.org/wiki/Cross-site_request_forgery).
I used this the cross domain iframe hack to commmunicate between the two different domain . I recommend reading this
http://softwareas.com/cross-domain-communication-with-iframes

Trying to use jQuery to display JSON text data

I know very little (none) JavaScript, or much about using API's. However I would like to display some hotel reviews on my webiste made available over the qype.com API. However I'm struggling with being able to manage this.
This is the code I have so far:
$(document).ready( function() {
$.getJSON( "http://api.yelp.com/business_review_search?term=hilton%20metropole&location=B26%203QJ&ywsid=APIKEY Removed",
function(data) {
$.each( data.businesses, function(i,businesses) {
content = '<p>' + businesses.reviews.text_excerpt + '</p>';
content = '<p>' + businesses.reviews.date + '</p>';
$(content).appendTo("#review");
} );
}
);
} );
I have a div in the body called review where I want to display the text.
Any advice greatly received.
JSON can be found at http://api.yelp.com/business_review_search?term=hilton%20metropole&location=B26%203QJ&ywsid=lOoGGbkYpVmTvxHlWGT2Lw
Also, I have multiple businesses on the same page, how would I make use of this multiple times on the same page, but output the data in different locations?
Update: Ah, I see your error now. businesses.reviews is an array (each business can have more than one review) so you have to loop over each business and each business' reviews.
i had to change some things to get it to run in my test bed, but you can see a sample of this code running here: http://bit.ly/4mTxPp
yelp currently support JSONP calls so you can change your code to:
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
function showData(data) {
$.each(data.businesses, function(i,business){
// extra loop
$.each(business.reviews, function(i,review){
var content = '<p>' + review.text_excerpt + '</p>';
content += '<p>' +review.date + '</p>';
$(content).appendTo('#review');
});
});
}
$(document).ready(function(){
// note the use of the "callback" parameter
writeScriptTag( "http://api.yelp.com/business_review_search?"+
"term=hilton%20metropole"+
"&location=B26%203QJ"+
"&ywsid=lOoGGbkYpVmTvxHlWGT2Lw"+
"&callback=showData"); // <- callback
});
function writeScriptTag(path) {
var fileref = document.createElement('script');
fileref.setAttribute("type","text/javascript");
fileref.setAttribute("src", path);
document.body.appendChild(fileref);
}
</script>
Do you get an error in Firebug using this code? What happens exactly?
I expect this problem is caused by the fact that you're trying to do a cross-domain request which is not allowed. Normally you'll want to do this kind of data gathering on your back-end, but you can use an alternative such as JSONP to do the same.
Take a look at jQuery's documentation on this stuff and it should be clear what's going on.
Also, as a side note: In your callback you have content = which is ok but not ideal. Assigning to content like this will create a variable in the global scope which you do not want. In this case it probably wont cause an issue but say you have 2 of these requests going at once, the second assignment could easily step on the first causing hard-to-debug weirdness. Best to just always create variables with var.
If data.businesses is an array, I would assume that data.businesses[x].reviews is also an array. This code loops the businesses as well as the reviews for each business. It also gets rid of the content variable by appending straight to the #review div.
$.each(data.businesses, function(i,business){
$.each(business.reveiws, function(r,review){
$("#review").append(
'<p>' + review.text_excerpt + '</p>'
).append(
'<p>' + review.date + '</p>'
);
});
});
I think you can specify JSONP with your $.getJSON method by adding "callback=?" to the url parameters.
As of jQuery 1.2, you can load JSON
data located on another domain if you
specify a JSONP callback, which can be
done like so: "myurl?callback=?"
$.getJSON("http://api.yelp.com/business_review_search?term=hilton%20metropole&location=B26%203QJ&ywsid=APIKEY Removed&callback=?",
function(data){
...
});
The problem is that you are making a cross domain request, which is not allowed for security purposes. Either you will have to make a proxy script on your domain (like for example in php) and call yelp from that or fetch the data completely on the server side.
I assume you must be experiencing part of your data (which you are supposed to see) disappearing. I think you must edit your code to:
content = '<p>' + businesses.reviews.text_excerpt + '</p>';
content += '<p>' + businesses.reviews.date + '</p>';
Hope this helps...

jsonp request not working in firefox

I am trying a straightforward remote json call with jquery. I am trying to use the reddit api. http://api.reddit.com. This returns a valid json object.
If I call a local file (which is what is returned from the website saved to my local disk) things work fine.
$(document).ready(function() {
$.getJSON("js/reddit.json", function (json) {
$.each(json.data.children, function () {
title = this.data.title;
url = this.data.url;
$("#redditbox").append("<div>" + title + "<div>");
});
});
});
If I then try to convert it to a remote call:
$(document).ready(function() {
$.getJSON("http://api.reddit.com", function (json) {
$.each(json.data.children, function () {
title = this.data.title;
url = this.data.url;
$("#redditbox").append("<div>" + title + "<div>");
});
});
});
it will work fine in Safari, but not Firefox. This is expect as Firefox doesnt do remote calls due to security or something. Fine.
In the jquery docs they say to do it like this (jsonp):
$(document).ready(function() {
$.getJSON("http://api.reddit.com?jsoncallback=?", function (json) {
$.each(json.data.children, function () {
title = this.data.title;
url = this.data.url;
$("#redditbox").append("<div>" + title + "<div>");
});
});
});
however it now stops working on both safari and firefox. The request is made but what is return from the server appears to be ignored.
Is this a problem with the code I am writing or with something the server is returning? How can I diagnose this problem?
EDIT Changed the address to the real one.
JSONP is something that needs to be supported on the server. I can't find the documentation, but it appears that, if Reddit supports JSONP, it's not with the jsoncallback query variable.
What JSONP does, is wrap the JSON text with a JavaScript Function call, this allows the JSON text to be processed by any function you've already defined in your code. This function does need to be available from the Global scope, however. It appears that the JQuery getJSON method generates a function name for you, and assigns it to the jsoncallback query string variable.
The URL you are pointing to (www.redit.com...) is not returning JSON! Not sure where the JSON syndication from reddit comes but you might want to start with the example from the docs:
$(document).ready(function() {
$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?tags=cat&tagmode=any&format=json&jsoncallback=?", function (data) {
$.each(data.items, function(i,item){
$("<img/>").attr("src", item.media.m).appendTo("#redditbox");
if ( i == 4 ) return false;
});
});
});
(apologies for formatting)
EDIT Now I re read your post, I see you intended to go to api.reddit.com unfortunately you haven't got the right parameter name for the json callback parameter. You might need to further consult the reddit documentation to see if they support JSONP and what the name of the callback param should be.
I'm not sure about reddit.com, but for sites that don't support the JSONP idiom you can still create a proxy technique (on the backend) that would return the reddit JSON, and then you would just make an ajax request to that that.
So if you called http://mydomain.com/proxy.php?url=http://api.reddit.com:
<?php
$url = $_GET["url"];
print_r(file_get_contents($url));
?>
http://api.reddit.com/ returns JSON, but doesn't appear to be JSONP-friendly. You can verify this, if you have GET, via
% GET http://api.reddit.com/?callback=foo
which dumps a stream of JSON without the JSONP wrapper.
http://code.reddit.com/browser/r2/r2/controllers/api.py (line 84) shows the code looking for 'callback' (not 'jsoncallback'). That may be a good starting point for digging through Reddit's code to see what the trick is.

Categories