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);
});
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 have this div here:
<div id='suggested_students'>
</div>
I am trying to write some javascript which will append this with the correct values:
<div id='STUDENT NAME' onClick='moveProfile("STUDENT NAME", "STUDENT ID")'>
STUDENT NAME<br>
STUDENT ID<br>
</div>
This is the javascript/ajax I have:
$('#search_bar').keyup(function () {
var keyword = $('#search_bar').val();
if(keyword.length > 2){
console.log('hey')
var url = window.location.pathname;
$.ajax({
method: 'GET',
url: url,
data: {
'keyword': keyword,
},
dataType: 'json',
success: function (data) {
var suggestions = data.students;
for(i = 0; i< suggestions.length; i++){
var current_student = suggestions[i];
console.log(current_student[0])
console.log(current_student[1])
}
}
});
}
})
and each iteration of the for loops produces something like:
[STUDENT NAME, STUDENT ID
How do I go about filling in these place holders and then appending the html to the main div for each student.
This will add the student information into the container div for you...
success: function (data) {
// get a reference to the container div
var $container = $("#suggested_students");
// remove any existing student information
$container.empty();
var suggestions = data.students;
for(i = 0; i< suggestions.length; i++){
var current_student = suggestions[i];
// create a new div to add to the container element
var $div = $("<div/>");
$div.data("name", current_student[0]);
$div.data("id", current_student[1]);
$div.html(current_student[0] + "<br/>" + current_student[1]);
$div.on("click", moveProfile);
$container.append($div);
}
}
There's a couple of things worth noting here. Firstly, I didn't give each new div the ID of the student name. There are several reasons for this, but the main one is that it's not a very friendly ID. Names have spaces and can also have other punctuation marks. Also, you can have multiple students with the same name, but you can't have multiple elements with the same ID.
Secondly, I set data attributes for each student div, rather than pass the values in an inline event handler. To handle the click event you'd need this extra function, already referenced above...
function moveProfile() {
var $this = $(this);
var studentId = $this.data("id");
var studentName = $this.data("name");
// do whatever you need with the student info here
}
Try this:
$('#search_bar').keyup(function () {
var keyword = $(this).val(), $suggested_students;
$suggested_students = $('#suggested_students');
if (keyword.length > 2) {
var url = window.location.pathname;
$.ajax({
method: 'GET',
url: url,
data: {
'keyword': keyword
},
dataType: 'json',
success: function (data) {
var i, suggestions, s_name, s_id, current_student;
suggestions = data.students;
// empty before
$suggested_students.empty();
for(i = 0; i< suggestions.length; i++){
current_student = suggestions[i];
s_id = current_student[0];
s_name = current_student[1]
$suggested_students.append(
"<div id='" + s_id + "' onClick='moveProfile(\"" + s_name + "\", \"" + s_id +"\")'>" +
s_id + " <br>" +
s_name + " <br>" +
"</div>"
);
}
}
});
}
});
I suggest, however, to abort the $.ajax call in case a new string is written or wait a few moments before executing a new one and avoid using onClick in this way: just add a class or a selector like #suggested_students > div and add a click event listener to each div inside the container.
for(i = 0; i< suggestions.length; i++){
var current_student = suggestions[i];
console.log(current_student[0])
console.log(current_student[1])
var div = "<div id='"+current_student[0]+"' onClick='moveProfile(\""+current_student[0]+"\", "+current_student[1]+")'>"+current_student[0]+"<br>"+current_student[1]+"<br></div>";
$('#suggested_students').append(div);
}
im creating Image Hotspot using javascript, i need to get a data (x,y and Info) from json file, currently im getting data from Javascript Array. How can i get it from json file?
Code Pasted here;
var points;
var l_nOldX;
var l_nOldY;
function createHotspots(){
var points = new Array(
/*Tamilnadu*/
[38.7, 85.6, "0168"],
[36.1, 85.3, "1843"],
[38.5, 88.3, "39647"],
[34.8, 29.2, "12320"]
);
var divHotspot = document.getElementById("loadImages");
for(pi = 0; pi < points.length; pi++){
var hs = document.createElement("div");
hs.className = "hotspot";
hs.style.position = "absolute";
hs.style.left = "calc(" + points[pi][0] + "% - 8px)";
hs.style.top = "calc(" + points[pi][1] + "% - 0px)";
hs.style.width = "15px";
hs.style.height = "15px";
var html;
if (points[pi][0] < 31) {
html = "<table cellpadding='0' cellspacing='0' class='tbltooltipright' align='center'><tr><td id='img9' align='center'><div align='center'><div class='divtooltip'><div class='divclose'></div>" + points[pi][2] + "</div><div id='triangle-down' class='arrow_boxr'></div></td></tr><tr><td align='center' id='img10' ></td></tr></table>";
// alert('a');
hs.innerHTML = html;
$(hs).bind("mouseenter", function () {
$(".tbltooltipnormal").hide();
$(".tbltooltipleft").hide();
$(".tbltooltipright").hide();
$(this).find(".tbltooltipright").show();
});
}
else {
html = "<table cellpadding='0' cellspacing='0' class='tbltooltipnormal' align='center'><tr><td id='img9' align='center'><div align='center'><div class='divtooltip'><div class='divclose'></div>" + points[pi][2] + "</div><div id='triangle-down' class='arrow_boxn'></div></td></tr><tr><td align='center' id='img10' ></td></tr></table>";
hs.innerHTML = html;
$(hs).bind("mouseenter", function () {
$(".tbltooltipnormal").hide();
$(".tbltooltipleft").hide();
$(".tbltooltipright").hide();
$(this).find(".tbltooltipnormal").show();
});
}
$('.divclose').on('click touchstart', function () {
//debugger;
$('.tbltooltipnormal').hide();
$('.tbltooltipleft').hide();
$('.tbltooltipright').hide();
return false;
});
divHotspot.appendChild(hs);
}
}
In above code i've get data from "Points" array instead of i need to get this array data from one json file ?
Please help me to get this fixed.
thanks in Advance.
You can use ajax to get the data from the json file and just wrap the existing code in a function which takes an argument and just assign that argument to the desired var:
var points;
var l_nOldX;
var l_nOldY;
function createHotspots(points){ // <---pass the array
var points = points; // assign it here
var divHotspot = document.getElementById("loadImages");
...
}
$.ajax({
url:'points.json', //<----call the json file
type:'GET',
dataType:'json',
success:createHotspots // reference to the data
});
var yourJsonDataFromFile=undefined;
var getJsonData=function () {
console.log("fetching data from JSON file");
var url = "path_to_your_json _file";
var ajaxHttp = new XMLHttpRequest();
ajaxHttp.overrideMimeType("application/json");
ajaxHttp.open("GET",url,true);
ajaxHttp.setRequestHeader("Access-Control-Allow-Origin", "*");
ajaxHttp.send(null);
ajaxHttp.onreadystatechange = function () {
if(ajaxHttp.readyState == 4 && ajaxHttp.status == "200")
{
yourJsonDataFromFile = JSON.parse(ajaxHttp.response);
}
};
}
modify this code add file path in path_to_your_json _fileand call this function getJsonData() after that your data will be in yourJsonDataFromFile in json format , hope this will resolve your issue
Please try this. Should solve your problem
$.getJSON('<path_to_your_json_file>/file.json', function(data) {
var points = data;
});
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>");
});
});
})
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;
});