Yelp Fusion API JSON Review Parsing - html

I want to display reviews on a webpage but have trouble with JSON parsing and formatting. Any help is greatly appreciated. I can handle the HTML and CSS markup, I just need to loop through each new review and get the reviewer, reviewtext, pictureurl, etc.
So far, it's only able to get the amount of reviews. I'm new to JSON and am having trouble parsing the reviews and getting the format right.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css" integrity="sha384-Smlep5jCw/wG7hdkwQ/Z5nLIefveQRIY9nfy6xoR1uRYBtpZgI6339F5dgvm/e9B" crossorigin="anonymous">
<title>Ilan's Test</title>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-lg-12">
<div id="results">
</div>
</div>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/js/bootstrap.min.js" integrity="sha384-o+RDsa0aLu++PJvFqy8fFScvbHFLtbvScb8AjopnFD+iEQ7wo/CG0xlczd+2O/em" crossorigin="anonymous"></script>
<script>
var myurl = "https://cors-anywhere.herokuapp.com/https://api.yelp.com/v3/businesses/financial-sanity-now-los-angeles-2/reviews";
$.ajax({
url: myurl,
headers: {
'Authorization':'Bearer API-KEY-GOES-HERE',
},
method: 'GET',
dataType: 'json',
success: function(data){
// Grab the results from the API JSON return
var totalresults = data.total;
// If our results are greater than 0, continue
if (totalresults > 0){
// Display a header on the page with the number of results
$('#results').append('<h5>We discovered ' + totalresults + ' reviews!</h5>');
// Itirate through the JSON array of 'reviews' which was returned by the API
$.each(data.reviews[id], function(id, review) {
// Store each review object in a variable
var id = review.id;
var reviewtext = reviews[id].text;
var reviewrating = reviews[id].rating;
// Append our result into our page
$('$results').append(reviewtext + reviewrating + reviews);
});
} else {
// If our results are 0; no reviews were returned by the JSON so we display on the page no results were found
$('#results').append('<h5>We discovered no results!</h5>');
}
}
});
</script>
</body>
</html>

Minor mistakes with the code, but it's fine; your each function was a bit messy and you accidentally used $results as a reference which should've been #results; but it's all good your getting it!
Check out the code below (note Yelp only allows 3 reviews to be fetched; so when you see 8 total; it won't fetch more than 3);
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css" integrity="sha384-Smlep5jCw/wG7hdkwQ/Z5nLIefveQRIY9nfy6xoR1uRYBtpZgI6339F5dgvm/e9B" crossorigin="anonymous">
<title>Ilan's Test</title>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-lg-12">
<div id="results">
</div>
</div>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/js/bootstrap.min.js" integrity="sha384-o+RDsa0aLu++PJvFqy8fFScvbHFLtbvScb8AjopnFD+iEQ7wo/CG0xlczd+2O/em" crossorigin="anonymous"></script>
<script>
var myurl = "https://cors-anywhere.herokuapp.com/https://api.yelp.com/v3/businesses/financial-sanity-now-los-angeles-2/reviews";
$.ajax({
url: myurl,
headers: {
'Authorization':'Bearer API-KEY-GOES-HERE',
},
method: 'GET',
dataType: 'json',
success: function(data){
// Grab the results from the API JSON return
var totalresults = data.total;
// If our results are greater than 0, continue
if (totalresults > 0){ console.log(data);
// Display a header on the page with the number of results
$('#results').append('<h5>We discovered ' + totalresults + ' reviews!</h5>');
// Itirate through the JSON array of 'reviews' which was returned by the API
$.each(data.reviews, function(i, item) {
// Store each review object in a variable
var author = item.user.name;
var reviewtext = item.text;
var reviewrating = item.rating;
// Append our result into our page
$('#results').append('Author: <b>' + author + '</b><br> Review: ' + reviewtext + '<br>Rating: ' + reviewrating + ' <hr>');
});
} else {
// If our results are 0; no reviews were returned by the JSON so we display on the page no results were found
$('#results').append('<h5>We discovered no results!</h5>');
}
}
});
</script>
</body>
</html>

Related

Display ajax in html page

I'm using flask as a backend, and one of my endpoints is objectList, which returns data in this format:
[{name1:value1, name2:value2}, {name1:value3, name2:value4}]
In order to display this data on my html page, I'm using the following code:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function){
$.ajax({
url: 'localhost:5000/objectList',
method:"GET",
success: function(result){
$("#div1").html(result);
};
});
};
</script>
</head>
<body>
<div id="div1"></div>
</body>
</html>
This doesn't display any data. What am I doing wrong and how can I fix this?
Edit: just a clarification, I want the data to load when the page loads, not on a button or a click
After our discussion, I find this code works properly
You have to close the parenthesis in the function ajax, and allow the access-control in the server side with this line
header("Access-Control-Allow-Origin: *");
// or replace the star with the server where you have the html
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$.ajax({
url: 'localhost:5000/objectList',
method:"GET",
success: function(result){
// to verifiy the result
console.log(result);
var htmlOutput = '';
// the iteration of your result because you have many entries
$.each(result, function(i, item) {
htmlOutput += ''+
'<ul>'+
'<li>name1: '+item['name1']+'</li>'+
'<li>name2: '+item['name2']+'</li>'+
'</ul>';
});
$("#div1").html(htmlOutput);
}, error: function(jqXHR, textStatus, error) {
// to verifiy either there is an error or not
console.error(textStatus);
}
});
});
</script>
</head>
<body>
<div id="div1"></div>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$.getJSON("demo_ajax_json.js", function(result){
$.each(result, function(i, field){
$("div").append(field + " ");
});
});
});
});
</script>
</head>
<body>
<button>Get JSON data</button>
<div></div>
</body>
</html>

