Because my other question, didn't solved my issue, and i tried everything what i know, and every time i am getting more stuck. Please combine this question with my other.
I am building my movie library.And i have two pages, index and movie.html.
Index.html will a page where will display movie items, each item, will have a name, a picture, score, short summary and director and screenplay names.And, also i will have a name from author, if the movie is based from book. All of that is taken from JSON file, that i have created locally.
In other html page, movie.html, i am planning to have more fancy design with more information. Like:wins, synopsis,cast and their characters, etc.
But here is the problem i am facing.
What I have tried:
I have this so far in
index.html
$( document ).ready( function () {
$.getJSON( "js/appjson.json", function ( data ) {
for ( var i = 0; i < data.length; i++ ) {
for ( var key in data[ i ] ) {
if ( key === "novel" ) {
$( '#jsonLoad' ).append( '<a href="movies.html?id='+data[i].id'" class="itemsHolder">' +
"<div class="titleHolder">" +
"<h2>" + data[ i ].name + "</h2>" +
"</div>" +
"<div class="novelAuthor">" + "<p class="NovelTxt">" + "Novel by" + " " + data[ i ].novel +"</p>" + "</div> " +
"<div class="posterHolder">" + data[ i ].posterPath + "</div>" +
"<div class="summaryShort">" + data[ i ].summary + "</div>" +
"<div class="raiting"><p>" + data[ i ].imdb + "</p></div><div class="genderMovie"> " + data[ i ].gender + "</div> " +
"<div class="directorNdScreen">" + 'Directed by ' + " <p class="director">" + data[ i ].director + '</p>' + ' ' + ' Screenplay by ' + "<p class="screenplay">" + data[ i ].screenplay + "</p>" + "</div>"
+ "</a>" )
}
}
if(!data[i].novel){
$( '#jsonLoad' ).append( '<a href="movies.html?id='+data[i].id+'" class="itemsHolder">' +
"<div class="titleHolder">" +
"<h2>" + data[ i ].name + "</h2>" +
"</div>" +
"<div class="posterHolder">" + data[ i ].posterPath + "</div>" +
"<div class="summaryShort">" + data[ i ].summary + "</div>" +
"<div class="raiting"><p>" + data[ i ].imdb + "</p></div><div class="genderMovie"> " + data[ i ].gender + "</div> " +
"<div class="directorNdScreen">" + 'Director by ' + " <p class="director">" + data[ i ].director + '</p>' + ' ' + ' Screenplay by ' + "<p class="screenplay">" + data[ i ].screenplay + "</p>" + "</div>"
+ "</a>" )
}
}
} )
} );
My JSON file, i have 20 objects, i will post just 2.
[
{
"id": 1,
"name": "Harry potter and the Sorcerer's Stone",
"year": 2001,
"movieStill" : " <img src='imgsMovie/HP1/StillPhoto/StillPhotoBackground.jpg'/>",\
},
{
"id": 2,
"name": "Harry potter and the Chamber of Secrets ",
"year": 2001,
"movieStill" : " <img src='imgsMovie/HP2/StillPhoto/StillPhotoBackground.jpg'/>",\
}
]
And my movie.html looks like this.
$( document ).ready( function () {
$.getJSON( "js/appjson.json", function ( data ) {
for ( var i = 0; i < data.length; i++ ) {
$( '.MovieInfo' ).append(
"<div class="imgStill">" + data[ i ].movieStill + "</div>"
)
}
} );
} );
I know in my movie.html i loop in every object.
How can i write an if statement, that will take per one object with own id, and display what is there.
Here, when i click on Harry potter 1 item, i got two images, from hp1 and hp2,
i just want to show only the one value from item i have clicked. And this means also for the rest of the properties, like different director etc, just to name a few.
It looks like in your movie.html you are just appending the images to .MovieInfo, which would not separate them out but have them all lumped together. You can instead read the id of from the data argument and only display the id associated with the movie you clicked.
Since you are already passing in a GET query to the url (movies.html?id=) you can just grab the value of id from the GET query and start with that (let's call it getID() for now). Afterwards just wrap the .MovieInfo append statement with an if statement checking the data argument for that value.
$.getJSON( "js/appjson.json", function ( data ) {
for ( var i = 0; i < data.length; i++ ) {
if (data[i].id === getID()) {
$( '.MovieInfo' ).append(
"<div class="imgStill">" + data[ i ].movieStill + "</div>"
)
}
}
});
Related
I try make a poll, basically I refresh my petition every 3s to the API using jsonp and getJSON the problem is my view also refresh at the same time and blink in the interface of the client (HTML), I have some like this
var chatbox = $("#chatbox");
singleChatView();
setInterval(function () {
chatbox.empty();
singleChatView();
}, 1000);
function singleChatView() {
var chatid = localStorage.getItem('chatid');
$.getJSON("http://myapi/?chatid=" + chatid + "&jsonp=?", function (chats) {
console.log(chats);
$.each(chats.DATA, function (key, c) {
$('.msgRecipientName').text(c.SENTBY.name);
if (c.SENTBY.id == userInfo.PROFILE.USERID) {
chatbox.append(
"<li class='msgThread group currentUser'>" +
"<div class='msgBalloon group'>" +
"<div class='msgHeader'>" +
"<div class='msgFull'>" + c.MESSAGE + "</div>" +
"</div>" +
"</div>" +
"<div class='msgDate'>" +
formatDate(c.CREATEDON) +
"</div>" +
"</li>"
);
} else {
chatbox.append(
"<li class='msgThread group'>" +
"<div class='msgAuthor' style='background: #fff url(myapi/100_couple.png) 50% background-size: cover;'>" +
"<a ng-href=''>" +
"<span></span>" +
"</a>" +
"</div>" +
"<div class='msgBalloon group'>" +
"<div class='msgHeader'>" +
"<div class='msgFrom'>" + c.SENTBY.name + "</div>" +
"<div class='msgFull'>" + c.MESSAGE + "</div>" +
"</div>" +
"</div>" +
"<div class='msgFrom'>" + c.SENTBY.name + "</div>" +
"<div class='msgDate'>" + formatDate(c.CREATEDON) + "</div>" +
"</li>"
);
}
});
});
}
I don't have any idea how I can do this and void this issue with the view, can some one help me, all this is new for me thanks
I would suggest trying the following. The blink is most likely due to you clearing the chatbox and not putting anything in there until the ajax returns. This version, aside from reducing the number of times the DOM is changed, also doesn't replace the chatbox until it has built all the html that should be in it.
var chatbox = $("#chatbox");
//start the chat loop
singleChatView();
function singleChatView() {
var chatid = localStorage.getItem('chatid');
$.getJSON("http://myapi/?chatid=" + chatid + "&jsonp=?", function(chats) {
console.log(chats);
//collect the messages
//if we update the page once, the browser has to do less work rendering
//all the changes
var messages = [];
//keep track of the "c.SENTBY.name"
//since you are doing a global selector and setter, the value will
//end up being the last value you update all them to be anyway
//no need to update multiple times
var sendby = '';
$.each(chats.DATA, function(key, c) {
sentby = c.SENTBY.name;
if (c.SENTBY.id == userInfo.PROFILE.USERID) {
messages.push(
"<li class='msgThread group currentUser'>" +
"<div class='msgBalloon group'>" +
"<div class='msgHeader'>" +
"<div class='msgFull'>" + c.MESSAGE + "</div>" +
"</div>" +
"</div>" +
"<div class='msgDate'>" + formatDate(c.CREATEDON) + "</div>" +
"</li>"
);
} else {
messages.push(
"<li class='msgThread group'>" +
"<div class='msgAuthor' style='background: #fff url(myapi/100_couple.png) 50% background-size: cover;'>" +
"<a ng-href=''>" +
"<span></span>" +
"</a>" +
"</div>" +
"<div class='msgBalloon group'>" +
"<div class='msgHeader'>" +
"<div class='msgFrom'>" + c.SENTBY.name + "</div>" +
"<div class='msgFull'>" + c.MESSAGE + "</div>" +
"</div>" +
"</div>" +
"<div class='msgFrom'>" + c.SENTBY.name + "</div>" +
"<div class='msgDate'>" + formatDate(c.CREATEDON) + "</div>" +
"</li>"
);
}
});
//update the recipent with the last sent by, once
$('.msgRecipientName').text(sentby);
//replace all the chatbox text with the collected html that would have
//otherwise been append one at a time
chatbox.html(messages);
//now that we've finished this iteration, start the next iteration after
//a second
setTimeout(singleChatView, 1000);
});
}
I'm trying to nest 3 divs within a "row" div.
I had this working in "long format" (multiple var's instead of looping through the array). I've refactored my code and now I don't get any error codes AND my code does not append to the HTML file. When I console log I get an array with 3 objects. I'm sure i'm missing something minor.
Anyways some help would be great!
<div class="row">
**nested divs go here.
</div>
$(document).ready(function() {
$.get("http://api.openweathermap.org/data/2.5/forecast/daily?id4726206&cnt=3", {
APPID: "MY API KEY",
lat: 29.423017,
lon: -98.48527,
units: "imperial"
}).done(function(data) {
var stationId = data.city.name;
// Stattion Name
$('#station').append(stationId);
//console.log(data);
var forecast = data.list;
//Wind Direction in Compass Format
function getDirection(dir) {
var compass = ['N', 'NNE', 'NE', 'ENE', 'E', 'ESE', 'SE', 'SSE', 'S', 'SSW', 'SW', 'WSW', 'W', 'WNW', 'NW', 'NNW'];
var result = Math.floor((360 - dir) / 22.5);
return compass[result];
}
//Forecast Variables
$.each(forecast, function(i, v) {
var html = '';
html += "<div class='col-sm-3 wInfo'>" + "<div class='title'>High / Low</div>";
html += "<div class='cTemp'>" + (Math.ceil(forecast[i].temp.max)) + '°';
html += " / " + (Math.ceil(forecast[i].temp.min)) + '°' + "</div>";
html += "<div class='tempIcon'>" + "<img src='http://openweathermap.org/img/w/" + forecast[i].weather[0].icon;
html += ".png' alt=''></div>" + "<div class='conditions' id='castId'>" + '<span class="cond">' + forecast[i].weather[0].main;
html += "</span>: " + "<span>" + forecast[i].weather[0].description + '</span>' + "</div>";
html += "<div class='conditions'>" + "<span class='cond'>Humidity: </span>" + "<span>" + forecast[i].humidity + "%</span></div>";
html += "<div class='conditions'>" + "<span class='cond'>Wind: </span>" + "<span>" + (Math.floor(forecast[i].speed));
html += " mph / " + getDirection(forecast[i].deg) + "</span></div>" + "<div class='conditions'>";
html += "<span class='cond'>Pressure: </span>" + "<span>" + forecast[i].pressure + "</span></div>";
return html;
});
$('.forecast').append(forecast);
console.log(forecast);
});
});
You are trying to append the array forecast in html. which wont work. You should declare the html variable outside and then use it in append function.
I will also recommend to use string builder logic using array and then convert it to string and append it. remember string concatenation is heavy operator as it creates new instance of elememt every time concatenation is done :
var html = [];
$.each(forecast, function(i, v) {
html.push("<div class='col-sm-3 wInfo'>" + "<div class='title'>High / Low</div>");
html.push("<div class='cTemp'>" + (Math.ceil(forecast[i].temp.max)) + '°');
html.push(" / " + (Math.ceil(forecast[i].temp.min)) + '°' + "</div>");
html.push("<div class='tempIcon'>" + "<img src='http://openweathermap.org/img/w/" + forecast[i].weather[0].icon);
html.push(".png' alt=''></div>" + "<div class='conditions' id='castId'>" + '<span class="cond">' + forecast[i].weather[0].main);
html.push("</span>: " + "<span>" + forecast[i].weather[0].description + '</span>' + "</div>");
html.push("<div class='conditions'>" + "<span class='cond'>Humidity: </span>" + "<span>" + forecast[i].humidity + "%</span></div>");
html.push("<div class='conditions'>" + "<span class='cond'>Wind: </span>" + "<span>" + (Math.floor(forecast[i].speed)));
html.push(" mph / " + getDirection(forecast[i].deg) + "</span></div>" + "<div class='conditions'>");
html.push("<span class='cond'>Pressure: </span>" + "<span>" + forecast[i].pressure + "</span></div></div>");
});
$('.forecast').append(html.join(""));
I am working with a JSON DB and displaying ingredients on the page. I have a separate HTML page for each recipe. I am creating an unordered list on the page and manually typing in the recipe ingredients for the recipe on the page.
I am trying to pull in the recipe name from the DB but I cant get it to show. I want to pull in the correct item if it matches the item UPC in the DB. Please see below.
$(document).ready(function() {
'use strict';
$.ajax({
dataType: "jsonp",
url: '',
success: function(data){
$.each(data, function(i, item) {
$('#recipeIngredients').html(
"<ul>" +
"<li>" + '1/2 tsp sugar' + "</li>" +
"<li>" + '1/2 tsp salt' + "</li>" +
"<li>" + '3 tbsp ' + (item.itemFullUPC == "070796150062" ? item.itemName : "" ) + "</li>" +
"<li>" + '1 pkg active dry yeast' + "</li>" +
"<li>" + '3/4 cup warm water' + "</li>" +
"<li>" + '2 tbsp ' + (item.itemFullUPC == "070796150012" ? item.itemName : "" ) + "</li>" +
"<li>" + '2 cups shredded mozzarella cheese' + "</li>" +
"</ul>"
);
});
} }) });
You're overwriting the HTML every time through the loop, so the final result will just be from the last item in the array.
Instead, you should use an if statement, and only display the items that matches the UPC code you want.
Then you should use .append() rather than .html() so you add the <ul> to the list, instead of overwriting it.
$.each(data, function(i, item) {
if (item.itemFullUPC == "070796150012") {
$('#recipeIngredients').append(
"<ul>" +
"<li>" + '1/2 tsp sugar' + "</li>" +
"<li>" + '1/2 tsp salt' + "</li>" +
"<li>" + '1/2 tsp salt' + "</li>" +
"<li>" + '1 pkg active dry yeast' + "</li>" +
"<li>" + '3/4 cup warm water' + "</li>" +
"<li>" + '2 tbsp ' + item.itemName + "</li>" +
"<li>" + '2 cups shredded mozzarella cheese' + "</li>" +
"</ul>"
);
}
});
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
I'm in the midst of learning how to code.
The code below shows what happens after I click a button - a jQuery post() call is made which submits the data to a PHP form and then displays the result from the database query into a div.
The code is fine, but I'm simply wondering if there's any way to make it better.
By better, I mean if there is any way to make the code more readable, faster, and less buggy.
$.post("load_product.php", {'ID': IDname}, function(json) {
var product_details_array = $.parseJSON(json);
var test_for_null = product_details_array[0];
if ( test_for_null.length > 0)
{
$('#product_tags_container').append(
"<div class='product_tags'>" + "<img id='remove_tag' src='../function icons/cross.png'>" + "<div id='product_texture_picture'>" + "<img src='" + "product_pictures/" + product_details_array[4] + product_details_array[5] + "'>" + "</div>" + "<div id='product_title'>" + product_details_array[0] + "</div>" + "<br><br>" + "<div id='product_brand'>" + product_details_array[6] + "</div>" + "<div id='product_price'>"+ product_details_array[3] + "</div>" + "</div>");
}
});
I cleaned up all the unnecessary concatenation within your append function. The append function is too long to maintain in my opinion. I'm guessing your server side responses
No response: ''
JSON array is null: null
JSON array is empty: []
$.post("load_product.php", {
id: IDname
}).done(function(data) {
if (data.length>0 && data!=null && data!='[]') {
var product_details_array = $.parseJSON(data);
$('#product_tags_container').append("<div class='product_tags'><img id='remove_tag' src='../function icons/cross.png'><div id='product_texture_picture'><img src='product_pictures/" + product_details_array[4] + product_details_array[5] + "'></div><div id='product_title'>" + product_details_array[0] + "</div><br><br><div id='product_brand'>" + product_details_array[6] + "</div><div id='product_price'>" + product_details_array[3] + "</div></div>");
}
}
});
You don't have to use this, but if I had to 'remake' this code, I'd do it like this:
$.post("load_product.php", {'ID': IDname}, function(json) {
var product_details_array = $.parseJSON(json);
if (product_details_array[0].length > 0) {
$('#product_tags_container').append(
"<div class='product_tags'>" +
"<img id='remove_tag' src='../function icons/cross.png'>" +
"<div id='product_texture_picture'>" +
"<img src='" + "product_pictures/" + product_details_array[4] + product_details_array[5] + "'>" +
"</div>" +
"<div id='product_title'>" + product_details_array[0] + "</div>" +
"<br><br>" +
"<div id='product_brand'>" + product_details_array[6] + "</div>" +
"<div id='product_price'>" + product_details_array[3] + "</div>" +
"</div>");
}
});
In my opinion this is more readable. If I had to read your 1-line html code I'd re-format it to look like the example I gave first. If you or anyone else has to make an edit it would be easier to do like this.
EDIT:
function assembleProductHTML(product_details_array) {
return "<div class='product_tags'>" +
"<img id='remove_tag' src='../function icons/cross.png'>" +
"<div id='product_texture_picture'>" +
"<img src='" + "product_pictures/" + product_details_array[4] + product_details_array[5] + "'>" +
"</div>" +
"<div id='product_title'>" + product_details_array[0] + "</div>" +
"<br><br>" +
"<div id='product_brand'>" + product_details_array[6] + "</div>" +
"<div id='product_price'>" + product_details_array[3] + "</div>" +
"</div>";
}
$.post("load_product.php", {'ID': IDname}, function(json) {
var product_details_array = $.parseJSON(json);
if (product_details_array[0].length > 0) {
$('#product_tags_container').append(assembleProductHTML(product_details_array));
}
});
this is my code.
i need address of lan and lat.how do it?
following code is not working.why?
i included.
http://maps.googleapis.com/maps/api/js?libraries=places,geometry&sensor=true"
function maps(latss,lngss)
{
var lat=latss;
var lng=lngss;
var places = new google.maps.places.PlacesService( document.createElement( 'div' ) ),
searchRequest = {
location: new google.maps.LatLng(lat,lng),
radius: 500
};
places.search( searchRequest, function ( results, status ) {
var html = '';
for ( var index = 0; index < results.length; index++ ) {
html +=
'<li '
+ 'data-location-id="' + results[index].id + '" '
+ 'data-address="' + results[index].vicinity + '" '
+ 'data-latitude="' + results[index].geometry.location.lat() + '" '
+ 'data-longitude="' + results[index].geometry.location.lng() + '" '
+ 'data-name="' + results[index].name + '">'
+ '<div>' + results[index].name + '</div>'
+ '<div>' + results[index].vicinity + '</div>'
+ '</li>';
};
document.getElementById( 'results' ).innerHTML = html;
} );
The script as it is works, issues may be:
the search didn't give any result(check the status)
the target-element(document.getElementById( 'results' )) is unknown at the time you try to access it
latss and lngss are not valid values vor a LatLng
However, your debugger should give you more information.
Note: the page must contain a "powered by google"-logo when you use places-results without a google-map.