for a school assignment I chose to load all of the movies from top250 list dynamically with Ajax to a singlepage and from that page everytime I choose a movie from the list, a popover shows up with the details of that movie. What I wanted to know is how to get a general link for all movies to get the details for each movie on that list because I'm stuck with "The Shawshanks Redemption"-link. Here's the code
$(document).ready(function () {
$.ajax({
url: "crosscall/crosscall.php",
data: {
'url': 'http://www.imdb.com/chart/top?ref_=nv_ch_250_4' //Site van IMDB die de Top 250 toont.
},
type: "POST",
success: function (data) {
var $data = $(data);
var titel = $('.titleColumn');
var nummer = 0;
var imageURL = 'http://ia.media-imdb.com/images/M/MV5BODU4MjU4NjIwNl5BMl5BanBnXkFtZTgwMDU2MjEyMDE#._V1_SX214_AL_.jpg';
var imageID = 'image';
var image = $('.posterColumn td a img').attr('src');
$(document.body).append('<img id="' + imageID + '">');
$.ajax({
url: 'hotlink.php?url=' + imageURL,
success: function (base64data) {
$('#' + imageID).attr('src', 'data:image/png;base64,' + base64data);
}
});
$data.find('.titleColumn').each(function () {
var titel2 = $(this).find('a').text();
var datum = $(this).find('span[name=rd]').text();
var plaats = $(this).find('span[name=ir]').text();
if (titel2.length > 10) titel2 = titel2.substring(0, 38);
if (nummer < 250) {
$('.container').append('<div class="imgurstyle"><div class="titel"><h1>' + plaats + ' ' + titel2 + ' ' + datum + ' </h1></div><img src="' + imageURL + image + '" alt="image"></div>');
}
});
//Als men op een film klikt, zal de popover tevoorschijn komen.
$("a.popLink").click(function (event) {
//voorkomt dat het link waarop men zal klikken herlaadt.
event.preventDefault();
showPopover1();
});
var popoverBG;
var popover;
//functie popover maken zoals bij de oefeningen die we hadden behandeld tijdens WC.
function showPopover1() {
//maak popoverBG
popoverBG = document.createElement('div');
popoverBG.className = 'popoverBG';
document.body.appendChild(popoverBG);
//maak popover
popover = document.createElement('div');
popover.className = 'popover';
$.ajax({
url: "crosscall/crosscall.php",
data: {
'url': 'http://www.imdb.com/title/tt0111161/?ref_=chttp_tt_1' //Details van elk filmpagina ophalen.
},
type: "POST",
success: function (data) {
//gegevens ophalen in popover steken
var $data = $(data);
var jaartal = $('.infobar');
var nummer = 0;
$data.find('.infobar').each(function () {
var titel = $(this).parent().find('h1 span[itemprop=name]').text();
var jaartal2 = $(this).find('.nobr').text();
var rating = $(this).find('div .titlePageSprite star-box-giga-star').appendTo('li');
console.log($(this).find('.titlePageSprite star-box-giga-star'));
var genre = $(this).find('.itemprop').text();
var regisseur = $(this).parent().find('div[itemprop="director"] span ').text();
var schrijver = $(this).parent().find('div[itemprop="creator"] span').text();
var acteurs = $(this).parent().find('div[itemprop="actors"] span').text();
var meerAct = $(this).parent().find('.see-more inline nobr a[itemprop="url"]').text();
var plot = $(this).parent().find('p[itemprop="description"]').text();
var tijdsduur = $(this).find('time').text();
if (nummer < 250) {
popover.innerHTML = '<header><h2>' + titel + '</h2></header><ul><li><img src="images/shawshank%20redemption.jpg" alt="n1"></li><li>Release:' + jaartal2 + '</li><li>User ratings:' + rating + '</li><li>Genre: ' + genre + '</li><li>Duur: ' + tijdsduur + '</li><li>Regisseur: ' + regisseur + '</li><li>Schrijvers:' + schrijver + '</li><li>Acteurs: ' + acteurs + ' ' + meerAct + '</li><li>' + plot + '</li></ul><p>Meer info klik Hier<p>Close</p>';
}
});
}
});
document.body.appendChild(popover);
//voeg click toe aan popoverBG
popoverBG.onclick = removePopover;
function removePopover() {
document.body.removeChild(popoverBG);
document.body.removeChild(popover);
};
};
}
});
});
Related
I'm trying to iterate a nested API response and display them inside a html. I managed to do single image because the response only have single value.
**API response **
{"result":{"totalResults":5861511,"products":[{"productTitle":"S-XL Plus Size Tunic Autumn <font><b>Women</b></font> Dresses Casual Cartoon Print Christmas Dress Casual Loose Long Sleeve Party Dress Vestidos","originalPrice":"US $7.98","imageUrl":"https://ae01.alicdn.com/kf/H3ba2899c892d4a88a5f704453c39942ae/S-XL-Plus-Size-Tunic-Autumn-font-b-Women-b-font-Dresses-Casual-Cartoon-Print-Christmas.jpg","productUrl":"https://www.aliexpress.com/item/S-XL-Plus-Size-Tunic-Autumn-Women-Dresses-Casual-Cartoon-Print-Christmas-Dress-Casual-Loose-Long/4000353066650.html","allImageUrls":"https://ae01.alicdn.com/kf/H3ba2899c892d4a88a5f704453c39942ae/S-XL-Plus-Size-Tunic-Autumn-font-b-Women-b-font-Dresses-Casual-Cartoon-Print-Christmas.jpg,https://ae01.alicdn.com/kf/H218b19ee8bfc4f6ebe74b4297ca8395f5/S-XL-Plus-Size-Tunic-Autumn-font-b-Women-b-font-Dresses-Casual-Cartoon-Print-Christmas.jpg,https://ae01.alicdn.com/kf/H14b48746d6eb4d5788a7a9f6ce37195c7/S-XL-Plus-Size-Tunic-Autumn-font-b-Women-b-font-Dresses-Casual-Cartoon-Print-Christmas.jpg,https://ae01.alicdn.com/kf/Hb4b1f8b6223d4e7c88208751bfa681886/S-XL-Plus-Size-Tunic-Autumn-font-b-Women-b-font-Dresses-Casual-Cartoon-Print-Christmas.jpg,https://ae01.alicdn.com/kf/Hcfd17f95ac85470d9550d13f3683adc1I/S-XL-Plus-Size-Tunic-Autumn-font-b-Women-b-font-Dresses-Casual-Cartoon-Print-Christmas.jpg}]},"errorCode":20010000,"currentPageNum":0,"totalPageNum":0}
main.js
$(function (){
var $orders = $('#orders');
var $productimage = $('#productimage');
var $output = $('#output');
$.ajax({
type: 'GET',
url: 'http://gw.api.alibaba.com/openapi/param2/2/portals.open/api.listPromotionProduct/9420?fields=productUrl,allImageUrls,imageUrl,originalPrice,productTitle&keywords=women',
success: function(orders){
$.each(orders, function(i, order){
$orders.append('' + order.products[0].productTitle + '');
$output.append(order.products[0].allImageUrls[1]);
// $productimage.append('<img class="pic-1" src="' + order.products[0].imageUrl + '">'); // single image
});
}
});
});
Result generated
"t"
How do you create a loop for $output from allImageUrls ?
You need to split the allImageUrls and then run them in a loop as follows:
var result ={
"result": {
"totalResults": 5861511,
"products": [
{
"productTitle": "S-XL Plus Size Tunic Autumn <font><b>Women</b></font> Dresses Casual Cartoon Print Christmas Dress Casual Loose Long Sleeve Party Dress Vestidos",
"originalPrice": "US $7.98",
"imageUrl": "https://ae01.alicdn.com/kf/H3ba2899c892d4a88a5f704453c39942ae/S-XL-Plus-Size-Tunic-Autumn-font-b-Women-b-font-Dresses-Casual-Cartoon-Print-Christmas.jpg",
"productUrl": "https://www.aliexpress.com/item/S-XL-Plus-Size-Tunic-Autumn-Women-Dresses-Casual-Cartoon-Print-Christmas-Dress-Casual-Loose-Long/4000353066650.html",
"allImageUrls": "https://ae01.alicdn.com/kf/H3ba2899c892d4a88a5f704453c39942ae/S-XL-Plus-Size-Tunic-Autumn-font-b-Women-b-font-Dresses-Casual-Cartoon-Print-Christmas.jpg,https://ae01.alicdn.com/kf/H218b19ee8bfc4f6ebe74b4297ca8395f5/S-XL-Plus-Size-Tunic-Autumn-font-b-Women-b-font-Dresses-Casual-Cartoon-Print-Christmas.jpg,https://ae01.alicdn.com/kf/H14b48746d6eb4d5788a7a9f6ce37195c7/S-XL-Plus-Size-Tunic-Autumn-font-b-Women-b-font-Dresses-Casual-Cartoon-Print-Christmas.jpg,https://ae01.alicdn.com/kf/Hb4b1f8b6223d4e7c88208751bfa681886/S-XL-Plus-Size-Tunic-Autumn-font-b-Women-b-font-Dresses-Casual-Cartoon-Print-Christmas.jpg,https://ae01.alicdn.com/kf/Hcfd17f95ac85470d9550d13f3683adc1I/S-XL-Plus-Size-Tunic-Autumn-font-b-Women-b-font-Dresses-Casual-Cartoon-Print-Christmas.jpg"
}
]
},
"errorCode": 20010000,
"currentPageNum": 0,
"totalPageNum": 0
}
var allImagesList = result.result.products[0].allImageUrls.split(',');
allImagesList.forEach((imageUrl)=>{
console.log(imageUrl);
})
And your code will look like something as below:
$(function (){
var $orders = $('#orders');
var $productimage = $('#productimage');
var $output = $('#output');
$.ajax({
type: 'GET',
url: 'http://gw.api.alibaba.com/openapi/param2/2/portals.open/api.listPromotionProduct/9420?fields=productUrl,allImageUrls,imageUrl,originalPrice,productTitle&keywords=women',
success: function(orders){
$.each(orders, function(i, order){
$orders.append('' + order.products[0].productTitle + '');
$output.append(order.products[0].allImageUrls[1]);
var allImagesList = order.products[0].allImageUrls.split(',');
allImagesList.forEach((imageUrl)=>{
$productimage.append('<img class="pic-1" src="' + imageUrl + '">'); // single image
})
});
}
});
});
$.each(orders, function(i, order) {
$orders.append('' + order.products[0].productTitle + '');
//------------------------Start
var allImageUrlsArray = []; // Create array;
//split with comma, assign to varaible and loop it.
allImageUrlsArray = order.products[0].allImageUrls.split(',');
for (var i = 0; i < allImageUrlsArray.length; i++) {
$output.append(allImageUrlsArray[i]);
}
//---------------------------End
});
You did some mistakes in iterate JSON Object, and allImageUrls contain multiple images with comma(,) so you should convert this into array. Let's check the below example
LN: 21 you can loop the allImageUrls
for([k, v] of Object.entries(value.allImageUrls)){
console.log(k, v);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="orders"></div>
<script>
$(function() {
var $orders = $('#orders');
var $productimage = $('#productimage');
var $output = $('#output');
$.ajax({
type: 'GET',
url: 'https://gw.api.alibaba.com/openapi/param2/2/portals.open/api.listPromotionProduct/9420?fields=productUrl,allImageUrls,imageUrl,originalPrice,productTitle&keywords=women',
success: function(item) {
let orders = item.result.products;
orders = orders.map(product => {
product.allImageUrls = product.allImageUrls.split(',');
return product;
});
var con = '';
for ([key, value] of Object.entries(orders)) {
con += "<li><a href='" + value.productUrl + "'><img style='width: 30px;' src='" + value.allImageUrls[0] + "'/>" + value.productTitle + "</a></li>";
// Loop all images
for ([k, v] of Object.entries(value.allImageUrls)) {
console.log(k, v);
}
}
$orders.append("<ul>" + con + "</ul>");
}
});
});
</script>
$(function() {
var $orders = $('#orders');
var $productimage = $('#productimage');
var $output = $('#output');
$.ajax({
type: 'GET',
url: 'http://gw.api.alibaba.com/openapi/param2/2/portals.open/api.listPromotionProduct/9420?fields=productUrl,allImageUrls,imageUrl,originalPrice,productTitle&keywords=women',
success: function(orders) {
$.each(orders.result.products, function(i, order) {
console.log(order)
$div = $('<div id = "' + "order_" + i + '"></div>');
$imageDiv = $('<div id = "' + "image_" + i + '"></div>');
// = $('#order_' + i);
console.log($div)
$div.append('' + order.productTitle + '');
//;
var array = order.allImageUrls.split(',');
for (var j = 0; j < array.length; j++) {
//$output.append(order.allImageUrls[j]);
$imageDiv.append('<img style="width:50px;height:50px" class="pic-1" src="' + array[j] + '">'); // single image
}
$div.append($imageDiv);
$orders.append($div);
});
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="output">
<div id="orders">
</div>
</div>
Hope this helps. :)
I am working on a MVC4 C#.Net project and when I am trying to
click the button ('#btn_rightArw_Dwn') then the ajax call fires multiple times in MVC4. Why this is happening? Please look up on below jQuery code.
Below I have added jQuery code.
$("#btn_rightArw_Dwn").click(function() {
$('.fade_bg').show();
var Masterid = $('#MastersId').val();
var pgm_id = $('#program1').val();
if ($('#rdclick').val() == "0") {
$.ajax({
url: "/DataInput/Arrow_Load_Down?Id=" + Masterid + "&flag=" + "Right" + "&type=" + 0 + "&pgm_id=" + pgm_id,
async: true,
data: {},
success: function(data) {
$('#DVmaster').html(data);
$('#btn_rightArw1').attr('hidden', false);
$('#btn_LeftArw1').attr('hidden', false);
var production_id = $('#program1').val();
$.ajax({
url: "/DataInput/Arrow_Load_Details_Down?Id=" + Masterid + "&flag=" + "Right" + "&ProductnSts_id=" + pgm_id + "&type=" + 0,
async: false,
data: {},
success: function(data) {
$('#DVDetails').html(data);
$('#DVDetails').show();
$('#btn_rightArw_Dwn').attr('hidden', false);
$('#btn_LeftArw_dwn').attr('hidden', false);
},
error: function(html) {
$('.fade_bg').hide();
}
});
var channelid = $("#channel1").val();
var starttime = $("#StartTime").val();
var Endtime = $("#EndTime").val();
var date = $("#Date").val();
var Vimpact = $("#Viewers").val();
var gradeid = $("#grade1").val();
var seclength = $("#Seconds option:selected").text();
var Daypartid = $('#daypartid').val();
var itemid = $('#item1 option:selected').val();
var brandid = $("#brand1 option:selected").val();
$.ajax({
url: "/DataInput/Print_Labels_in_Edit?starttime=" + starttime + "&finishtime=" + Endtime + "&date=" + date + "&channelid=" + channelid + "&impact1=" + Vimpact + "&Seclength=" + seclength + "&gradesid=" + gradeid + "&itemid=" + itemid + "&brandid=" + brandid,
cache: false,
success: function(html) {
var labels = html.split(',');
var daypartname = labels[0];
var CPH = labels[1];
var TVR = labels[2];
var Mediavalue = labels[3];
var daypartid = labels[4];
$('.fade_bg').hide();
$('#lblDaypart').text(" " + daypartname);
$("#lblCPH").text('£' + " " + CPH);
$('#lblTvr').text(" " + TVR);
$('#lblMediaValue').text(" " + "£ " + Mediavalue);
$('#daypartid').val(daypartid);
},
error: function(html) {
$('.fade_bg').hide();
}
});
}
});
}
});
Thanks in advance.
I have an RSS reader that fetches events with ajax. I want the user to be able to click the link of the event and have it transition to a new page with the details. Here is an example I found: http://jsfiddle.net/hellosze/t22QP/ I am have trouble understanding what is happening since I am rather new to jQuery so I was hoping someone code direct me as to what is happening. Thanks!
Here is how I extract the xml data and display it to a main page:
$.ajax({
type: 'GET',
url: 'categoryURL',
dataType: 'xml',
success: function (xml) {
var data = [];
$(xml).find("item:lt(40)").each(function () {
var dateText = $(this).find("Date").text().toString();
var eventDate = moment(dateText,"YYYY-MM-DD");
var title = $(this).find("title").text();
var region = dateText.substr(8).toUpperCase();
if (region.length < 3) { region = "ALL"; }
var description = $(this).find("description").text();
var dateDisplay = description.substr(0, description.indexOf(",")+6); //Parsed DATE from description
if (dateDisplay.length > 35) { dateDisplay = "See event for details"; }
//var locationdisplay = description.substr(description.indexOf(",")+6,4); //Parsed the location from description
var category = $(this).find("category").text();
var linkUrl = $(this).find("link").text();
var displayTitle = "<a href='" + linkUrl + "' target='_blank'>" + title + "</a>"
var item = {title: displayTitle, DateDecription: dateDisplay, Date: new Date(eventDate), Region: region,}
data.push(item);
// $('#feedContainer').append('<h3>'+displaytitle+'</h3><p>'+"Event Date: "+descriptdisplay+'</p><p>'+"Location: "+region+'</p');
}); //END .each()
data.sort(function (a, b) {
a = new Date(a.Date);
b = new Date(b.Date);
return a>b ? -1 : a<b ? 1 : 0;
});
$.each(data, function (index, item) {
$('#feedContainer').append('<h3>' + item.title + '</h3><p>' + "Event Date: " + item.DateDecription + '</p><p>' + "Location: " + item.Region + '</p');
});
} //END success fn
});
});
From the below function I am getting results. Now I want to put that result into a div. So how should I put the result into a div?
$(document).ready(function () {
$.ajax({
type: "POST",
url: "../ajaxaction.php",
data: {
action: 'alllist'
},
dataType: 'json',
success: function (msg) {
for (var i = 0; i < msg.length; i++) {
var uname = msg[i].user_name;
var vtitle = msg[i].video_title;
var vid = msg[i].video_id;
var vthumb = msg[i].video_thumb;
}
}
});
});
You can append the result in to div with the format you like but a simple way of adding would be. You can use append() function to keep the added html with new html for each iteration of loop.
success: function(msg){
for (var i = 0; i < msg.length; i++) {
var uname = msg[i].user_name;
var vtitle = msg[i].video_title;
var vid = msg[i].video_id;
var vthumb = msg[i].video_thumb;
$('#divId').append("Name: " + uname + "," + "Title: " + vtitle +
"Id: " + vid + "," + "Thumb: " + vthumb + "<br />");
}
$(document).ready(function() {
$.ajax({
type: "POST",
url: "../ajaxaction.php",
data: { action:'alllist'},
dataType: 'json',
success: function(msg){
for (var i = 0; i < msg.length; i++) {
var uname = msg[i].user_name;
var vtitle = msg[i].video_title;
var vid = msg[i].video_id;
var vthumb = msg[i].video_thumb;
$("#container").html("Username: " + uname + "<br />Video Title: " + vtitle + "<br />Vide ID: " + vid + "<br />Video Thumb: " + vthumb);
}
}});
});
If your div exists:
jQuery('div selector').append(uname+' '+vtitle+...whatever variable and format);
If not
jQuery('element selector to put the div in').append('<div id="aID" class="some classes">'+uname+' '+vtitle+...whatever variable and format...+'</div>');
you can do this:
success: function(msg){
$.each(msg, function(i, item){
$('#divid').html('User Name : '+item.user_name+
'Video title : '+item.video_title+
'Video Id : 'item.video_id+
'Video Thumb : 'item.video_thumb );
});
}
I am using the following code to pull in data from my database and plot points with google maps. What I want to do is something like, "if response=null, alert('empty')" but everytime I try to work that into this code, something just breaks. If anyone could offer any help that would be awesome.
Here is my code:
<script type="text/javascript">
$(function ()
{
var radius3 = localStorage.getItem("radius2");
var lat3 = localStorage.getItem("lat2");
var long3 = localStorage.getItem("long2");
var type2 = localStorage.getItem("type2");
var citya = localStorage.getItem("city2");
var rep2 = localStorage.getItem("rep2");
var size2 = localStorage.getItem("size2");
var status2 = localStorage.getItem("status2");
$.ajax({
url: 'http://examplecom/test/www/base_search.php',
data: "city2=" + city2 + "&rep2=" + rep2 + "&status2=" + status2 + "&size2=" + size2 + "&type2=" + type2 + "&long2=" + long2 + "&lat2=" + lat2 + "&radius2=" + radius2,
type: 'post',
dataType: 'json',
success: function (data) {
if (data) {
$.each(data, function (key, val) {
var lng = val['lng'];
var lat = val['lat'];
var id = val['id'];
var name = val['name'];
var address = val['address'];
var category = val['category'];
var city = val['city'];
var state = val['state'];
var rep = val['rep'];
var status = val['status'];
var size = val['size'];
$('div#google-map').gmap('addMarker', {
'position': new google.maps.LatLng(lat, lng),
'bounds': true,
'icon': 'images/hospital.png'
}).click(function () {
$('div#google-map').gmap('openInfoWindow', {
'backgroundColor': "rgb(32,32,32)",
'content': "<table><tr><td>Name:</td><td>" + name + "</td></tr><tr><td>Address:</td><td>" + address + ", " + city + " " + state + "</td></tr><tr><td>Category:</td><td>" + category + "</td></tr><tr><td>Rep:</td><td>" + rep + "</td></tr><tr><td>Status:</td><td>" + status + "</td></tr><tr><td>Size:</td><td>" + size + "</td></tr></table>"
}, this);
});
} else {
alert('hello');
}
}
})
}
});
})
}
</script>
Something like
success: function (data) {
if(!data) {
alert('empty');
return;
}
$.each(data, function (key, val) { ...
should work.
Something like this!
success: function (data) {
if(data.length == 0) {
alert('empty');
return;
}
Something like this?
success: function (data) {
if(data){
//do your stuff here
}
else{
alert('empty');
}
}