Check if user +1ed the URL - javascript

I'd like to check if a visitor has +1ed a certain URL (and show him a +1 button if he hasn't). Any ideas?

There's a hidden API for the counts, available at the following URL:
https://clients6.google.com/rpc?key=AIzaSyCKSbrvQasunBoV16zDH9R33D88CeLr9gQ
It expects POST data in JSON-RPC format, so you'll need to send a request like this:
[{
"method": "pos.plusones.get",
"id": "p",
"params": {
"nolog": true,
"id": "http://www.mydomain.com/mypage",
"source": "widget",
"userId": "#viewer",
"groupId": "#self"
},
"jsonrpc": "2.0",
"key": "p",
"apiVersion": "v1"
}]
However, you won't be able to use this in JavaScript due to the Same-Origin policy. This means you'll have to set up a server-side solution unless you go for Option 2.
Option 2 is what I use on a couple custom social plugins. A very simple API is available at http://sharedcount.com, which offers the result as JSON-P if a callback is specified:
var scr = document.createElement("script");
myUrl = encodeURIComponent("http://mydomain.com/mypage"),
apiUrl = "http://api.sharedcount.com/?url="+myUrl+"&callback=shareCounts";
scr.src = apiUrl;
document.body.appendChild(scr);
function shareCounts(data) {
alert(data.GooglePlusOne);
}

Related

Unsplash API triggering download

I'm following triggering guidelines in Unsplash documentation. So the endpoint is:
GET /photos/:id/download
This is the photo's example response:
{
"id": "LBI7cgq3pbM",
"width": 5245,
"height": 3497,
"color": "#60544D",
"urls": { ... },
"user": { ... },
"links": {
"self": "https://api.unsplash.com/photos/LBI7cgq3pbM",
"html": "https://unsplash.com/photos/LBI7cgq3pbM",
"download": "https://unsplash.com/photos/LBI7cgq3pbM/download", // don't use this property
"download_location": "https://api.unsplash.com/photos/LBI7cgq3pbM/download?ixid=MnwxMTc4ODl8MHwxfHNlYXJjaHwxfHxwdXBweXxlbnwwfHx8fDE2MTc3NTA2MTM" // use this one ;)
}
}
"Be sure to include any query parameters included in the URL (like the ixid)."
So my question is what is value od ixid=MnwxMTc4ODl8MHwxfHNlYXJjaHwxfHxwdXBweXxlbnwwfHx8fDE2MTc3NTA2MTM and how to get it?
Try the following
const ixid = new URLSearchParams(
new URL("https://api.unsplash.com/photos/LBI7cgq3pbM/download?ixid=MnwxMTc4ODl8MHwxfHNlYXJjaHwxfHxwdXBweXxlbnwwfHx8fDE2MTc3NTA2MTM").search
).get("ixid");
console.log(ixid);

Modify Response Object in strapi

