This question already has answers here:
Calling an asynchronous function within a for loop in JavaScript
(10 answers)
Closed 6 years ago.
I am just learning Jquery from freecode.camp and I am writing some code to Use the Twitchtv JSON API ( https://www.freecodecamp.com/challenges/use-the-twitchtv-json-api).
When I want to get five channels logo on Twitch.tv ,but when I write the code ,I just found there was four same logo ,it was never what I want .
I have a codepen at http://codepen.io/zhangolve/pen/JKOXwW?editors=1111 ,if you like ,please check it out.
this is the JS code:
$("#click").on("click", function() {
var channel = ['OgamingSC2', 'FreeCodeCamp', 'terakilobyte', 'storbeck', 'RobotCaleb'];
for (var i = 0; i < channel.length; i++) {
var url = 'https://api.twitch.tv/kraken/streams/' + channel[i] + '?callback=?';
var thechannelurl = 'https://api.twitch.tv/kraken/channels/' + channel[i] + '?callback=?';
$.getJSON(url, function(data) {
if (data.stream == null) {
$.ajax({
dataType: "json",
url: thechannelurl,
//data: data,
type: "GET",
success: function(w) {
$("#content").append('<img src=' + w.logo + '> </img>')
}
});
} else {
var logo = data.stream.channel.logo;
//console.log(logo);
$("#content").append('<img src=' + logo + '></img>');
}
})
}
})
I forked your pen ...
Here is the code working:
http://codepen.io/rafaelcastrocouto/pen/rLYWXV
One channel in your list has no logo ... so I used a placeholder image.
var channelAPI = 'https://api.twitch.tv/kraken/';
var channels=['OgamingSC2',
'FreeCodeCamp',
'terakilobyte',
'storbeck',
'RobotCaleb'];
var getJSONCallback = function (data, url) {
if (data && data.logo) {console.log('1', data.logo)
appendLogo(data.logo);
} else if (data &&
data.stream &&
data.stream.channel &&
data.stream.channel.logo) {console.log('3', data.stream.channel.logo)
appendLogo(data.stream.channel.logo);
} else if (url && url.channel) {console.log('2', url.channel.toString())
$.getJSON(channelAPI+'channels/'+url.channel, getJSONCallback);
} else {
appendLogo('https://placeholdit.imgix.net/~text?txtsize=63&bg=FF6347&txtclr=ffffff&txt=No Logo Found&w=302&h=302');
}
};
var appendLogo = function (logo) {
$("#content").append('<img class="img" src="'+logo+'"></img>');
};
var clickFunction = function() {
for(var i=0;i<channels.length;i++) {
var channel = channels[i];
$.getJSON(channelAPI+'streams/'+channel, function (data) {
getJSONCallback(data, {channel: this});
}.bind(channel));
}
};
$("#click").on("click", clickFunction);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="click" class="btn btn-primary" >click</button>
<div id="content"></div>
Related
I have a page shows product catalog populated by a webmethod.
When user click on image he is redirect to details page.
When user come back to catalog id like page scroll bottom at the product visited
How can i accomplish this
my html
<div class="articoli">
</div>
my javascript
<script>
$(document).ready(function () {
var Skip = 9;
var Take = 9;
function Load(Skip, Take) {
$('#divPostsLoader').html('<img src="Images/loading.gif" height="100" />');
$.ajax({
type: "POST",
url: "page.aspx/LoadProduct",
data: "{ Skip:" + Skip + ", Take:" + Take + " }",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
if (data != "") {
//accodo dati a div
$('.articoli').append(data.d);
}
$('#divPostsLoader').empty();
},
error: function () {
alert('error');
}
})
};
$(window).scroll(function () {
if ($(window).scrollTop() == ($(document).height() - $(window).height())) {
Load(Skip, Take);
Skip = Skip + 9;
}
});
});
my c# webmethod
[System.Web.Services.WebMethod]
public static string LoadProduct(int Skip, int Take)
{
StringBuilder GetProduct = new StringBuilder();
MyDataBaseEntities db = new MyDataBaseEntities();
var prod = (from a in db.TAB
select a).Skip(Skip).Take(Take);
foreach (var a in prod)
{
var Codart = a.Codart;
var Prezz = a.Prezz;
var pathimg = a.pathimg;
GetProduct.Append("<div class=\"col-md-4\">");
GetProduct.Append("<div class=\"col-md-6 text-left\">");
GetProduct.AppendFormat(string.Format("<a href='Details.aspx?Articolo={0}' class=\"codart\" >", Codart));
GetProduct.AppendFormat("<span class=\"codart\">{0}</span>", Codart);
GetProduct.Append("</a>");
GetProduct.Append("</div> ");
GetProduct.Append("<div class=\"col-md-6 text-right\" style=\"color:gray;font-size:large;\">");
GetProduct.AppendFormat(string.Format("{0:c}", Prezz));
GetProduct.Append("</div> ");
GetProduct.AppendFormat(string.Format("<a href='Details.aspx?Articolo={0}' class=\"codart\" >", Codart));
GetProduct.AppendFormat(string.Format("<img src='{0}' class='img-responsive MyImage' alt='{1}'/>", pathimg, Codart));
GetProduct.Append("</a>");
GetProduct.Append("</div> ");
}
return GetProduct.ToString();
}
how can i scroll bottom at page load?
Try adding an Id to the item(s) you want to scroll to. You can then, depending on how you want to tackle it, either href or assign said Id through a script to initiate a scroll. Here you can see more details on how to scroll to a specific part of your page by using the component's Id.
I would add a unique Id to each item in your list.
Then I would write a script to read/set a variable to which item to scroll to.
Mind you, I'm writing this on a whim so you might need to correct or alter it to fit your needs.
You can use this to save and read cookies with jquery.
The script could be something like this:
var scrollToId;
$(document).ready(function () {
var cookie = $.cookie('last_clicked_id');
if (cookie != '') {
scrollToId = cookie;
} else {
scrollToId = '#';
}
$("html, body").animate({ scrollTop: $(scrollToId).offset().top }, 1000);
});
$('.productItemClass')
.on('click',
function() {
$.cookie('last_clicked_id', $(this).attr('id'));
});
use this and set the variable sc
var sc;
var scroll;
var loop = setInterval(function() {
sc = window.scrollTop;
if (scroll === null) {
localstorage.setItem("bgc", sc);
}
}, 10);
window.onload = function() {
scroll = localstorage.getItem("bgc");
if (scroll !== null) {
window.scollTop = scroll + "px";
}
}
I'm working on a simple program which displays the weather conditions of queried/searched places. All is well, though I'd like to know how to automatically reset/clear the DOM (or at least the relevant section displaying the results) and populate it with results of the new search. At the moment, it appends the results unless I clear them manually (clear button).
Rather than copy/paste the all the codes (HTML/CSS/JS-jQuery), I preferred having them at JSBin. So here is a link to the 'app', and thus the rest of the codes (HTML and CSS).
JS/jQuery Code
$(function() {
function showWeather() {
let $title = $("#station"),
$description = $("#description"),
$temperature = $("#temp"),
$chill = $("#chill"),
$wind = $("#wind"),
$humidity = $("#humidity"),
$units = $(".units").text(),
$apiPath1 = "https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%20in%20(select%20woeid%20from%20geo.places(1)%20where%20text%3D%22",
$query = $('input#city').val(),
$apiPath2 = "%2C%20ak%22)&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys",
$url = $apiPath1 + $query + $apiPath2;
$("input#city").val("");
$.ajax({
type: "GET",
url: $url,
success: function(data) {
$title.append(`
<h3>${data.query.results.channel.item.title}</h3>
`)
$description.append(`
<p>${data.query.results.channel.item.condition.text}</p>
`)
$temperature.append(`
<h1><span id="temp1">${data.query.results.channel.item.condition.temp}</span> °<span class="units">F</span></h1>
`)
$chill.append(`
<p>Feels like: <span id="temp2">${data.query.results.channel.wind.chill}</span> °<span class="units">F</span></p>
`)
$wind.append(`
<p>Wind speed: ${data.query.results.channel.wind.direction} km/h; Wind direction: ${data.query.results.channel.wind.speed}</p>
`)
$humidity.append(`
<p>Humidity: ${data.query.results.channel.atmosphere.humidity} %</p>
`)
}
});
}
//Converting Fahrenheit to Celsius
function fahrToCels(F) {
return Math.round((5/9) * (F - 32));
}
//Converting Celsius to back to Fahrenheit
function celsToFahr(C) {
return Math.round((C * 9/5 + 32));
}
$("#submit").on("click", function() {
showWeather();
});
$("input#city").on("keypress", function(event) {
if (event.which === 13) {
showWeather();
}
});
$('#clear').on('click', function (event) {
event.preventDefault();
$('#station, #description, #temp, #chill, #wind, #humidity').empty('');
});
$("#tempUnits").on("click", function() {
let temp1 = Number($("#temp1").text());
temp2 = Number($("#temp2").text());
if ($(".units").html() === "C") {
$(this).html("Temperature in Celsius")
$("#temp1").html(celsToFahr(temp1));
$("#temp2").html(celsToFahr(temp2));
$(".units").html("F");
}
else {
$(this).html("Temperature in Fahrenheit")
$("#temp1").html(fahrToCels(temp1));
$("#temp2").html(fahrToCels(temp2));
$(".units").html("C");
}
});
});
Cheers!
Try using html instead of append
$.ajax({
type: "GET",
url: $url,
success: function(data) {
$title.html(`
<h3>${data.query.results.channel.item.title}</h3>
`)
$description.html(`
<p>${data.query.results.channel.item.condition.text}</p>
`)
$temperature.html(`
<h1><span id="temp1">${data.query.results.channel.item.condition.temp}</span> °<span class="units">F</span></h1>
`)
$chill.html(`
<p>Feels like: <span id="temp2">${data.query.results.channel.wind.chill}</span> °<span class="units">F</span></p>
`)
$wind.html(`
<p>Wind speed: ${data.query.results.channel.wind.direction} km/h; Wind direction: ${data.query.results.channel.wind.speed}</p>
`)
$humidity.html(`
<p>Humidity: ${data.query.results.channel.atmosphere.humidity} %</p>
`)
}
});
Use
$title.html('<h3>${data.query.results.channel.item.title}</h3>')
instead of
$title.html('<h3>${data.query.results.channel.item.title}</h3>')
Replace other $.append(content) with $.html(htmlString)
I am following a tutorial on YouTube showing how to get data from the myapifilms.com api and I am having trouble rendering the data to HTML. Currently my ajax call is working and the data is showing in the console. The problem I am having is getting the data to show on the page itself. I searched through the question already asked but had no luck. Here's my js code so far:
$(document).ready(function(){
$("#searchMovie").click(searchMovie);
var movieTitle = $("#movieTitle");
var table = $("#results");
var tbody = $("#results tbody"); //table.find("tbody");
function searchMovie() {
var title = movieTitle.val();
$.ajax({
url: "http://www.myapifilms.com/imdb/idIMDB?title="+ title +"&token= + token goes here +&format=json&language=en-us&aka=0&business=0&seasons=0&seasonYear=0&technical=0&filter=2&exactFilter=0&limit=1&forceYear=0&trailers=0&movieTrivia=0&awards=0&moviePhotos=0&movieVideos=0&actors=0&biography=0&uniqueName=0&filmography=0&bornAndDead=0&starSign=0&actorActress=0&actorTrivia=0&similarMovies=0&adultSearch=0&goofs=0"es=0&fullSize=0&companyCredits=0",
dataType: "jsonp",
success: renderMovies
})
function renderMovies(movies) {
console.log(movies);
tbody.empty();
for(var m in movies) {
var movie = movies[m];
var title = movie.title;
var plot = movie.simplePlot;
var posterUrl = movie.urlPoster;
var imdbUrl = movie.urlIMDB;
var tr = $("<tr>");
var titleTd = $("<td>").append(title);
var plotTd = $("<td>").append(plot);
tr.append(titleTd);
tr.append(plotTd);
tbody.append(tr);
}
}
}
});
I feel like I am so close but can't quite figure what I am missing. Again I was following a tutorial so if there's a better way to accomplish this goal I'm definitely open to suggestions.
Update:
I changed my code to this and I'm getting undefined in the browser. I changed the for loop to this
success: function (movies) {
console.log(movies);
tbody.empty();
for (var m in movies) {
$(".movies").append("<h3>"+ movies[m].title +"</h3>");
$(".movies").append("<h3>"+ movies[m].plot +"</h3>");
}
}
I figured out a solution, instead of using myapifilms, I used the tmdb api instead. Changing my code to this worked:
var url = 'http://api.themoviedb.org/3/',
mode = 'search/movie?query=',
input,
movieName,
key = 'myapikey';
//Function to make get request when button is clicked to search
$('button').click(function() {
var input = $('#movie').val(),
movieName = encodeURI(input);
$.ajax({
type: 'GET',
url: url + mode + input + key,
async: false,
jsonpCallback: 'testing',
contentType: 'application/json',
dataType: 'jsonp',
success: function(json) {
console.dir(json.results);
for (var i = 0; i < json.results.length; i++){
var result = json.results[i];
$(".moviesContainer").append('<div class="movies col-md-12">'+
'<img class="poster" src="http://image.tmdb.org/t/p/w500'+ result.poster_path +'" />'
+'<h3>'+ result.title +'</h3>'
+'<p><b>Overview: </b>'+ result.overview +'</p>'
+'<p><b>Release Date: </b>'+ result.release_date +'</p>'
+'</div>');
}
},
error: function(e) {
console.log(e.message);
}
});
});
I have the problem that my code is not performing the ajax call when i pass a search parameter. I added several console.log to my code! So that you i hope you can easily comprhened my code:
icd: function(icd,id,search){
if(!(typeof search === 'undefined')){
var urls = "icd?search=" + search;
console.log("1");
}else{
if(icd == 2){
var urls = "/icd/icd2/" + id;
}if(icd == 3){
var urls = "/icd/icd3/" + id;
}
console.log("2");
}
console.log("3");
$.ajax({
dataType: "json",
url: SERVER + urls,
headers: {"X-TOKEN": TOKEN},
success: function(data,status,xhr){
console.log("4");
var array = $.map(data['icd'], function (field, i) {
return '<tr data-link="'+ field.id +'"><td>' + field.nummer + '</td><td>' + field.bezeichnung + '</td></tr>';
});
$('#DiagnosenTable').html(array.join(''));
$('#side-panel2 .breadcrumb').html($('<li/>').html($('<a/>',{href: '#',text: 'Alle',click: function(){Diagnose.start()} })));
if(icd == 2){
$('#side-panel2 .breadcrumb').append($('<li/>', {class: 'active',text: data['icd1'].bezeichnung}));
}
if(icd == 3){
$('#side-panel2 .breadcrumb').append($('<li/>').html($('<a/>',{href: '#',text: data['icd1'].nummer,click: function(){Diagnose.icd(2,data['icd1'].id)} })));
$('#side-panel2 .breadcrumb').append($('<li/>', {class: 'active',text: data['icd2'].bezeichnung}));
}
$('#DiagnosenTable tbody').eq(0).children('tr').each(function(){
$(this).click(function(){
if(icd == 2){
Diagnose.icd('3',$(this).attr('data-link'));
}else{
$('#inputCode').val($(this).children('td')[0].innerHTML);
$('#inputBez').val($(this).children('td')[1].innerHTML);
$('#TextEntry').val($(this).children('td')[0].innerHTML);
}
});
});
},
error: function(xhr, status, error) {
ErrorHandler.connection(xhr,status,error);
console.log("5");
}
});
console.log("6");
}
When i first tried to execute my code, i noticed that when i pass a search parameter, the ajax call isnt performed (because 4 or 5 is not printed to the console)Here is a screenshot from my console:
I cant explain me why this happens! What do i wrong?
One of these URLS is not like the other
var urls = "icd?search=" + search;
var urls = "/icd/icd2/" + id;
var urls = "/icd/icd3/" + id;
Do you see why the search URL does not work? It is different than the others. AKA: It is missing the a leading /.
var urls = "/icd?search=" + search;
^
just want to ask regarding my javascript code. I have a function that will delete and edit a data in my jqgrid. But everytime i run my code, it will not delete and edit if I dont put an alert in some portion of the code. Why is it happening? How can i make my program run without the alert?
Below is my delete function:
function woodSpeDelData(){
var selected = $("#tblWoodSpe").jqGrid('getGridParam', 'selrow');
var woodID='';
var woodDesc='';
var codeFlag = 0;
var par_ams = {
"SessionID": $.cookie("SessionID"),
"dataType": "data"
};
//this part here will get the id of the data since my id was hidden in my jqgrid
$.ajax({
type: 'GET',
url: 'processjson.php?' + $.param({path:'getData/woodSpecie',json:JSON.stringify(par_ams)}),
dataType: primeSettings.ajaxDataType,
success: function(data) {
if ('error' in data)
{
showMessage('ERROR: ' + data["error"]["msg"]);
}
else{
$.each(data['result']['main']['rowdata'], function(rowIndex, rowDataValue) {
$.each(rowDataValue, function(columnIndex, rowArrayValue) {
var fldName = data['result']['main']['metadata']['fields'][columnIndex].name;
if (fldName == 'wood_specie_id'){
woodID = rowArrayValue;
}
if (fldName == 'wood_specie_desc'){
woodDesc = rowArrayValue;
alert($('#editWoodSpeDesc').val() +' '+ woodDesc); //program will not delete without this
if(selected == woodDesc){
codeFlag =1;
alert(woodID); //program will not delete without this
};
}
});
if (codeFlag == 1){
return false;
}
});
if (codeFlag == 1){
return false;
}
}
}
});
alert('program will not proceed without this alert');
if (codeFlag == 1) {
var datas = {
"SessionID": $.cookie("SessionID"),
"operation": "delete",
"wood_specie_id": woodID
};
alert(woodID);
alert(JSON.stringify(datas));
$.ajax({
type: 'GET',
url: 'processjson.php?' + $.param({path:'delete/woodSpecie',json:JSON.stringify(datas)}),
dataType: primeSettings.ajaxDataType,
success: function(data) {
if ('error' in data)
{
showMessage('ERROR: ' + data["error"]["msg"]);
}
else{
$('#tblWoodSpe').trigger('reloadGrid');
}
}
});
}
}
EDIT
My main purpose of putting an alert was just to know if my code really get the right ID of the description, and if would really go the flow of my code... But then i realized that it really wont work with it.