I cant figure out where I have gone wrong. I am trying to have it so that a random index is selected then from that index the corresponding item in the array is chosen and displayed. However, at the moment nothing is being displayed. I think this is because the functions are not loading after the page has loaded and I'm not sure how to do this correctly. If you see any other errors in my current code please feel free to leave some feedback. Thanks :)
JS
<script type="text/javascript">
$(document).ready(function() {
function getRandomVideo() {
//Arrays for videos, titles, images, and searches
var videos = ['https://www.youtube.com/embed/kiTO7c_qeZs', 'https://www.youtube.com/embed/z4Hfv00eqoI', 'https://www.youtube.com/embed/7cdZYQB5ONE', 'https://www.youtube.com/embed/i1gE3nyQnKg', ];
var titles = ['Beethoven - Music, Love and Wine', 'Mozart String Serenade No.13', 'Beethoven Sonata No. 31 in A Flat Major', "Debussy - Children's Corner", ];
var images = ["url('Assets/beethoven.jpg')", "url('Assets/mozart.jpg')", "url('Assets/beethoven.jpg')", "url('Assets/debussy.jpg')", ]
var searches = ['beethoven+biography&s=0', 'wolfgang+mozart&s=0', 'beethoven+biography&s=0', 'Claude+Debussy&s=1', ];
//Gets a random index then uses said index to select an option in the array
var rand = Math.floor(Math.random() * videos.length);
var video = videos[rand];
var title = titles[rand];
var image = images[rand];
var search = searches[rand];
//replaces parts of html with selected option from array
document.getElementById("songTitle").innerHTML = title;
document.getElementById("img").style.backgroundImage = image;
document.getElementById("randomVideo").src = video;
return search
}
var apiKey = "jja10ssv4950uh65";
//I want to do this function and the one abovevwhen the document is loaded
$(document).onload(function() {
var searchTerm = getRandomVideo();
var url = "http://api.trove.nla.gov.au/result?key=" + apiKey + "&encoding=json&zone=newspaper&sortby=relevance&q=" + searchTerm + "&s=0&n=5&include=articletext,pdf&encoding=json&callback=?";
console.log(url);
$.getJSON(url, function(data) {
$('#output').empty();
$.each(data.response.zone[0].records.article, function(index, value) {
$("#output").append("<p>" + value.articleText + "</p>");
});
});
});
});
</script>
When you call the function try like this...E.g:
<button onclick="$(function(){getRandomVideo()});">Test</button>
And let
<script type="text/javascript">
function getRandomVideo() {
// Your codes..
}
</script>
Remove the onload part from from your jquery code and it will work.
$(document).ready(function() {
function getRandomVideo() {
//Arrays for videos, titles, images, and searches
var videos = ['https://www.youtube.com/embed/kiTO7c_qeZs', 'https://www.youtube.com/embed/z4Hfv00eqoI', 'https://www.youtube.com/embed/7cdZYQB5ONE', 'https://www.youtube.com/embed/i1gE3nyQnKg', ];
var titles = ['Beethoven - Music, Love and Wine', 'Mozart String Serenade No.13', 'Beethoven Sonata No. 31 in A Flat Major', "Debussy - Children's Corner", ];
var images = ["url('Assets/beethoven.jpg')", "url('Assets/mozart.jpg')", "url('Assets/beethoven.jpg')", "url('Assets/debussy.jpg')", ]
var searches = ['beethoven+biography&s=0', 'wolfgang+mozart&s=0', 'beethoven+biography&s=0', 'Claude+Debussy&s=1', ];
//Gets a random index then uses said index to select an option in the array
var rand = Math.floor(Math.random() * videos.length);
var video = videos[rand];
var title = titles[rand];
alert(title);
var image = images[rand];
var search = searches[rand];
//replaces parts of html with selected option from array
document.getElementById("songTitle").innerHTML = title;
document.getElementById("img").style.backgroundImage = image;
document.getElementById("randomVideo").src = video;
return search
}
var apiKey = "jja10ssv4950uh65";
//I want to do this function and the one abovevwhen the document is loaded
var searchTerm = getRandomVideo();
var url = "http://api.trove.nla.gov.au/result?key=" + apiKey + "&encoding=json&zone=newspaper&sortby=relevance&q=" + searchTerm + "&s=0&n=5&include=articletext,pdf&encoding=json&callback=?";
console.log(url);
$.getJSON(url, function(data) {
$('#output').empty();
$.each(data.response.zone[0].records.article, function(index, value) {
$("#output").append("<p>" + value.articleText + "</p>");
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="songTitle"></div>
.onload is not a jQuery method . At .ready() at beginning of js document should be loaded at call to $.getJSON()
$(document).ready(function() {
// do stuff
var apiKey = "jja10ssv4950uh65";
var searchTerm = getRandomVideo();
var url = "http://api.trove.nla.gov.au/result?key=" + apiKey + "&encoding=json&zone=newspaper&sortby=relevance&q=" + searchTerm + "&s=0&n=5&include=articletext,pdf&encoding=json&callback=?";
console.log(url);
$.getJSON(url, function(data) {
$('#output').empty();
$.each(data.response.zone[0].records.article, function(index, value) {
$("#output").append("<p>" + value.articleText + "</p>");
});
});
})
Related
I have an html table on a page with raws that have 'urls', I'm trying to fetch one url at a time from a random row, however my code returns url as http://www.test.com/products/product-namehttp://www.test.com/products/product-name.json, as you can see it returns url twice, one without json and other with json data, hence I'm getting 404.
I just need the .json URL, not the first part.
How do I get rid of the first url which is not json?
Here's the code.
$(document).ready(function() {
$(document).on('click', '#closepopup', function() {
$("#popup").removeClass('popupslidein')
});
var tablelink = "https://test.com/pages/product-listing-for-popups.json"; //products url for json data
$.getJSON(tablelink, function(data) {
var table = data.page.body_html;
$('#popuptable').append(table);
startthepopups()
});
var suburbink = "https://test.com/pages/product-listing-suburbs-for-popups"; //suburb names in table rows
$.getJSON(suburbink, function(data) {
var suburb = data.page.body_html;
$('#popupsuburb').append(suburb)
});
var namelink = "https://test.com/pages/product-listing-names-for-popups"; //names in table rows
$.getJSON(namelink, function(data) {
var name = data.page.body_html;
$('#popupname').append(name)
});
function startthepopups() {
var popupstay = 10000;
var popuptrigger = 100000;
function triggerpopup() {
var getrandomtd = Math.floor((Math.random() * $('#popuptable tr').length) + 1);
var link = $('#popuptable tr:nth-child(' + getrandomtd + ')').text();
console.log(link);
var productname = '';
var getrandomsuburbtd = Math.floor((Math.random() * $('#popupsuburb tr').length) + 1);
var suburblink = $('#popupsuburb tr:nth-child(' + getrandomsuburbtd + ')').text();
var getrandomnametd = Math.floor((Math.random() * $('#popupname tr').length) + 1);
var randomname = $('#popupname tr:nth-child(' + getrandomnametd + ')').text();
$.getJSON(link + '.json', function(data) {
productname = data.product.title;
imagelink = data.product.images[0].src;
if (!$("#popup").hasClass("popupslidein")) {
$('#popupsomeone span.name').empty().append(randomname);
$('#popupsomeone span.location').empty().append(suburblink);
$('#popupimage').css('background-image', 'url(' + imagelink.split('.jpg')[0] + '_small.jpg)');
$('#popupproduct a').attr('href', link).empty().append(productname);
$("#popupagotext").empty().append(Math.round(Math.random() * 15 + 10));
$("#popup").addClass('popupslidein');
setTimeout(function() {
$("#popup").removeClass('popupslidein')
}, popupstay);
}
});
}(function loop() {
var random = Math.round(Math.random() * 10) * 100000 + popuptrigger;
setTimeout(function() {
triggerpopup();
loop()
}, 60000)
}());
}
});
$.getJSON() has a tendency to append your current url to the path you pass it if it thinks it's relative. To make this work, you could try to use $.getJSON() like so. Keep in mind, the protocol used will be the current page this code lives on.
$.getJSON('//test.com/pages/product-listing-for-popups.json')
I also noticed that nowhere in your code do you have a url for http://www.test.com/products/product-name.json, are you sure you're sharing the correct snippet of code?
Working Demo
The following two ways of using $.getJSON() with a fully qualified url work perfectly fine:
$(document).ready(function() {
var url = "https://jsonplaceholder.typicode.com/todos/1";
// Example 1
$.getJSON(url)
.done(function( data ) {
console.log(data);
});
// Example 2
$.getJSON(url, function(data) {
console.log(data)
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
I am trying to make a little app using moment.js and the openweatherapi. I am trying to reload my page every 'x' amount of time in order for the time to update. Whenever this happens, my JSON data blinks.. I've seen several questions like this before, but am still struggling..
I was using
setTimeout(function(){
window.location.reload(1);
}, 5000);
Here is what my code looks like:
<div id = "data"></div>
<ul class = "weatherData">
<li id = "city"></li>
<li id = "weatherType"></li>
<li id = "fTemp"></li>
<li id = "windSpeed"></li>
</ul>
</div>
<script>
$(document).ready(function(){
var api = 'http://api.openweathermap.org/data/2.5/weather?
lat=39.729431&lon=-104.831917&appid=97f35dee6354ab9d2bac7c56a4c4a6fe';
$.getJSON(api, function(data){
var weatherType = data.weather[0].description;
var city = data.name;
var windSpeed = data.wind.speed;
var kTemp = data.main.temp;
var fTemp;
var cTemp;
fTemp = (kTemp*(9/5)-459.67).toFixed(2);
cTemp = (kTemp-273).toFixed(2);
windSpeed = (2.237*(windSpeed)).toFixed(1);
$('#city').html(city);
$('#weatherType').html(weatherType);
$('#fTemp').html(fTemp + " ℉");
$('#windSpeed').html(windSpeed + " mph ");
});
});
</script>
<script>
var time = moment().format("h:mm");
var NowMoment = moment().format('LL');
var day = moment().format('dddd');
var eDisplayMoment = document.getElementById('displayDate');
eDisplayMoment.innerHTML = NowMoment;
var eDisplayTime = document.getElementById('displayTime');
eDisplayTime.innerHTML = time;
document.getElementById('displayDay').innerHTML = day;
</script>
Could someone guide me on what to do??
You just need to wrap your code in a function called getWeather, and call that from your setInterval. This will re-run the code not the whole page.
$(document).ready(function() {
var api = 'http://api.openweathermap.org/data/2.5/weather?lat = 39.729431 & lon = -104.831917 & appid = 97 f35dee6354ab9d2bac7c56a4c4a6fe ';
function getWeather() {
$.getJSON(api, function(data) {
var weatherType = data.weather[0].description;
var city = data.name;
var windSpeed = data.wind.speed;
var kTemp = data.main.temp;
var fTemp;
var cTemp;
fTemp = (kTemp * (9 / 5) - 459.67).toFixed(2);
cTemp = (kTemp - 273).toFixed(2);
windSpeed = (2.237 * (windSpeed)).toFixed(1);
$('#city').html(city);
$('#weatherType').html(weatherType);
$('#fTemp').html(fTemp + " ℉");
$('#windSpeed').html(windSpeed + " mph ");
});
};
getWeather();
setInterval(getWeather, 5000)
});
I am trying to run my script that is going to search for a movie title from a movie database. I get results in the console and no errors. But in my renderMovies function it's supposed to store the API movie title, plot etc in my variables, but when I print it out in a list it either gives me nothing (blank) or undefined. I am kind of new to jQuery, AJAX and APIs so I'm following a guide, so the code is not entirely written by me.
OBS: I get undefined when using this $("<td>" + plot + "</td>"), but blank when using $("<td>").append(title). You can find that code in the middle of the renderMovies function.
For example: I search for the movie 'Avatar' and I get two results. However the two results gets "stored" as undefined in the plot description and blank from the title.
$(document).ready(function(){
$(init);
function init() {
$("#searchMovie").click(searchMovie);
var movieTitle = $("#movieTitle");
var table = $("#results");
var tbody = $("#results tbody");
function searchMovie(){
var title = movieTitle.val();
$.ajax({
url: "http://www.myapifilms.com/imdb/idIMDB?title=" + title + "&token=b81c6057-20cf-4849-abc4-decbf9b65286&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&keyword=0"es=0&fullSize=0&companyCredits=0&filmingLocations=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); // blank
var plotTd = $("<td>" + plot + "</td>"); // undefined on my website
tr.append(titleTd);
tr.append(plotTd);
tbody.append(tr);
}
}
}
});
I've reordered your functions and calls because some of the variables were undefined. (Google Chrome -> F12 (opens developers console))
This returns a response on a button click.
$(document).ready(function () {
function searchMovie() {
var movieTitle = $("#movieTitle");
var title = movieTitle.val();
$.ajax({
url: "http://www.myapifilms.com/imdb/idIMDB?title=" + title + "&token=b81c6057-20cf-4849-abc4-decbf9b65286&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&keyword=0"es=0&fullSize=0&companyCredits=0&filmingLocations=0",
dataType: "jsonp",
success: renderMovies
});
}
function renderMovies(movies) {
console.log(movies);
var movieInfo = movies.data.movies;
var table = $("#results");
var tbody = $("#results tbody");
tbody.empty();
for (var m in movieInfo) // Tar information från apin och stoppar in i egna variabler.
{
var movie = movieInfo[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); // blank
var plotTd = $("<td>" + plot + "</td>"); // undefined on my website
tr.append(titleTd);
tr.append(plotTd);
tbody.append(tr);
}
}
$("#searchMovie").click(searchMovie);
});
I am trying to get multiple images from an ajax source and load the on the page when they have all finished loading. The issue I was having that has caused me to try to find a solution was that some of the images weren't loading even though those images existed on the server.
I have tried to add code that now adds the image to an array
design_images.push({cid:designImg});
... and then when all the images have loaded will add that to the page, but I can't get that to work.
var counter = 0;
$(design_images).load(function() { // many or just one image(w) inside body or any other container
counter += 1;
}).each(function(key, value) {
this.complete && $(this).load();
console.log(value);
});
Nothing is outputted from the .each
This is the output of the array design_images
The value of design_images.length is 0 though.
Here is the complete function:
function matte_design_change_design_type(element)
{
var element_value = null;
var mattes_selected_type = get_mattes_selected_type();
matte_design_widths[mattes_selected_type] = [];
var mattes_selected_design = get_mattes_selected_design();
var count_matte_designs = 0;
var found = false;
$(document).ready(function()
{
$.ajax(
{
type: "GET",
url: SITE_URL + "/system/components/xml/" + mattes_selected_type,
dataType: 'xml',
success: function(xml)
{
var output = [];
var design_images = [];
$('component', xml).each(function(i, el)
{
matte_design_widths[mattes_selected_type][i] = 0;
count_matte_designs++;
var thumb = $("thumb", this).text(),
cid = $("cid", this).first().text(),
name = $("name", this).first().text().replace("Collage - ", ""),
alt = name,
description = $("description", this).first().text(),
if (parseInt(cid, 10) === mattes_selected_design)
{
found = true;
$("#matte_design_name").html(name);
$("#matte_design_description").html(description);
}
var designImg = new Image();
designImg.id = 'cid_' + cid;
designImg.alt = alt;
designImg.onclick = function() {
matte_design_change(cid, mattes_selected_type);
};
designImg.onload = function() {
output.push('<span class="matte_design_image_name" id="design_' + cid + '"><img id="cid_' + cid + '" />');
output.push('<br /><span class="matte_design_name" id="matte_design_name_' + mattes_selected_type + '_' + i + '">' + name + '</span></span>');
matte_design_increase_width(mattes_selected_type, this.width, i);
$('#matte_designs_strip_wrapper').html(output.join(''));
};
designImg.src = 'https://example.com/system/components/compimg/' + thumb + '/flashthumb';
});
var counter = 0;
var size = $('img').length;
$(design_images).load(function() {
counter += 1;
}).each(function(key, value) {
this.complete && $(this).load();
console.log(value);
});
}
});
});
}
I have tried waitForImages and imagesLoaded but I couldn't get them to work for me, but I'm not opposed to using either one.
Hide all images by default using CSS
img{
display: none;
}
Use Jquery to check if all loaded, then display images
JQuery
$(window).load(function(){
$('img').fadeIn(800); //or $('img').show('slow');
});
I have a code to put two cameras on my site:
$(document).ready(function(){
var m;
var index;
var IP;
var port;
var name;
var user;
var password;
var image_old;
var image_new;
var cameraFeed;
var topImage;
var urls = [];
$.ajax({
type: "GET",
url: "json.htm?type=cameras",
dataType: "JSON",
async : false,
success: function(data) {
for(m=0; m<=1; m++){
index = data.result[m].idx;
IP = data.result[m].Address;
port = data.result[m].Port;
name = data.result[m].Name;
user = data.result[m].Username;
password = data.result[m].Password;
image_old = data.result[m].ImageURL;
image_new = image_old.replace("#USERNAME", user).replace("#PASSWORD", password);
cameraFeed = "http://" + IP + ":" + port + "/" + image_new;
alert(cameraFeed + m);
urls.push(cameraFeed);
}
setInterval(function() {
var d = Date.now();
$.each(urls, function(i, url) {
$('#topImage' + i).attr('src', url + "×tamp=" + d);
});
}, 100);
},
error: function(data) {
alert("Error")
}
});
});
And html code:
<img id="topImage0" width="640px">
<img id="topImage1" width="640px">
I can not create a script to make setinterval work for both imgs. It works only for one of them. Any suggestions how to make it works ?
Set interval works only for one img.
To give you an idea how to structure your application code:
Get the data from the server
Create the URLs from data
Update each image every X milliseconds with those URLs
In code:
$.ajax({...}).done(function(data) { // get data from server
// create URLs
var urls = [];
for (var m = 0; m < 2; m++) { // why not iterate over data.results?
var cameraFeed;
// build cameraFeed ...
urls.push(cameraFeed);
}
// Update images
setInterval(function() {
var d = Date.now();
$.each(urls, function(i, url) {
$('#topImage' + i).attr('src', url + "×tamp=" + d);
});
}, 100);
});
Of course this can still be approved, but that should point you into the right direction. Note in particular that it is unnecessary to have a setInterval for each image. Just let a single interval update all images.
Especially the for loop can be approved upon. I don't know how many results data.results has and if you only want to get the first two, but this is an excellent use case for Array#map:
var urls = data.results.map(function(result) {
// ...
return cameraFeed;
});