how we can develop the location auto detect Using html 5?

I am developing one webproject and in that project i have requirement that
there will be one button there named by auto detect and when ever any one
click on that button visitor will get his location popup in this near textbox,i have created it and seen result in console.
autodetect.html:44 {error_message: "This API project is not authorized to use >this API.", results: Array(0), status: "REQUEST_DENIED"}
Following is the code for it:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Auto detect location</title>
</head>
<body>
<button onClick="getLocation()">Get Location</button>
<!--output will display here-->
<div id="output" style="margin-top: 20px;"></div>
<div id="output1" style="margin-top: 20px;"></div>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script>
var x = document.getElementById('output');
var y = document.getElementById('output1');
x.innerHTML = "Here is output";
function getLocation() {
//alert('hi getLocation working');
if (navigator.geolocation) {
// x.innerHTML = "Supporting..";
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Sorry your browser not supporting autodetect location.";
}
}
function showPosition(position) {
// x.innerHTML = position.coords.latitude;
// y.innerHTML = position.coords.longitude;
var locAPI = "https://maps.googleapis.com/maps/api/geocode/json?key=AIzaSyCY2xZxxjq0U6iVzYJetKi9uJZnmIrnPGs&latlng=" + position.coords.latitude + "," + position.coords.longitude + "&sensor=true";
// x.innerHTML = locAPI;
$.get({
url: locAPI,
success: function(data) {
console.log(data);
}
});
}
</script>
</body>
</html>
how we can get code corrected so that we will det displayed this location of the visitos ?
From the error message, it looks like you don't have a project with the api enabled, maybe this could help.Also you shouldn't share your api key publicly.

Parse and upload a csv file in D3.js V5

