Can't get Google Plus API to work - javascript

I have been trying to understand API for a while now. But i am just lost...
I am trying to do something as simple as to retrieve and display my Google Plus Tagline.
$.getJSON("https://www.googleapis.com/plus/v1/people/103039534797695934641?key=xxxxxxxxxxxxxxxxxxxxxxxxxxx", function(data) {
html = data.nickname;
// Insert the generated HTML to the DOM
$('.shots').html(html);
});
What am i doing wrong?
Should i maybe insert a callback in the link - and if so, do you know how that is done?
I have tried all the ways i could think of.

You should try using the Google+ JavaScript Quickstart sample to get going as opposed to performing XHRs against the endpoint, passing your API key... and effectively writing your own client library.
Also, if you are just interested in seeing what the API can do, you should start from the Google APIs explorer for Google+.
The following HTML does what you need:
<html>
<body>
</body>
<script>
var key = 'YOUR_API_KEY';
function doStuff(){
gapi.client.load('plus','v1', function(){
gapi.client.setApiKey(key);
gapi.client.plus.people.get({'userId': '103039534797695934641'}).execute(function(result){
alert(result.tagline);
console.log(JSON.stringify(result));
});
});
}
</script>
<script src="https://apis.google.com/js/client.js?onload=doStuff"></script>
</html>
Note that I am using the Google-provided client library. You can explore some more by opening the console in your browser and browsing through the gapi.client.plus[...] methods.

Unless you need something more specific, all you need to do is change data.nickname to data.tagline:
$.getJSON("https://www.googleapis.com/plus/v1/people/103039534797695934641?key=AIzaSyBaDZGM-uXuHc-VZZ2DINzVBcIDMN_54zg", function(data) {
var html = data.tagline;
// Insert the generated HTML to the DOM
$('.shots').html(html);
});
You can open the URL in a browser (Chrome/Firefox works for me) that is used in $.getJSON to view more properties that data contains such as data.kind, data.nickname, and data.occupation.
JSFiddle Example

Related

Display the html returned by fetch()

I am using a web app to submit some form data to an API. The process is as follows:
Enter data in a html form
When the user presses a button I use javascript to collect the form data and create a JSON string out of it
Using fetch() I post that JSON to an API endpoint
The API server returns a redirect to a new page (complete html document)
What I would like to achieve is that when the fetch request completes the user would be redirected to the page that was received from the API server. I tried searching for this however I couldn't find anything since most examples are for storing the response in a variable and doing something with it.
This needs to be done in vanilla Javascript, since it is an embedded system and I would like to use as little dependencies as possible.
May be this will work for you.
<html>
<head>
<meta charset="UTF-8" />
</head>
<body>
<h1>site</h1>
<script>
document.addEventListener("DOMContentLoaded", async () => {
const res = await fetch('/index2.html');
const text = await res.text();
document.open();
document.write(text);
document.close();
});
</script>
</body>
</html>
The answer from Alexander works, however as Nikola already said it's not really considered good practice to clear current html and replace it.
At the end I opted for a different approach. I collected all the data from the original form, created a json string out of it and then dynamically created another form with only one field to which I assigned the value of json string and then submitted this new form. This way I could achieve the redirect behavior of the element while making minimum modifications on the server side.

How to parse a widget that returns javascript to build DOM instead of HTML?

We are provided a widget that prints a playlist of songs provided by NPR. We need to fetch, programmatically every few seconds, the currently airing song, the one at the top of the list, and then save it to a file or something. Easy right? wget http://composer.nprstations.org/asasfasdfasf | sed 'find/it' > nowplaying.txt or something to that effect. Could be python, bash, pascal, whatever.
HOWEVER.. upon further inspection, the widget does not simply return the HTML, it returns a bunch of javascript that then builds the DOM. So it's client side logic that builds the playlist, not server side, or maybe both. Once the page is loaded, I can just as easily get the text we need, typing something like $('.now-playing a').html()[0] in the console would do the trick, but I don't know how we could do this programmatically.
So we need a browser with a javascript engine to first process the page before we can parse it. What would you recommend we do??
Thanks for any help!!
this is the entire response from the widget server:
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="/widgets/src/whatson.js"></script>
<script src="/widgets/src/jquery-deparam.js"></script>
<script>
var configuration = {
schedule: 'now'
};
if ( window.location.search ) configuration = $.extend({}, configuration, $.deparam( (window.location.search).replace('?','') ));
$(function(){
$('.now-playing').whatsOn( configuration );
});
</script>
</head>
<body>
<div class="now-playing"></div>
</body>
</html>
See, from what you posted, the page runs the whatsOn JS function.
As you told, in commnets it connects to the API with the your station ID.
So, the next step is simulating the same - you can try connect with the wget, or some scripting language, to the same API with the same "station ID" as JS does, and analyse what you got.
And repeat the same with the next step, if needed.
It is impossible to solve the problem without access...
Alternatively, you can check the WWW::Mechanize::Firefox perl module. Here are some examples and an cookbook ;)