I would like to get a modified response object. For example I dont know how to get the user object without the roles.
The default response is:
{
"id": 6,
"username": "username",
"email": "user#email.com",
"provider": "local",
"confirmed": true,
"blocked": false,
"role": {
"id": 2,
"name": "Authenticated",
"description": "Default role given to authenticated user.",
"type": "authenticated"
}
}
Now I want to get the same response without the role attribute.
{
"id": 6,
"username": "username",
"email": "user#email.com",
"provider": "local",
"confirmed": true,
"blocked": false
}
Currently you cannot do this in the Rest API unless you change the UserController provided by permissions plugin, which is not recommended.
What you can do then is to use the GraphQL plugin provided by Strapi, so you can query only the fields you need on client side.
The docs about how to use GraphQL plugin are here.
For anyone still struggling with this problem:
The latest versions of strapi do support custom queries, you can pass an array containing all the names of relations you wish to populate (only relations!).
If you don't want to populate any relationships, you can keep it empty, your controller would then look something like this:
module.exports = {
UserWithoutRoles: ctx => {
return strapi.query('user').findOne({ id: ctx.params.id }, ['']);
}
}
If you do wish to populate it, it would be like this:
module.exports = {
UserWithoutRoles: ctx => {
return strapi.query('user').findOne({ id: ctx.params.id }, ['role']);
}
}
Also see:
[https://strapi.io/documentation/3.0.0-beta.x/concepts/queries.html#api-reference][1]

How to store the JSON value fetch from a URL using JQuery?

I am new to JQuery. I am trying to develop a small travel website for checking PNR. I am currently using an API provided by one of the travel company. As soon as we hit the API Url, browser displays the result in JSON format.
I am using JQuery, JS and HTML. I want to know how to store the JSON value (in string format) retrieved from hitting an API, in a variable and use it later in the script.
PS: Though I have found many answer in Stackoverflow but none of the result works. Kindly help with the appropriate value.
Sample Code: (I am using one textbox and button)
<script>
function search_pnr(){
var pnr = $('#input_pnr').val();
var result;
var url = "http://api website/pnr"+pnr;
//Suggest the code here, to fetch the result from url and store in the variable result.
</script>
<input type="text" placeholder="Enter PNR" id ="input_pnr"/>
<input type="button" value="Search PNR" onclick="search_pnr()"/>
Below is the JSON value getting from server
{"to_station": {"lng": 77.2888291, "name": "ANAND VIHAR TERMINAL", "lat": 28.6118176, "code": "ANVT"}, "total_passengers": 1, "pnr": "6717552286", "journey_class": {"name": null, "code": "3A"}, "train": {"classes": [{"available": "N", "name": "SECOND AC", "code": "2A"}, {"available": "Y", "name": "THIRD AC", "code": "3A"}, {"available": "N", "name": "SECOND SEATING", "code": "2S"}, {"available": "N", "name": "FIRST AC", "code": "1A"}, {"available": "Y", "name": "AC CHAIR CAR", "code": "CC"}, {"available": "N", "name": "FIRST CLASS", "code": "FC"}, {"available": "N", "name": "3rd AC ECONOMY", "code": "3E"}, {"available": "N", "name": "SLEEPER CLASS", "code": "SL"}], "days": [{"code": "MON", "runs": "N"}, {"code": "TUE", "runs": "Y"}, {"code": "WED", "runs": "N"}, {"code": "THU", "runs": "Y"}, {"code": "FRI", "runs": "N"}, {"code": "SAT", "runs": "Y"}, {"code": "SUN", "runs": "N"}], "number": "22405", "name": "BGP-ANVT GARIB RATH"}, "from_station": {"lng": 86.9828131, "name": "BHAGALPUR", "lat": 25.2494829, "code": "BGP"}, "passengers": [{"booking_status": "CNF/G12/36/GN", "no": 1, "current_status": "CNF/-/0/GN"}], "reservation_upto": {"lng": 77.2888291, "name": "ANAND VIHAR TERMINAL", "lat": 28.6118176, "code": "ANVT"}, "response_code": 200, "boarding_point": {"lng": 86.9828131, "name": "BHAGALPUR", "lat": 25.2494829, "code": "BGP"}, "debit": 3, "doj": "25-08-2018", "chart_prepared": false}
Kindly also help how to read both the objects and array in the given JSON.
You can use ajax to fetch the result from the url
var result;
var url = "http://api website/pnr"+pnr;
$.ajax
({
url: url,
type: 'GET',
dataType: 'json',
success: function(data)
{
result = data;
alert(JSON.stringify(data));
}
});
You just need to parse JSON and how to read each object. This should give you good start
$.ajax({
type: "GET",
url: "http://api_website/pnr"+pnr,
data: data,
success: function(resultData) {
console.log(resultData);
var to_station = resultData.to_station;
var trains = resultData.train;
var passengers = resultData.passengers;
alert("Station Name: "to_station.name);
alert("Passengers: "passengers.booking_status);
},
error(function() {
alert("Something went wrong");
}
});
You can read more bout how to read JSON here.
$.ajax({
method: "GET",
url: url
})
.done(function( data ) {
console.log(data)
// see what properties you need from data object and save it to variable
var data = data
});
First thing,
Use a javascript file....API calls are better off done in a js file rather than in a script tag.
Second thing, if you want to store it in a json format,
you can store it in a value like the way you have declared your url variable.
Since, you are fetching the data, I'm assuming this is a get request, you can find more information about them in the following links -
https://www.sitepoint.com/ajaxjquery-getjson-simple-example/
https://api.jquery.com/jquery.get
Also, if the data isn't very sensitive, you can store it in the local storage of your browser, so that you can access it later on in other web pages as well.
In your current json data, I would say that if you declare it to a variable say
apiResult
Your to_station would be apiResult.to_station, the lng value would be apiResult.to_station.lng and so on.
Hope any of this helps, and good luck.
Everyone already added the AJAX examples, so I will leave that out.
So for reading the objects, you just have to parse what you need through various means, if you know what the object looks like and exactly what you need you can use dot notation. If you are looking to grab things more dynamically you can using higher order functions or for loops as well as Object prototypes example getting the entries (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries)
You might consider using localStorage for storing the information depending on what you are using it for which is a built-in Web API
here is MDN's definition
The read-only localStorage property allows you to access a Storage
object for the Document's origin; the stored data is saved across
browser sessions. localStorage is similar to sessionStorage, except
that while data stored in localStorage has no expiration time, data
stored in sessionStorage gets cleared when the page session ends —
that is, when the page is closed.
https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage
You may want to use AJAX. You have to be sure how the server will retrieve the data. If it is in a JSON format do:
<script>
function search_pnr(){
var pnr = $('#input_pnr').val();
var result;
var url = "http://api website/pnr"+pnr;
$.getJSON( url, function( data ) {
result = data;
$.each( data, function( key, value ) {
// whatever with keys and values if needed
}
);
}
</script>
Ref w3 Schools
JQuery official website
All current browsers have native JSON support built in. So as long as you're not dealing with prehistoric browsers like IE6/7 you can do it just as easily as that:
var j={"name":"binchen"};
JSON.stringify(j); // '{"name":"binchen"}'
For more info kindly visit link

How to get a list of document's fields from couchDB using node/cradle?

First of all, i want to let you know that i am a novice with node and couchDB and i have this project where i need to add some functionality to the existing application.
So, i have javascript/node/express web application and i want to get a specific document from a remote couchDB, using cradle, and then get a list of its fields and their values. Later on i would need to display those fields/values in some html.
I don't know which fields the document has because they are dynamically added/removed by a third party.
I was able to get the document i wanted, but i don't know how to iterate through its fields. What would be the best way to do that?
Here is a simpificated sample of the document:
{
"_id": "1.1.5",
"_rev": "5-56ebac233e7f56a14a4534c6902727f7",
"1.1.5.39": {
"Project": {
"Project1": {
"files": "...",
"status": "NEW",
"id": 2
},
"Project2": {
"files": "...",
"status": "ASSIGNED",
"id": 3
}
}
}
"1.1.5.23": {
"Project": {
"Project3": {
"files": "...",
"status": "NEW",
"id": 4
},
"Project4": {
"files": "...",
"status": "NEW",
"id": 5
}
}
}
}
I would need to get the fields '1.1.5.39' and '1.1.5.23', and also the 'status' values. These fields represent some versions of a software. The problem is also fields' format: numbers and dots, so i can't just use 'Object.attribute' notation...
First part is getting the document via cradle:
// get the Connection
var connection = new(cradle.Connection)('http://living-room.couch', 5984, {
cache: true,
raw: false
});
// get the DB
var db = connection.db('yourDB');
// get the document
var docID = "1.1.5";
db.get('docID', function (err, doc) {
displayDoc(doc);
});
function displayDoc(doc) {
// Do your display handling here
}
The second part what you need is displaying arbitrary objects. Here I refer you to my answer to this question.
Good Luck.

Json returns every character as a separate object?

I have a json object that I'm loading from wordpress using the JSON API plugin. When I load the json object and try to log out the parts of it, it seems like it treats every single character as its own object so the loop returns me a couple thousand objects all with item in it which is a single character. This is my first time using json so idk if i'm missing a step here. this is the code I'm using so far.
function getProjInfo(theId){
$.ajax({// calling the ajax object of jquery
type: "GET",// we are going to be getting info from this data source
url: 'http://testing.charter21.com/api/get_post/?post_id='+ theId,//the datasource
dataType: "application/json",
success: function(data){
parseJson(data);
}, // what happens when it is successful at loading the XML
error: function(){
alert("error");
}
});
}//end of the function
function parseJson(inData){
postInfo = inData;
$.each(postInfo, function(index, value){
console.log(this);
});
}
the json looks like this:
{
"status": "ok",
"count": 10,
"count_total": 19,
"pages": 2,
"posts": [
{
"id": 175,
"type": "post",
"slug": "home-page-slider",
"url": "http:\/\/testing.charter21.com\/uncategorized\/home-page-slider\/",
"status": "publish",
"title": "Home Page slider",
"title_plain": "Home Page slider",
"content": "<p>The cImages in here are the images that are in the slider on the home page this content in this box will not show up. Its only here as a guide.<\/p>\n",
"excerpt": "The cImages in here are the images that are in the slider on the home page this content in this box will not show up. Its only here as a guide.",
"date": "2011-01-25 10:40:25",
"modified": "2011-01-25 10:40:25",
"categories": [],
"tags": [],
"author": {
"id": 1,
"slug": "admin",
"name": "admin",
"first_name": "",
"last_name": "",
"nickname": "admin",
"url": "",
"description": ""
},
"comments": [],
"attachments": [],
"comment_count": 0,
"comment_status": "open"
}
so basically instead of giving me "status" as an key and "ok" as a value, i get "s" as an object with an index 0 that has a value of "s" for every single character in the json object. Any help on this matter would be appreciated.
You need to set dataType:json in your $.ajax() request so that jQuery converts the JSON-formatted string into a JavaScript object for you to process as such. You're currently using application/json which is a mime type, and not a valid value for this field in a jQuery request.
In your case you can even try data = eval(data) , this javascript statement should convert your string to json object.
Use the Jquery function:
data = $.parseJSON(data);
before using $.each.
The way I solved it in my AngularJS app is by sending the response from the server (I'm using Node Express) as a JavaScript object, rather than as a string. Nothing else worked for me.
var response = {};
response.error = "Error message";
res.send(response);

Categories

Resources