Hello I am new to APIs and I am struggling a lot with the Flickr API. I tried looking up videos and articles and it was overwhelming. What I am trying to do for my project is have a user search up restaurants using the Yelp API. Once they get a list of restaurants, each list item will have a select button. When the user clicks the select button, images of that location should pop up in a div on the HTML page. I manage to get the Yelp API to work however I am struggling with how to make the images load when the user clicks the select button. I am completely lost and any help would be appreciated. Below is my code.
HTML:
<div class="col-xs-6">
<h2 id="title">Manhattan</h2>
<div>
<h2>Photos</h2>
<div id="photos"></div>
</div>
</div>
JavaScript:
$(document).ready(function () {
$('#getposts_form').submit(function(event) {
event.preventDefault();
$('#output').empty();
var search = $('#search').val();
var title = $('#title').text();
var categories = $('#categories').val();
var price = $("#price").val();
console.log(search);
console.log(categories);
console.log(price);
$("#ajaxIndicator").modal('show');
// make the ajax request
$.ajax({
url: 'yelp.php',
type: 'GET',
dataType: 'JSON',
data: {
location: title,
categories: categories,
price: price
},
success: function(serverResponse) {
console.log(serverResponse);
var businesses = serverResponse.businesses;
console.log(businesses);
var myHTML = '';
for(var i = 0; i < serverResponse.businesses.length; i++){
myHTML += '<li class="tweet list-group-item">';
myHTML += '<ul class="list">'
myHTML += '<li><span class="user"><b>' + serverResponse.businesses[i].name + '</b></span></li>';
myHTML += '<li><span class="user">' + serverResponse.businesses[i].price + '</span></li>';
myHTML += '<li><span class="user">' + serverResponse.businesses[i].latitude + '</span></li>';
myHTML += '<li><span class="user">' + JSON.stringify(serverResponse.businesses[i].categories) + '</span></li>';
myHTML += '<li><span class="user"><button class="btn btn-default" type="submit" id="select">Select</button></span><li>';
myHTML += '</ul>'
myHTML += '</li>';
}
$('#output').append(myHTML);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log('error');
console.log(errorThrown);
console.log(jqXHR);
},
complete: function() {
$("#ajaxIndicator").modal('hide');
}
});
});
//ajax call for flickr api
$('.select').submit(function(event) {
event.preventDefault();
$('#photos').empty();
var lat = $('#lat').val();
var long = $('#long').val();
$("#ajaxIndicator").modal('show');
make the ajax request
$.ajax({
url: 'http://api.flickr.com/services/rest/?method=flickr.photos.search&api_key="here i added my own key"&format=json&nojsoncallback=1',
type: 'GET',
dataType: 'JSON',
data: {
//lat: lat,
//long:long,
},
success: function(serverResponse) {
console.log("flickr");
console.log(data);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log('error');
console.log(errorThrown);
console.log(jqXHR);
},
complete: function() {
$("#ajaxIndicator").modal('hide');
}
});
});
What you need to do is
Extract the urls and store them in an array
Loop through array, creating a new child image with the src set correctly
var photos = $("#photos")
for (var i = 0; i < arr.length; i++) {
var image = "<img src=" + encodeURL(arr[i]) + "></img>"
photos.append(image)
}
I think that you should focus on simpler apis for the time being
Related
I currently have a JS file which displays a single line know issue entered by a user via a SharePoint list. The div id it displays on the page is 'knowntitle'.
I now have been asked to display further information, so that the user would have another field to fill in on the SharePoint list called Further Details would be a Multiple Lines of Text field.
I wrote the original pages a year ago, and I'm a bit rusty! I've made a start and commented out what I've done so far. Any help on how to proceed would be gratefully received, js below:
function getDeviceKnownIssues() {
//var txtfurtherinfo = "";
var txtTitleKnown = "<ol>";
var query = "http://xxx/sites/it/ITInfrastructure/_vti_bin/listdata.svc//Knownissues?$filter=DeviceID eq " + window.DeviceId + "";
var call = $.ajax({
url: query,
type: "GET",
dataType: "json",
headers: {
Accept: "application/json;odata=verbose"
}
});
call.done(function(data, textStatus, jqXHR) {
$.each(data.d.results, function(index, item) {
var KnownTitle = item.Title;
//var FurtherInfo = item.Info;
txtTitleKnown = txtTitleKnown + "<li>" + KnownTitle + "</li>";
});
txtTitleKnown = txtTitleKnown + "</ol>";
//$('furtherinfo').append(txtName);
$('#knowntitle').append(txtTitleKnown);
});
call.fail(function(jqXHR, textStatus, errorThrown) {
alert("Error retrieving data: " + jqXHR.responseText);
});
}
You can concatenate the further info together with line breaks \r\n and them display them in the cell:
$.each(data.d.results, function(index, item) {
txtTitleKnown += "<li>" + item.Title + "</li>";
if(item.Info != undefined) {
txtfurtherinfo += item.Info + "\r\n";
}
});
txtTitleKnown = txtTitleKnown + "</ol>";
$('#knowntitle').append(txtTitleKnown);
$('#furtherinfo').append(txtfurtherinfo);
I am trying to display items from my database. There are 6 items in it. However, it was only able to display the first item. But they are able to display all the 6 buttons. I have also attached a picture at the end to show how my page looks like currently. Is there any way to solve this problem? I want my item image, description and price to appear and followed by the button next. But as of now, its showing the first item and the 6 buttons.
Javascript
$(document).ready(function () {
showlist();
});
function showlist(userid) {
var url = serverURL() + "/listitems.php";
categorynameID = decodeURIComponent(getUrlVars()["categoryID"]);
var JSONObject = {
"categoryID": decodeURIComponent(getUrlVars()["categoryID"])
};
$.ajax({
url: url,
type: 'GET',
data: JSONObject,
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function (arr) {
_showitemResult(arr);
},
error: function () {
validationMsg();
}
});
}
function _showitemResult(arr) {
for (var i = 0; i < arr.length; i++) {
$("#lblimagefile").attr("src", serverURL() + "/images/" + arr[i].imagefile); //display profile image
$("#lblitemName").html(arr[i].itemName); //display item name
$("#lblprice").html(arr[i].price); //display price
htmlstring = "<a href='#' class='ui-btn' id='btn" + arr[i].itemID + "'>View Item</a>"; //add a new [Category] button
$("#result").append(htmlstring);
$("#btn" + arr[i].itemID).bind("click", { id: arr[i].itemID }, function (event) {
var data = event.data;
showitem(data.id);
});
}
}
function showitem(itemID) {
//alert(categoryID);
window.location = "showitem.html?itemID=" + itemID;
}
HTML
<div role="main" class="ui-content" id="main-ui">
<img id="lblimagefile" height="100">
<div id="lblitemName"></div>
<div id="lblprice"></div>
<div id="result"></div>
</div>
Add to htmlstring price, image and name template. htmlstring is your template for every post.
HTML:
<div role="main" class="ui-content" id="main-ui">
<div id="result"></div>
</div>
jQuery:
htmlstring = "<img src='" + serverURL() + "/images/" + arr[i].imagefile + "' height='100'><div>" + arr[i].itemName + "</div><div>" + arr[i].price + "</div><a href='#' class='ui-btn' id='btn" + arr[i].itemID + "'>View Item</a>"; //add a new [Category] button
$("#result").append(htmlstring);
I am using a jquery plugin to generate a mega dropdown on my mobile website:
The menu is generated dynamically: everytime the user clicks on the right arrow, an api call is made to gather all sub-points to the clicked menu-entry. Down the menu everything works fine, but when I click on "back" it seems that there is added a forward/back-button for each menu-level:
This is my code:
// Catching the click-event
$(document).on('click','.next-button', function(){
var subCatContainer = $(this).next('.subcats');
var current = $(this).parent('.shopCatWithSub');
var categoryid = current.data('categoryuuid');
console.log('Next clicked');
console.log(categoryid);
if(typeof categoryid !== "undefined"){
buildSubcats(categoryid, subCatContainer, standardUrl);
} else {
console.log("No category set!");
}
});
// Get subcategories from API:
function buildSubcats(catid, subCatContainer, standardUrl) {
$.ajax({
type: 'GET',
url: 'https://my-awesome-url.de/api?category-id=' + catid,
dataType: 'jsonp',
contentType: 'application/json',
success: function (data) {
handleResponse(data, subCatContainer, standardUrl);
},
error: function(XMLHttpRequest, textStatus, errorThrow) {
console.log(errorThrow);
if (jQuery.isFunction(callback)) {
}
}
});
}
// Build and add new nav-elements:
function handleResponse(data, subCatContainer, standardUrl){
var output = '';
$.each(data, function(key, category){
var element = '';
var uladd = "";
var aClassAdd = "";
if(category.hasSubcategories) {
uladd = '<ul class="subcats"></ul>';
aClassAdd = 'has-next-button';
}
element = '<li class="shopCatWithSub" data-categoryuuid="' + category.categoryUUID + '">'
+ '<a class="text-truncate menu-item ' + aClassAdd + '" href="' + standardUrl + category.categoryUUID + '">'
+ '<i class="icon-' + category.categoryIconClass + ' mr-2"></i>'
+ category.displayName
+ '</a>'
+ uladd
+ '</li>';
output += element;
});
subCatContainer.empty();
subCatContainer.html(output);
// Re-initialize menu
$('.nav-mobile').mobileMegaMenu();
}
I assume that there is a problem with the re-initializing of the complete menu-structure. But I can't figure out how to handle it.
I'm using seatwaves api and have run into an error, The issue is that when i load hte table that the json is on i run into this error in the console No 'Access-Control-Allow-Origin' header is present on the requested resource.
i'm still quite new to this so any help or all the help would be so greateful!
Thanks
Sam
Heres the ajax code
$.ajax({
type: 'GET',
crossDomain: true,
dataType: 'json',
url: 'api link for seatwave',
success: function(json) {
//var json = $.parseJSON(data);
for (var i = 0; i < json.results.TicketGroups.length; i++) {
var section = json.results.TicketGroups[i].TicketTypeName;
var no = json.results.TicketGroups[i].Qty;
var price = json.results.TicketGroups[i].
Price;
var button =
"<button class='btn btn-info' data-url='LINK'>Click Here</button>";
$("#tableid").append("<tr><td>seatwave</td><td>" + section +
"</td><td>N/A</td><td>N/A</td><td>" + no +
"</td><td>£"+price +
"</td><td>" + button + "</td></tr>");
$("#tableid").find(".btn.btn-info").click(function() {
location.href = $(this).attr("data-url");
});
}
sortTable();
},
error: function(error) {
console.log(error);
}
});
I have two javascript functions madeAjaxCall() and getBookCall(bookId) to obtain book list and chapter list respectively.
I'm trying to call getBookCall(bookId) from within the function madeAjaxCall().
function madeAjaxCall(){
$.ajax({
type: "GET",
url: "http://localhost:8080/restApp/book/list",
contentType:"application/json; charset=utf-8",
dataType:"json",
success: function(data){
delete_table();
if(data){
var len = data.length;
var txt = "";
txt += "<tr><th>"+"bookId"+"</th><th>"+"bookName"+"</th><th>"+"Chapter Details"+"</th></tr>";
if(len > 0){
for(var i=0;i<len;i++){
if(data[i].bookId != null && data[i].bookName != null){
/* txt += "<tr><td>"+data[i].bookId+"</td><td>"+data[i].bookName+"</td><td>"+"Chapter details"+"</td></tr>"; */
txt += "<tr><td>"+data[i].bookId+"</td><td>"+data[i].bookName+"</td><td>"+"Chapter details"+"</td></tr>";
}
}
if(txt != ""){
$("#table1").append(txt).removeClass("hidden");
}
}
}
},
error: function(jqXHR, textStatus, errorThrown){
alert('error: ' + textStatus + ': ' + errorThrown);
}
});
return false;
}
And the other function
function getBookCall(bookId){
$.ajax({
type: "GET",
url: "http://localhost:8080/restApp/chapter/list/"+bookId,
contentType:"application/json; charset=utf-8",
dataType:"json",
success: function(data){
delete_table2();
if(data){
var len = data.length;
var txt = "";
txt += "<tr><th>"+"chapterId"+"</th><th>"+"chapterName"+"</th></tr>";
if(len > 0){
for(var i=0;i<len;i++){
if(data[i].chapterId != null && data[i].chapterName != null){
txt += "<tr><td>"+data[i].chapterId+"</td><td>"+data[i].chapterName+"</td></tr>";
}
}
if(txt != ""){
$("#table2").append(txt).removeClass("hidden");
}
}
}
},
error: function(jqXHR, textStatus, errorThrown){
alert('error: ' + textStatus + ': ' + errorThrown);
}
});
return false;
}
I am obtaining list of books as JSON from the function madeAjaxCall() and appending the list in a table. I want to call the function getBookCall(bookId) from within the function madeAjaxCall() with the help of a href. But i am unable to call the function getBookCall(bookId) using a href, from within the function madeAjaxCall().
This is the line from the function madeAjaxCall from where the function getBookCall(bookId) could not be called.
txt += "<tr><td>"+data[i].bookId+"</td><td>"+data[i].bookName+"</td><td>"+"Chapter details"+"</td></tr>";
Here In example I have use custom data-* attribute to store bookid, which can be fetched using .data(), create your anchor like:
txt += '<a class="myBookLink" href="#" data-bookid="' + data[i].bookId + '">Chapter details</a>";
Then use Event Delegation using .on() delegated-events approach to bind the click event handler of anchor.
$(document).on('click', function(){
getBookCall($(this).data('bookid'))
return false;
})
Important: In place of document you should always use closest static container.
For Immediate solution use quotes properly.
txt += "<tr><td>"
+ data[i].bookId
+ "</td><td>"
+ data[i].bookName
+'</td><td>Chapter details</td></tr>';
instead of
txt += "<tr><td>"+data[i].bookId+"</td><td>"+data[i].bookName+"</td><td>"+"Chapter details"+"</td></tr>";