Refresh Part of Page (div)

I have a basic html file which is attached to a java program. This java program updates the contents of part of the HTML file whenever the page is refreshed. I want to refresh only that part of the page after each interval of time. I can place the part I would like to refresh in a div, but I am not sure how to refresh only the contents of the div. Any help would be appreciated. Thank you.
Use Ajax for this.
Build a function that will fetch the current page via ajax, but not the whole page, just the div in question from the server. The data will then (again via jQuery) be put inside the same div in question and replace old content with new one.
Relevant function:
http://api.jquery.com/load/
e.g.
$('#thisdiv').load(document.URL + ' #thisdiv');
Note, load automatically replaces content. Be sure to include a space before the id selector.
Let's assume that you have 2 divs inside of your html file.
<div id="div1">some text</div>
<div id="div2">some other text</div>
The java program itself can't update the content of the html file because the html is related to the client, meanwhile java is related to the back-end.
You can, however, communicate between the server (the back-end) and the client.
What we're talking about is AJAX, which you achieve using JavaScript, I recommend using jQuery which is a common JavaScript library.
Let's assume you want to refresh the page every constant interval, then you can use the interval function to repeat the same action every x time.
setInterval(function()
{
alert("hi");
}, 30000);
You could also do it like this:
setTimeout(foo, 30000);
Whereea foo is a function.
Instead of the alert("hi") you can perform the AJAX request, which sends a request to the server and receives some information (for example the new text) which you can use to load into the div.
A classic AJAX looks like this:
var fetch = true;
var url = 'someurl.java';
$.ajax(
{
// Post the variable fetch to url.
type : 'post',
url : url,
dataType : 'json', // expected returned data format.
data :
{
'fetch' : fetch // You might want to indicate what you're requesting.
},
success : function(data)
{
// This happens AFTER the backend has returned an JSON array (or other object type)
var res1, res2;
for(var i = 0; i < data.length; i++)
{
// Parse through the JSON array which was returned.
// A proper error handling should be added here (check if
// everything went successful or not)
res1 = data[i].res1;
res2 = data[i].res2;
// Do something with the returned data
$('#div1').html(res1);
}
},
complete : function(data)
{
// do something, not critical.
}
});
Wherea the backend is able to receive POST'ed data and is able to return a data object of information, for example (and very preferrable) JSON, there are many tutorials out there with how to do so, GSON from Google is something that I used a while back, you could take a look into it.
I'm not professional with Java POST receiving and JSON returning of that sort so I'm not going to give you an example with that but I hope this is a decent start.
You need to do that on the client side for instance with jQuery.
Let's say you want to retrieve HTML into div with ID mydiv:
<h1>My page</h1>
<div id="mydiv">
<h2>This div is updated</h2>
</div>
You can update this part of the page with jQuery as follows:
$.get('/api/mydiv', function(data) {
$('#mydiv').html(data);
});
In the server-side you need to implement handler for requests coming to /api/mydiv and return the fragment of HTML that goes inside mydiv.
See this Fiddle I made for you for a fun example using jQuery get with JSON response data: http://jsfiddle.net/t35F9/1/
Usefetch and innerHTML to load div content
let url="https://server.test-cors.org/server?id=2934825&enable=true&status=200&credentials=false&methods=GET"
async function refresh() {
btn.disabled = true;
dynamicPart.innerHTML = "Loading..."
dynamicPart.innerHTML = await(await fetch(url)).text();
setTimeout(refresh,2000);
}
<div id="staticPart">
Here is static part of page
<button id="btn" onclick="refresh()">
Click here to start refreshing every 2s
</button>
</div>
<div id="dynamicPart">Dynamic part</div>
$.ajax(), $.get(), $.post(), $.load() functions of jQuery internally send XML HTTP request.
among these the load() is only dedicated for a particular DOM Element. See jQuery Ajax Doc. A details Q.A. on these are Here .
I use the following to update data from include files in my divs, this requires jQuery, but is by far the best way I have seen and does not mess with focus. Full working code:
Include jQuery in your code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
Create the following function:
<script type="text/javascript">
function loadcontent() {
$("#test").load("test.html");
//add more lines / divs
}
</script>
Load the function after the page has loaded; and refresh:
<script type="text/javascript">
$( document ).ready(function() {
loadcontent();
});
setInterval("loadcontent();",120000);
</script>
The interval is in ms, 120000 = 2 minutes.
Use the ID you set in the function in your divs, these must be unique:
<div id="test"></div><br>

