I want to develop an app for Pebble. This app is going to tell you how long it takes from one place you set in options to another one taking in account traffic jams and stuff.
To achieve this I need to make a page that will return JSON. Pebble retrieves information using code like that:
var cityName = 'London';
var URL = 'http://api.openweathermap.org/data/2.5/weather?q=' + cityName;
ajax(
{
url: URL,
type: 'json'
},
function(data) {
// Success!
console.log('Successfully fetched weather data!');
},
function(error) {
// Failure!
console.log('Failed fetching weather data: ' + error);
}
);
I created a small page with a js script that gets needed information from Yandex API:
var route;
ymaps.ready(init);
var myMap;
function init(){
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
var time = 0;
var home = getParameterByName("h");
var work = getParameterByName("w");
ymaps.route([home, work],{avoidTrafficJams: true}).then(
function (router) {
route=router;
time = ((route.getTime())/60).toFixed(2);
var info = new Object;
info["home"] = home;
info["work"] = work;
info["time"] = ~~time+"m"+~~((time%1)*60)+"s";
JSON.stringify(info);
},
function (error) {
alert('Возникла ошибка: ' + error.message);
}
);
}
As you can see I can get a JSON string in the end. But how do I send it to clients when a request with right parameters is made?
I ended up using phantomjs and executing this js script on my php page.
Related
I've got a problem with JSON in JavaScipt. I've got 2 different JSON URL. One of them contains data about users and the second one about posts. And in posts JSON I've got a field userId.
I want to find a way to connect them somehow. I need to get users and their posts and then count how many posts every user wrote.
var postRequest = new XMLHttpRequest();
postRequest.open('GET', 'https://jsonplaceholder.typicode.com/posts');
postRequest.onload = function() {
var posts = JSON.parse(postRequest.responseText);
var userRequest = new XMLHttpRequest();
userRequest.open('GET', 'https://jsonplaceholder.typicode.com/users');
userRequest.onload = function (){
var users = JSON.parse(userRequest.responseText);
for(k in users){
document.write("</br></br>"+ users[k].name +", " + users[k].username + ", " + users[k].email + "</br>" + "-------------------------------------------------------------------------------------" + "</br>");
for(k1 in posts){
if(posts[k1].userId===users[k].id){
document.write(posts[k1].body + "</br>");
}
}
}
};
userRequest.send();
};
postRequest.send();
but I think it doesn't look good. I want to get data from JSON to variable to use them later, in function for example.
Anyone help? I've never connected data from 2 JSON files and want to do it in a good way and getting good practice.
Use this instead
for(k in users){
for(k1 in posts){
if(posts[k1].userId===users[k].id){
if(!users[k].hasOwnProperty('posts')) {
users[k].posts = [];
}
users[k].posts.push(posts[k1].body);
}
}
}
if you could you jquery
$.when($.ajax({
url: "https://jsonplaceholder.typicode.com/users"
})).then(function(data, textStatus, jqXHR) {
$.each(data, function(index, value) {
$.ajax({
url: "https://jsonplaceholder.typicode.com/posts?userId=" + value.id
}).then(function(data, textStatus, jqXHR) {
console.log("UserID:" + data[0].userId + " Nos Posts:" + data.length);
});
});
});
You can try above code and let me know if it solve your purpose
Steps you can use :
1. You can add a body property in to the objects in users array as per the id and userid match.
2. Later you can iterate the users array whenever you want to use.
DEMO
var postRequest = new XMLHttpRequest();
postRequest.open('GET', 'https://jsonplaceholder.typicode.com/posts');
postRequest.onload = function() {
var posts = JSON.parse(postRequest.responseText);
var userRequest = new XMLHttpRequest();
userRequest.open('GET', 'https://jsonplaceholder.typicode.com/users');
userRequest.onload = function (){
var users = JSON.parse(userRequest.responseText);
for(k in users) {
for(k1 in posts) {
if(posts[k1].userId===users[k].id){
users[k].body = posts[k1].body;
}
}
}
console.log("users", users);
};
userRequest.send();
};
postRequest.send();
I am trying to create a Google Classroom course using the Google Classroom API and a service account. I am currently experimenting using JavaScript and I have everything set up and working to get a list of course. I set up a JWT and request an authentication token which I receive.
{"access_token":"----ACCESS TOKEN HERE----------","token_type":"Bearer","expires_in":3600}
When I use this to retrieve a user's course list (via GET) there is no problem. I receive back a proper response with a list of courses which I then display in a table.
When I try to use the same process to try to create a course (via POST), I get a 401 error:
{
"error": {
"code": 401,
"message": "The request does not have valid authentication credentials.",
"status": "UNAUTHENTICATED"
}
}
This is the code I use to authenticate:
function authenticate(callback) {
function b64EncodeUnicode(str) {
str = JSON.stringify(str);
return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, function(match, p1) {
return String.fromCharCode('0x' + p1);
}));
}
// constuct the JWT
var jwtHeader = {
"alg":"RS256",
"typ":"JWT"
}
jwtHeader = JSON.stringify(jwtHeader);
//construct the Claim
var jwtClaim = {
"iss":"psclassroomsync#psclassroomsync.iam.gserviceaccount.com",
"scope":"https://www.googleapis.com/auth/classroom.courses https://www.googleapis.com/auth/classroom.rosters",
"sub":"myemail#address.com", //this is an admin account I shouldn't really need this but tried with and without it
"aud":"https://www.googleapis.com/oauth2/v4/token",
"exp":(Math.round(new Date().getTime()/1000) + 60 * 10),
"iat":Math.round(new Date().getTime()/1000)
}
jwtClaim = JSON.stringify(jwtClaim);
//construct the signature
var key="-----BEGIN PRIVATE KEY-----Removed-----END PRIVATE KEY-----\n";
var jwtSign = b64EncodeUnicode(jwtSign);
var sJWT = KJUR.jws.JWS.sign("RS256", jwtHeader, jwtClaim, key);
var jwt = jwtHeader + "." + jwtClaim + "." + sJWT;
//request Token
var grantType = "urn:ietf:params:oauth:grant-type:jwt-bearer";
var tokenRequest = "grant_type=" + grantType + "&assertion=" + sJWT;
var postURL = "https://www.googleapis.com/oauth2/v4/token"
request = $j.ajax({
url: postURL,
type: "post",
data: tokenRequest,
success: callback
});
}
This is the code I use to GET the course list. (this works)
$j("#getClasses").click(function(event){
function getClasses(callback){
authenticate(function(data){
console.log(JSON.stringify(data));
var access_token = data["access_token"];
var apiUrl = 'https://classroom.googleapis.com/v1/courses'
var myData = 'teacherId=~(teacheremail)&access_token='+access_token;
var files = $j.ajax({
url: apiUrl,
type: "get",
data: myData,
success: function (data) {
var retreivedClasses = JSON.stringify(data);
for(var i = 0; i < data['courses'].length; i++){
nextObject = data['courses'];
$j('#classListTable').append('<tr><td>' + nextObject[i]['name'] + '</td><td>' + nextObject[i]['courseState'] + '</td><td>' + nextObject[i]['enrollmentCode'] + '</td></tr>');
}
//$j('#classList').text(retreivedClasses);
}
});
});
}
getClasses();
});
This is the code that I use to create a course via POST. I've hard coded a few of the variables for testing but still gives the 401 error.
$j("#createClass").click(function(event){
function createClass(callback){
authenticate(function(data){
console.log(JSON.stringify(data));
var access_token = data["access_token"];
var tokenInfo = $j.ajax({
url: 'https://www.googleapis.com/oauth2/v3/tokeninfo',
type: 'get',
data: "access_token="+access_token
});
var apiUrl = 'https://classroom.googleapis.com/v1/courses'
var myData = 'access_token='+access_token + '&ownerId=myemail#address.com&name=myClass'
console.log(myData);
var newGoogleClassroom = $j.ajax({
url: apiUrl,
type: "post",
data: myData,
success: function (data) {
var apiResponse = JSON.stringify(data);
$j('#classCreated').text(apiResponse);
}
});
});
};
createClass();
});
Finally, this is what I get when I get the token info. It looks fine to me i.e. proper scopes: (but I am new at this)
{
"azp": "removed",
"aud": "removed",
"scope": "https://www.googleapis.com/auth/classroom.courses https://www.googleapis.com/auth/classroom
.rosters",
"exp": "1474512198",
"expires_in": "3600",
"access_type": "offline"
}
I'd be grateful for any help.
Doug
P.S. I get the security implications of this code. It is in a secure environment for experimentation only. It won't see the light of day.
Based from this forum which is also receiving a 401 error, try to revoke the old oauth. As stated in this related thread, the 401 Unauthorized error you experienced may be related to OAuth 2.0 Authorization using the OAuth 2.0 client ID.
Suggested action: Refresh the access token using the long-lived refresh token. If this fails, direct through the OAuth flow.
I want to send json data through url to next html page. I checked it by emulator as I am working for mobile app, the url could not redirect to next page it is crashing at the moment what is the reason behind this. How can I parse it on next page .I am new to the jquery any idea? my json data contains result of two different sql queries in an array
$.ajax({
type : "POST",
datatype : "json",
url : "http://Localhost/phpBB3/check_pass.php?username="+ username + "&password="+ password+"&f=68",
success: function(data){
alert(data);
window.location.href="source/testmenu.html?varid=" + data +"&username=" + username +"&password=" + password;
}
});
This is the code on next page
$(document).ready(function GetUrlValue(VarSearch){
var SearchString = window.location.search.substring(1);
var arr = SearchString.split('&');
console.log(arr);
//Set session variables
var username = arr[1].split('=')[1];
var password = arr[2].split('=')[1];
document.getElementById('username').value = username;
document.getElementById('password').value = password;
)};
in your case in first page urlencode json
window.location.href="source/testmenu.html?varid=" + encodeURIComponent(data) +"&username=" + username +"&password=" + password;
and in next page
var data= arr[0].split('=')[1];
var recieved_json = $.parseJSON(data);
Then try this one:
var data = {
username: username,
password: password
};
$.ajax({
type: "POST",
url: "http://Localhost/phpBB3/check_pass.php",
params: $.param(data),
success: function(a) {
window.location.href = "source/testmenu.html?"
+ $.param(a) + "&" + $.param(data)
}
});
And this would be your code for the next page (the iterator is from Satpal's answer):
$(document).ready(function() {
var params = window.location.search;
var getURLParams = function(params) {
var hash;
var json = {};
var hashes = url.slice(url.indexOf('?') + 1).split('&');
for (var i = 0; i < hashes.length; i++) {
hash = hashes[i].split('=');
json[hash[0]] = hash[1];
}
return json;
}
params = getURLParams(params);
var username = params.username;
var password = params.password;
$('#username').val(username);
$('#password').val(password);
});
Though I agree with #Jai that sending username and password in url is not recommended.
Once you get the URL to load you'll need to run your data through some encoding and decoding. You might have the wrong path. If you want "http://Localhost/source/testmenu.html" make sure the first character is a "/".
Make sure your data object is encoded correctly.
// Encode data for querystring value.
var data = {
foo: "bar"
};
var data_str = JSON.stringify(data);
data_str = encodeURIComponent(data_str);
Decode and test your URL.
// Get data from querystring value.
// Get the query as an object with decoded values.
// Note that JSON values still need parsing.
function getQuery() {
var s=window.location.search;
var reg = /([^?&=]*)=([^&]*)/g;
var q = {};
var i = null;
while(i=reg.exec(s)) {
q[i[1]] = decodeURIComponent(i[2]);
}
return q;
}
var q = getQuery();
try {
var data = JSON.parse(q.data);
} catch (err) {
alert(err + "\nJSON=" + q.data);
}
Parameter should be html encode while navigating or requesting to the URL and decode at the receiving end. It may suspect potentially dangerous content which may leads to crash.
I'm looking for some tips on how I can create a discussion reply using the 2013 Sharepoint REST end point. I'm not using the built in SP javascript libraries, instead accessing the REST end point directly using jQuery ajax calls.
My issue when attempting to create a reply is that it is creating the article as a new thread instead of a reply. I've searched around the web and all I can come up with is something to do with the URL path.
If I use the "sharepointEndPoint/_api/web/lists/getByTitle('discussions')/Items" url, it will create article as a new thread.
I've tried appending the ID of the parent thread on the end of items in brackets "(1)" for example and also "/title of parent thread" but both throw an error.
I'm also setting the ParentItemID and the ParentFolderId against the article, but sharepoint still creates it as a new thread instead of a reply.
ParentItemID property could not be specified via message payload since it is a read only property, it means the following query for creating a message item fails:
Url /_api/web/lists/getbytitle('Discussions')/items
Method POST
Data {
'__metadata': { "type": "SP.Data.DiscussionsListItem" },
'Body': "Message text goes here",
'FileSystemObjectType': 0,
'ContentTypeId': '<MessageContentTypeId>',
'ParentItemID': <DiscussionItemId> //can't be set since it is read only
}
Solution
For creating a message under a discussion item (folder) you could consider following solution: once message item is created, it's getting moved under a discussion item (folder container)
Example
The following example demonstrates how to create a message (reply) in Discussion Board via SharePoint REST API:
var listTitle = "Discussions"; //Discussions Board title
var webUrl = _spPageContextInfo.webAbsoluteUrl;
var messagePayload = {
'__metadata': { "type": "SP.Data.DiscussionsListItem" }, //set DiscussionBoard entity type name
'Body': "Message text goes here", //message Body
'FileSystemObjectType': 0, //set to 0 to make sure Message Item is created
'ContentTypeId': '0x0107008822E9328717EB48B3B665EE2266388E', //set Message content type
'ParentItemID': 123 //set Discussion item (topic) Id
};
createNewDiscussionReply(webUrl,listTitle,messagePayload)
.done(function(item)
{
console.log('Message(reply) has been sent');
})
.fail(function(error){
console.log(JSON.stringify(error));
});
where
function executeJson(options)
{
var headers = options.headers || {};
var method = options.method || "GET";
headers["Accept"] = "application/json;odata=verbose";
if(options.method == "POST") {
headers["X-RequestDigest"] = $("#__REQUESTDIGEST").val();
}
var ajaxOptions =
{
url: options.url,
type: method,
contentType: "application/json;odata=verbose",
headers: headers
};
if("data" in options) {
ajaxOptions.data = JSON.stringify(options.data);
}
return $.ajax(ajaxOptions);
}
function createListItem(webUrl,listTitle,payload){
var url = webUrl + "/_api/web/lists/getbytitle('" + listTitle + "')/items";
return executeJson({
"url" :url,
"method": 'POST',
"data": payload
});
}
function moveListItem(webUrl,listTitle,itemId,folderUrl){
var url = webUrl + "/_api/web/lists/getbytitle('" + listTitle + "')/getItemById(" + itemId + ")?$select=FileDirRef,FileRef";
return executeJson({
"url" :url
})
.then(function(result){
var fileUrl = result.d.FileRef;
var fileDirRef = result.d.FileDirRef;
var moveFileUrl = fileUrl.replace(fileDirRef,folderUrl);
var url = webUrl + "/_api/web/getfilebyserverrelativeurl('" + fileUrl + "')/moveto(newurl='" + moveFileUrl + "',flags=1)";
return executeJson({
"url" :url,
"method": 'POST'
});
});
}
function getParentTopic(webUrl,listTitle,itemId){
var url = webUrl + "/_api/web/lists/getbytitle('" + listTitle + "')/getItemById(" + itemId + ")/Folder";
return executeJson({
"url" :url,
});
}
function createNewDiscussionReply(webUrl,listTitle, messagePayload){
var topicUrl = null;
return getParentTopic(webUrl,listTitle,messagePayload.ParentItemID)
.then(function(result){
topicUrl = result.d.ServerRelativeUrl;
return createListItem(webUrl,listTitle,messagePayload);
})
.then(function(result){
var itemId = result.d.Id;
return moveListItem(webUrl,listTitle,itemId,topicUrl);
});
}
I am trying to get the hereNow parameter from FourSquare using a checkins query on a specific user, unfrotunately I can't seem to get that parameter using checkins, I am seeing all other data regarding a venue except for the hereNow parameter.
Does anyone know how I can get that parameter using checkins? Otherwise, how can I incorporate venue objects and tie into my current code?
Here is my JavaScript to set hereNow as a variable:
var count;
getVenueStatus = function() {
var hereNowUrl = 'https://api.foursquare.com/v2/venues/VENUE_ID?&oauth_token=OAUTH_TOKEN&v=20140303';
$.getJSON(hereNowUrl, {format: "json"}, function(data) {
$(data.response.venue).each(function(index) {
$(this).each(function(index) {
var venue = this;
var hereNowCount = venue.hereNow.count;
count = hereNowCount;
console.log(count);
});
});
});
}
Here is my JavaScript to display the results on a map:
findFoodTrucks = function (param) {
getVenueStatus();
$.mobile.pageLoading();
var url = 'https://api.foursquare.com/v2/users/80507329/checkins?oauth_token=OAUTH_TOKEN&v=20140303';
var mapBounds = new google.maps.LatLngBounds();
if (param.userloc) mapBounds.extend(param.userloc);
$.getJSON(url, function(data) {
$(data.response.checkins).each(function(index) { // groups: nearby, trending
$(this.items).each(function(index) {
var foodtruck = this;
var foodtruckPosition = new google.maps.LatLng(foodtruck.venue.location.lat, foodtruck.venue.location.lng);
var foodtruckIcon = (count > 0) ? 'foodtruck_active.png' : 'foodtruck_inactive.png';
var foodtruckStreet = (foodtruck.venue.location.address) ? '<br>' + foodtruck.venue.location.address : '';
var foodtruckContent = '<strong>' + foodtruck.venue.name + '</strong>' + foodtruckStreet + '<br>';
mapBounds.extend(foodtruckPosition);
addFoodTruckMarker(foodtruckPosition, foodtruckIcon, foodtruckContent);
console.log(foodtruck);
});
if (param.zoomtotrucks) $('#map_canvas').gmap('getMap').fitBounds(mapBounds);
});
})
.error( function() {
loadFoodTrucks(param); //try again
})
.complete( function() {
$.mobile.pageLoading( true );
});
}
Thanks in advance!
The check-in response includes a compact venue, which is only sometimes guaranteed to have a hereNow field. To get the hereNow count, it's probably best to make a second venue detail API call.
PS: also noticed that you seemed to be passing an OAuth token and client ID/secret—in this case, you only need the OAuth token! Take a look at https://developer.foursquare.com/overview/auth for more info.