I am getting some data from an API using $.getJSON. I am appending the information to a div once I recieve it. But sometimes the data takes time to load and hence I want to display a loading functionality, until something is appended to the div. How do i do this?
function getApis(){
var source = document.getElementById('toplace').value;
var dest = document.getElementById('fromplace').value;
var options = "";
var container = document.getElementById('div-form');
var disp_info = document.getElementById('train-info');
// var train_block = document.getElementById("train-block");
container.style.display = 'none';
disp_info.style.display = 'inline-block';
var url = "http://api.railwayapi.com/between/source/" + source + "/dest/" + dest +"/date/18-09/apikey/abvsl2868/";
$.getJSON(url,function(data){
console.log(data);
// I WANT TO DISPLAY A LOADING FUNCTIONALITY UNTIL THIS DATA IS APPEARING ON THE SCREEN
$("#train-info").append("Total Number of trains running from " + source + " to " + dest + " : " + data.total + "<br><br><br>");
data.train.forEach(function(trains){
options = "<div style='border:1px solid black;font-family:'Kaushan Script''> <br>Train Name : " + trains.name + "<br><br>" +"Train Number : " + trains.number + "<br><br>Departure Time : " + trains.src_departure_time + "<br><br> Arrival Time : " + trains.dest_arrival_time + "<br><br></div>";
// $('#train-block').append(options + "<br>");
$('#train-info').append(options + "<br>");
});
});
}
You need to display your image, or whatever before the ajax call
$("#myDiv").html("<img src='spinner.gif'>");
$.ajax({
dataType: "json",
url: url,
data: data,
success: $("#myDiv").html("success");
});
Add a spinner image tag in the container element.
<div id="#train-info"><img src="loading-spinner.gif"/></div>
Before appending data to it, remove this image tag.
Related
Is there a way for me to make sure each img tag created also contains or can be linked with its individual data from the api? If only one image is returned in the search, it will give me the data for that image. However, if multiple images are returned, once clicked, it will return a only one possible image and data. I am new to coding and javascript in general, so please forgive any rookie mistakes. Thanks!
var scryfallURL = "https://api.scryfall.com/cards/search?q=";
var cardName = "";
var container = $("#list");
$("#searchBtn").on("click", function(event) {
event.preventDefault();
container.empty();
cardName = $("#search").val().trim();
queryURL = scryfallURL + cardName;
$.ajax({
url: queryURL,
method: "GET"
}).then(function(response) {
debugger;
var result = response.data;
console.log(result);
$('#search').val('');
//loops through creating an image tag for each search result
for (let index = 0; index < result.length; index++) {
var showCard = $("#list").append("<image src=' " + result[index].image_uris["normal"] + "' ></image>", "</br>");
var name = result[index].name + "<br>";
var creature = result[index].type_line + "<br>";
var flavorText = result[index].flavor_text + "<br>";
var legality = result[index].legalities + "<br>";
var cardFront = "<image src=' " + result[index].image_uris["large"] + "' ></image>" + "<br>";
};
// click function to clear the div and replace with only one card image and info
showCard.click(function() {
$("#searchForm").empty();
container.empty();
$("#info").append(name, creature, flavorText, legality);
$("#oneCard").append(cardFront);
})
});
});
I'm using the GIPHY api to display an image based on a query. Below is the code I'm currently using to pull the image. It works but the problem right now is that each time you visit the website it shows the same GIF every visit until the query changes. What I'd like is for the GIF to update after every visit or page reload to a new random image in the array even if the query is the same. I'm really new to javascript and am unsure how to solve this problem so any help would be much appreciated!
Here is the function I'm using to query data
function weather(position) {
var apiKey = '';
var url = '';
var data;
// console.log(position);
$.getJSON(url + apiKey + "/" + position.coords.latitude + "," + position.coords.longitude + "?callback=?", function(data) {
$('.js-current-item1').html(Math.floor(data.currently.temperature) + '°');
$('.js-current-item2').html(data.currently.summary);
gif(data.currently.icon)
city(position.coords.latitude + "," + position.coords.longitude)
});
}
And here is the function for pulling images from GIPHY
function gif(status) {
var apiKey = '';
var url = 'http://api.giphy.com/v1/gifs/search?q=';
var query = status;
$.getJSON(url + query + apiKey, function(data) {
$('body').css('background-image', 'url(' + data.data[5].images.original.url + ')');
});
}
In your function gif(status) while setting the image choose a random value from data array instead of fixed
change
$('body').css('background-image', 'url(' + data.data[5].images.original.url + ')');
to
var randomIndex = Math.floor(Math.random() * data.data.length);
$('body').css('background-image', 'url(' + data.data[randomIndex].images.original.url + ')');
I have a list of my recent Tumblr audio posts coming in through the Tumblr API and with each post, an artist summary from the Last.fm API is attached. I have the data coming in correctly, but the audio posts are not showing up in chronological order. Every time I refresh the page, they appear in random order. I would like to have the most recent audio post appear at the top. Here is my code:
$(document).ready(function() {
var user = "nycxnc";
var key = "###";
var type = "audio";
var limit = "5";
var url = "https://api.tumblr.com/v2/blog/" + user +
".tumblr.com/posts/" + type + "?callback=?&filter=" + type +
"&limit=" + limit + "" + key + "";
$.getJSON(url, function(data) {
$.each(data.response.posts, function(i, item) {
var artist = item.artist;
var track = item.track_name;
var url2 =
"http://ws.audioscrobbler.com/2.0/?method=artist.getInfo&track=" +
track + "&artist=" + artist +
"&api_key=###&autocorrect=1&format=json&callback=?";
$.getJSON(url2, function(data) {
$.each(data, function(i, item) {
artist_summary = item.bio.summary;
artist_image = item.image[4]["#text"];
$(".au-wrapper").append(
'<div class="audio-wrapper"><img src=' + artist_image +
'><div class="audio-meta"><span class="audio-title">' +
track + '</span><div class="audio-artist">' + artist +
'</div></div><div class="url">' + artist_summary +
'</div></div>');
});
});
});
});
});
How can I combine the data from two API in the correct order, if the second JSON url (Last.fm) is dependent on data from the Tumblr API? I'm new to Javascript and I'm creating this script as a learning experiment, so any help would be very appreciated. (: Thank you.
Hi All i have a quick question about JSON data into href for AJAX
I have JSON coming into AJAX example data[i].listingid
How do i put that into a href inside the ajax?
Below are my codes, it will explain the situation more clearly.
Thanks for your time
<script>
$.ajax({
type: "GET",
url: "listing.php",
dataType: 'json',
success: function (data) {
for (var i = 0; i < data.length; i++) {
console.log(data)
var listingid = data[i].listingid;
var myOtherUrl =
"SpecificListing.html?Listingid=" + encodeURIComponent(listingid);
var html1 = "<div class=two> Listing Address : " + data[i].address + "<a href=myOtherurl>" +
data[i].listingid + "Click to view the details" + "</div>" +
"</a>"
$('#display12').append(html1);
}
}
});
</script>
You can straightly add it with concatenation like below :
var html1 = "<div class=two> Listing Address : " + data[i].address +
"<a href='"+ myOtherurl + "'>"+
data[i].listingid+"Click to view the details" + "</a></div>";
or else you can use jquery attr method after you finish with appending html to div like below:
var listingid = data[i].listingid;
var myOtherUrl = "SpecificListing.html?Listingid=" + encodeURIComponent(listingid);
var html1 = "<div class=two> Listing Address : " + data[i].address +
"<a id='hrefholder' >"+
data[i].listingid+"Click to view the details" + "</a></div>";
$('#display12').append(html1);
$('#hrefholder').attr("href",myOtherurl );
Tip : Don't forget to add id to anchor tag
Here's a cleaned up version of your callback (I try to avoid string concatenation for HTML as much as possible):
var successCallback = function(data) {
var baseUrl = 'SpecificListing.html?Listingid=';
for (var i=0; i<data.length; i++) {
var listingId = data[i].listingid;
var newUrl = baseUrl + encodeURIComponent(listingId);
var $newDiv = $('<div />').addClass('two');
var $newLink = $('<a />')
.attr('href', newUrl)
.text(listingId + ': Click to view details');
$newDiv.append($newLink);
$('#display12').append($newDiv);
}
};
Find a full working implementation including simulated AJAX call here:
http://jsfiddle.net/klenwell/N2k8X/
var html1 = "<div class=two> Listing Address : " + data[i].address + "<a href=myOtherurl>" + data[i].listingid+"Click to view the details" + "</a></div>";
Will work. Are u binding ajax event to this link?
Anjith and Orion are both right but ya'll have a typo:
the variable in your definition is called myOtherUrl but inside your concatenated string it is myOtherurl. Variables are case-sensitive.
your variable will be parsed as a variable if you leave your double quotes around it so it's good as is
Here is my original code:
<tr class="song" id="'.$this->i.'">
<td class="clickable" id="td1_'.$this->i.'">
...
</td>
</tr>
And the jQuery for that:
$(".clickable").click(function()
{
//
//Make only certain parts of songs clickable
//Hacky Way to Get Index
var temp = $(this).attr("id");
temp = temp.split('_');
var i = temp[1];
var status = $('#status_'+i).val();
alert('Clicked ' + i);
var maxid = $('#maxid').val();
if(status == "max") //if maximized
{
alert("max");
}
else
{
var user = $("#user_min"+i).val();
var ytcode = $("#ytcode_min"+i).val();
var title = $("#title_min"+i).val();
var artist = $("#artist_min"+i).val();
var genre = $("#genre_min"+i).val();
var score = $("#score_min"+i).val();
var ups = $("#ups_min"+i).val();
var downs = $("#downs_min"+i).val();
var id = $("#id_min"+i).val();
var upload_date = $("#upload_date_min+i").val();
//Maximizing New Song
dataString = 'user='+ user + '&ytcode=' + ytcode +
'&title=' + title + '&artist=' + artist +
'&genre=' + genre + '&score=' + score +
'&ups=' + ups + '&downs=' + downs +
'&id=' + id + '&upload_date=' + upload_date +
'&i=' + i;
$.ajax({
type: "POST",
url: "maxSongAjax.php",
data: dataString,
cache: false,
success: function(html){
$('#'+i).fadeIn(1000).html(html);
}
});
//Setting Max ID to New Song
$('#maxid').val(i);
}
return false;
});
I have the ajax returning identical html to what was replaced for testing purposes. However, after I click the loaded html, it does not respond to clicks. No pop-ups are shown from the alerts.
Why is this? How come the loaded html isn't responding like the first?
This is a very common issue for people new to jQuery; you have to use .live()
.click() only binds to existing elements.
An alternative to .live() is .delegate()