Reading contents from a JSON url and writing out those contents

I have a url [https://www.inquicker.com/facility/americas-family-doctors.json] that is a JSON data url. How can I access the contents of this url, and write out the values.
The format contains schedules as an array that inside it contains schedule_id, name, and available_times. I have tried various ways of getting the JSON file, but none have worked.
UPDATE:
Well I have got it this far with this code, and it's laying out what looks like objects from the array. So I believe I got the cross site issue under control. I just need to figure out how to access the data now.
<!DOCTYPE html>
<html>
<head>
<title>JQuery (cross-domain) JSONP</title>
<script type="text/javascript"src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"> </script>
<script>
$(document).ready(function(){
$.getJSON('https://www.inquicker.com/facility/americas-family-doctors.json',
function(data){
alert(data.facility);
$.each(data.schedules, function(i, name){
$('#names').append('<li>' + name.available_times[0] + '</li>');
});
});
});
</script>
</head>
<body>
<ul id="names"></ul>
</body>
</html>
Any help, or suggestions will be greatly appreciated, Thanks.
You cannot generally pass an Ajax request across domains. Normally a server will refuse any Ajax calls that don't come from the same source unless it is explicitly configured otherwise. I am guessing that you aren't calling from the same domain, given that you are using a fully-qualified URL. If you own the server, you will have to configure it to accept such calls from your other domain.
If this is not the case, launch the script in Firefox with Firebug running and look at the console output and tell me what error you get if any.
Once you manage to pass the JSON from your server back to the page, you will retrieve it in your JavaScript as a string. You then need to execute this function:
var jsonObject = JSON.parse(jsonString);
where jsonString is the string that you received from your server. jsonObject becomes an object representation of the JSON passed back to the answer that you can access using dot notation.
Try something like :
alert(json.facility);
There is no title json object in the url you have mentioned.
The JSON is already parsed when it comes to your function.
$.get('https://www.inquicker.com/facility/americas-family-doctors.json', function(result){
alert(result.facility); //Do whatever you want here
// result.schedules array is also ready
});

Check iframe status after AJAX File Upload with Rails

There is a similar post Retrieving HTTP status code from loaded iframe with Javascript but the solution requires the server-side to return javascript calling a function within the iframe. Instead, I would simply like to check the HTTP status code of the iframe without having to call a function within the iframe itself since my app either returns the full site through HTML or the single object as JSON. Essentially I've been trying to implement a callback method which returns success|failure dependent upon the HTTP status code.
Currently I have uploadFrame.onLoad = function() { ... so far pretty empty ... } and I am unsure what to check for when looking for HTTP status codes. Up until now, I've mainly relied upon jQuery's $.ajax() to handle success|failure but would like to further understand the mechanics behind XHR calls and iframe use. Thanks ahead of time.
UPDATE
The solution I came up with using jQuery
form.submit(function() {
uploadFrame.load(function() {
//using eval because the return data is JSON
eval( '(' + uploadFrame[0].contentDocument.body.children[0].innerHTML + ')' );
//code goes here
});
});
I think the best solution is injecting <script> tag into your iframe <head> and insert your "detecting" javascript code there.
something like this:
$('#iframeHolderDivId').html($.get('myPage.php'));
$('#iframeHolderDivId iframe head').delay(1000).append($('<script/>').text('your js function to detect load status'));
Maybe it's not the best solution but I think it works

Categories

Resources