Murray (2017) suggests the following code for loading a csv file and parsing columns usign D3.js V4. This code no longer works in V5. How can it be restructured in order to work? Thanks
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>D3: Line chart</title>
<script type="text/javascript" src="/../../d3.js"></script>
<style type="text/css">
</style>
</head>
<body>
<script type="text/javascript">
var dataset;
//Function for converting CSV values from strings to Dates and numbers
var rowConverter = function(d) {
return {
date: new Date(+d.year, (+d.month - 1)), //Make a new Date object for each year + month
average: parseFloat(d.average) //Convert from string to float
};
}
//Load in data
d3.csv("mauna_loa_co2_monthly_averages.csv", rowConverter, function(data) {
var dataset = data;
//Print data to console as table, for verification
console.table(dataset, ["date", "average"]);
}
For v5, d3-fetch is your friend as d3-request has been deprecated.
For instance:
d3.csv("/path/to/file.csv", rowConverter).then(function(data){ do whatever })

Adding same button to each item on list?

I have a task list where I want to add the "hide button" to each item on the list. I have one and every time you click it, it hides the entire list. I want to be able to have a button for each item and only hide that certain item once clicked. I have the fiddle here: https://jsfiddle.net/9cp9twfh/
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" type="text/css" href="asana.css">
<link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<title>Asana</title>
</head>
<body>
<div class="topnav" id="myTopnav">
</div>
<button class="button">Hide Task</button>
<div class="task-list"></div>
<script src="asana.js"></script>
</body>
</html>
$(document).ready(function(){
$.ajax({
method: 'GET',
url: 'https://app.asana.com/api/1.0/projects/507623085822462/tasks',
headers: {
'Authorization': 'Bearer 0/0c60e78596a717c771c04c1c35b0a451'
},
success: function(result) {
$('.card').find('.taskname').html(result.data.name);
showTaskList(result.data);
}
});
});
$(document).ready(function() {
$('button').click(function() {
$('.task-list').stop(true).toggle('slow');
$('.button').text(function(i, t) {
return t == 'Show Task' ? 'Hide Task' : 'Show Task';
});
});
});
var showTaskList = function(taskList) {
for(var i = 0; i < taskList.length; i++) {
showTask(taskList[i]);
}
};
var showTask = function(taskData){
var taskList = $('.task-list');
var card = $('<div></div>').addClass('card');
var taskName = $('<div></div>').addClass('taskname');
taskName.html(taskData.name);
card.append(taskName);
taskList.append(card);
};
var showTask = function(taskData){
...
card.append(taskName);
card.append("<button class='hide' type='button'>Hide</button>");
taskList.append(card);
}
$(".task-list").on("click", "button.hide", function(){
$(this).closest(".card").hide();
});

google api- google sign in for website, cannot access the basic profile

I want to get the users' profile, like user id and email address, i have tried many ways to do it, but still get the error of "TypeError: googleUser.getBasicProfile is not a function"
I follow the instruction of google document, but i still get the error:
and here is all code of it:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>googleSignin</title>
<meta name="google-signin-requestvisibleactions" content="https://schema.org/AddAction" />
<meta name="google-signin-scope" content="https://www.googleapis.com/auth/plus.login" />
<meta name="google-signin-client_id" content="589020135825-sbg93psr9i0v8gq6ajm7mv9et38o9ts2.apps.googleusercontent.com">
</head>
<body>
<div class="g-signin2" data-onsuccess="onSignIn" data-theme="dark" onclick="onSignIn('googleUser')"></div>
<script>'
function onSignIn(googleUser) {
// Useful data for your client-side scripts:
var profile = googleUser.getBasicProfile();
var user_name = profile.getName();
alter(user_name);
console.log("ID: " + profile.getId());
console.log('Full Name: ' + profile.getName());
console.log('Given Name: ' + profile.getGivenName());
console.log('Family Name: ' + profile.getFamilyName());
console.log("Image URL: " + profile.getImageUrl());
console.log("Email: " + profile.getEmail());
//The ID token you need to pass to your backend:
//var id_token = googleUser.getAuthResponse().id_token;
//console.log("ID Token: " + id_token);
}
function signOut(){
var auth2 = gapi.auth2.getAuthInstance();
auth2.signOut().then(function() {
console.log('User signed out!');
});
}
function onLoad() {
gapi.load('auth2', function() {
var auth2 = gapi.auth2.init();
auth2.then(function(){
//current values
var isSignedIn = auth2.isSignedIn.get();
var currentUser = auth2.currentUser.get();
if (!isSignedIn) {
//rendering it
gapi.signin2.render('google-signin-button', {
'onsuccess': 'onSignIn'
});
}
});
});
}
</script>
Sign out
<script src="https://apis.google.com/js/platform.js" async defer></script>
</body>
</html>
Comparing your code to the example you don't need the onclick handler in your button div. The parementer you pass via that is a string giving the error. Let platform.js sort out the calling
You might want to add asunc defer to you script as well
see https://developers.google.com/identity/sign-in/web/