Generating a List and Subsequent Pages from JSON - javascript

In my project, I have a JSON file. I display the data that is parsed inside a list (ul) under a div with the class, "inner", and show only the name and cost of each product that you can see in my JSON.
{
"product": [
{
"name": "samsung galaxy",
"image": "https://rukminim1.flixcart.com/image/832/832/mobile/v/z/x/samsung-galaxy-on-nxt-sm-g610fzdgins-original-imaenkzvmnyf7sby.jpeg?q=70",
"cost": "RS.10,000",
"detail": "Flaunt your style with the Samsung Galaxy On Nxt. Featuring a drool-worthy body and impressive features, this smartphone is built to perform. Talk to your mom, chat with your friends, browse the Internet - stay connected the way that suits you best - this smartphone is powerful enough to keep up with your busy lifestyle."
}
]
}
When I click on the first product (first list item), I want to show the detail (value detail) of this product in another page from that same JSON object; when I click on the second product, I want that to show in a different page too, but also from that same object.
Here's my HTML:
<html>
<head>
<title>jquery</title>
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
$.ajax({
url: 'http://sonsofthunderstudio.in/jj/product.json',
dataType: 'jsonp',
jsonpCallback: 'jsonCallback',
type: 'get',
crossDomain : true,
cache: false,
success: function(data) {
$(data.product).each(function(index, value) {
console.log(value);
$( ".inner" ).append("<li>"+value.name+"<img src='" + value.image + "' width='50px' height='50px' / >"+value.cost+"</li>");
});
}
});
</script>
<div class="inner">
</div>
</body>
</html>
Where can I go from here?

When you want to show details of your product, You have to create a "ProductList.html" to show your product list, and create a "ProductDetail.html" to show product detail based on selected product.
when user click on a product, You have to pass the selected product to "ProductDetail.html" via url and get it in that page.
the 2 "encodeURIComponenet()" and "decodeURIComponent()" are javascript defined functions to make this action encoded and safe.
To achieve this, You have to append a "Link"(A Tag) to $(".inner"):
$(".inner").append("<a href='#'>"+value.name+"</a>");
in code above, you create a link, you pass the Product ID to destination page and In codes below, You set the "href" attribute for the link:
var _SelectedProduct = "ID=" + ProductID;
var _EncodeID = encodeURIComponenet(_SelectedProduct);
document.getElementById("YourLink").href = "ProductDetail.html?" + _EncodeID;
with these codes, when user click on a product, he will be redirected to "ProductDetail.html" with the selected product ID. You can get this ID in Your ProductDetail.js:
var _DecodeURL = decodeURIComponent(window.location);
var ID = _DecodeURL.split("=");
var _ProductID = ID[1];
with these codes, you split the passed url base on ("="), which means you will get the passed Product ID.(_ProductID).
and :
for(i=0;i<=product.lenght; i++){
if(product[i].ID == _ProductID){ ... }
}

You can add onclick event on li and call a function which will store the particular detail in localStorage.
On the next page you can access detail from localStorage and display it.
//--[Appending in your code]--
.
.
.
$(data.product).each(function(index, value) {
console.log(value);
$( ".inner" ).append("<li onclick='foo('"+value.detail+"')'>"+value.name+"<img src='" + value.image + "' width='50px' height='50px' / >"+value.cost+"</li>");
});
<script type="text/javascript">
function foo(detail)
{
localStorage.setItem("DETAIL",detail);
}
</script>
//--[On second page]--
<head>
<script type="text/javascript">
var detail = localStorage.getItem("DETAIL");
$("#details").html(detail);
</script>
</head>
<body>
<div id="details"></div>
</body>

When you append data first you need to do is to add an Identifier because you need to differentiate the elements and you need to put onClick to each element that you will append you can put it like this: '<li id="'+ index +'" onClick="clicklist(this)">'+ value.name (...) +'</li>'
The second thing you need to declare is a function called clicklist or something with the param element.
function clicklist(element) { }
Fill it with the code I will explain now:
You can access to your list data through the element with your jQuery functions. So first you can get id with var id = $(element).attr('id'); then you can find your list elements and get it value with var itemname = $(element).find("typeofelement.class").attr('value'); etc...
When you get all data in your list you need to open a new window with the params you get in the function. Then use this code:
//Add all the values you need in the other html (id and values) So repeat this line:
sessionStorage.setItem("ID", id);
//Open the window
window.open("yourother.html","_blank");
This is the simple way.

Related

How to avoid appending duplicates on ajax after second call?

I have a button called File which is a dropdown that has another button called open. Once the user clicks open I have an ajax GET request that appends a button after each call.
When the user clicks open once, the button is appended. However, when the user clicks open again, the same button is appended again with the same attributes and if the user clicks the open button the third time the button is appended once more, so a total of three times.
How do I ensure the button is only appended once?
The {{}} is from the django web framework and is not a concern
<input type = "button" class = "openGraph" value = "{{titles}}" id="{% url 'openGraph' title=titles.id %}">
This is the occurence when the user presses the open button.
$(document).ready(function(){
$('#openXML').on('click',function(event){
var csrftoken = getCookie('csrftoken');
$.ajax({
type: "GET",
url: "/loadTitles/",
dataType: 'text',
headers:{
"X-CSRFToken": csrftoken
},
success: function(data){
var json = JSON.parse(data)
var length = Object.keys(json).length
var pk = "/openGraph/" + json[length-1]['pk']
var title = json[length-1]['fields']['title']
myButton="<input type=\"button\" class = \"openGraph\" value=\""+title+"\" id="+pk+"/\>";
$("#loadAllTitles").append(myButton)
}
});
})
});
Because the IDs must be unique I'd suggest to test if the button already exist before adding. Hence, you need to change this line:
$("#loadAllTitles").append(myButton)
with:
if ($("#loadAllTitles").find('#' + $.escapeSelector(pk + '/')).length == 0)
$("#loadAllTitles").append(myButton)
I get the following console error: Uncaught Error: Syntax error, unrecognized expression: #/openGraph/104 –
If you are using jQuery 3.x you need to use:
jQuery.escapeSelector(): Escapes any character that has a special meaning in a CSS selector.
UPDATE
While pk is the ID when you create a new element you add to this ID a final /. This is your issue.
$('button').on('click', function(e) {
var pk = '#/openGraph/104';
var title='title';
myButton="<input type=\"button\" class = \"openGraph\" value=\""+title+"\" id="+pk+"/\>";
if ($("#loadAllTitles").find('#' + $.escapeSelector(pk + '/')).length == 0)
$("#loadAllTitles").append(myButton)
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="loadAllTitles">
</form>
<button type="button">Click to add the same input field</button>
Check for the presence of a button on line 3
$(document).ready(function(){
$('#openXML').on('click',function(event){
if (!$('#+pk+').length) {
// Your code
}
}
}

Get certain json values and displaying on html page

I made a small webpage that asks the user to enter the name of an actor and I was hoping to then display all of the movies the actor had appeared in. For my question, I've hard coded the api URL for the actor (Bradley Cooper).
How do I grab all of the movie titles, the release year, movie overview, and the movie poster value and display them all on the page? Right now, I'm only able to display one movie and for some strange reason, it's not the first movie mentioned in the json file.
I think I need to get the json data into an array but I'm not sure how to do that and I'm not sure how to then display more than one result on the page.
I appreciate any help and guidance you can provide.
<!DOCTYPE html>
<html>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body onload="search_actor()">
<script>
function search_actor() {
$.getJSON({
url: 'https://api.themoviedb.org/3/person/51329/movie_credits?api_key=f1d314280284e94ff7d1feeed7d44fdf',
dataType: 'json',
type: 'get',
cache: false,
success: function(data) {
$(data.cast).each(function(index, moviedata) {
// Movie Title
document.getElementById("movietitle").innerHTML = moviedata.title;
// Release Year
document.getElementById("releaseyear").innerHTML = moviedata.release_date.substr(0, 4);
// Movie Overview
document.getElementById("movieoverview").innerHTML = moviedata.overview;
// Movie Poster
var fullmovieposterpath = '<img src=https://image.tmdb.org/t/p/w500/' + moviedata.poster_path + ' width="20%" height="20%">';
document.getElementById("displaymovieposter").innerHTML = fullmovieposterpath;
});
}
});
}
</script>
<div id="movietitle"></div>
<div id="releaseyear"></div>
<div id="movieoverview"></div>
<div id="displaymovieposter"></div>
</body>
</html>
In your code you have single only one container to display the movie items.You need to loop over the response and dynamically create the movie cards.Also use css grid system to have more control over the movie card and their placement.
$.getJSON({
url: 'https://api.themoviedb.org/3/person/51329/movie_credits?api_key=f1d314280284e94ff7d1feeed7d44fdf',
dataType: 'json',
type: 'get',
cache: false,
success: function (data) {
console.log(data)
let k = '';
data.cast.forEach(function (item) {
//Using template literal to create a movie card
k += `<div class='movie-card'>
<div>${item.original_title}</div>
<div><img src = 'https://image.tmdb.org/t/p/w500/${item.poster_path}'></div>
<div><span>${item.release_date}</span></div>
<div class='movie-desc'>${item.overview}</div>
</div>`
})
$('.movie-conatiner').append(k)
}
});
See complete working copy here at stackblitz
Currently, you are displaying data in single division, so data is getting overwritten.
Instead you need to dynamically build division in for each statement and then assign the entire data in home page.
Also create only single div in html part with id="main"
Below is the updated code with above change. Please give proper CSS to the divisions.
Code after getting json response
divcnt=1;
divdata="";
$(data.cast).each(function(index, moviedata) {
var fullmovieposterpath = '<img src=https://image.tmdb.org/t/p/w500/' + moviedata.poster_path + ' width="20%" height="20%">';
divdata += '<div id="test'+ divcnt +'"><div id="movietitle'+ divcnt +'">'+moviedata.title+'</div><div id="releaseyear'+ divcnt +'">'+moviedata.release_date.substr(0, 4)+'</div><div id="movieoverview'+ divcnt +'">'+moviedata.overview+'</div><div id="displaymovieposter'+ divcnt +'">'+fullmovieposterpath+'</div></div>';
});
document.getElementById("main").innerHTML = divdata;

JQuery how to click html element to copy into text area?

Is it possible to click text in a list to add into a text box. I have made a JSON api that gets a list of people in the database. I then have a form that has a text field and displays the list of people. I would like to click a particular person and add it to the text box.
main.js
var ajax_call = function() {
var $people = $('#people');
$.ajax({
type: 'GET',
url: '/all/api',
success: function(people) {
$.each(people, function(i, person) {
$people.empty()
});
$.each(people, function(i, person) {
$people.append('<li>name: ' + person.first_name+', last: '+ person.last_name + '</li>');
});
}
});
$("#people").on("click", "li", function() {
var content = $(this).html();
//$("#testbox").val(content); //replace existing name in textbox
$("#testbox").val($("#testbox").val() + content + "\n"); //add new name to textbox
});
};
var interval = 800;
setInterval(ajax_call, interval);
form.html
<form id="textbox" action="" method="post">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="create" />
</form>
<ul id="people"></ul>
Try this "click" function attached to the ul but filtered by the li's (this allows the list to remain dynamic), it allows you to add the individual names (two versions one that overwrites the existing textfield info and the second that appends to it): DEMO
$("#people").on("click", "li", function() {
var content = $(this).html();
//$("#testbox").val(content); //replace existing name in textbox
$("#testbox").val($("#testbox").val() + content + "\n"); //add new name to textbox
});
I think the answer to your question is pretty easy.
In your code you have the line
$("#people").keyup(function() {
Which is probably not what you wanted to do, cause now you are waiting for a keyup (release of a key) event on a list. First of all your question stated that you want the user to click and not to press a button and second you want the list items not the list itself.
So IMO you have to change that part to something like:
$("li","#people").click(function(){
var content = this.html();
$("#testbox").val(content);
});
Try this :
replace this
$("#people").keyup(function() {
var content = $('#people').html();
$("#testbox").val(content);
});
with this
$("#people").click(function() {
var content = $('#people').html();
$("#testbox").val(content);
});
If I have understood your question right away then
$("#people").click(function(){
var content = $('#people').html();
$("#testbox").val(content);
});
should do the work. But I think you should use something like custom attribute instead of id as there can be only one id for a specific tag.

jQuery EasyUI accordion content from php

Once again I humbly come before you with bruises upon my head from beating my head against a wall...
I have been trying to learn as I go in figuring out how to populate a jQuery EasyUI accordion from a php/MySQL query. I believe that I am now getting the data back to the webpage correctly, but I am unable to figure out how to parse and format this to be displayed as the content on the page. What I am attempting to achieve is basically an accordion to display the contact history with each correspondence with an individual as an accordion item. Here is a sample of the output from the PHP query.
{"rows":[{"phone":"5554072634","contact_dt":"2014-01-27 22:51:37","method":"Email","who":"Scott","note":""},{"phone":"5554072634","contact_dt":"2014-01-27 23:08:49","method":"Spoke","who":"Scott","note":"Called back and she is not interested."}]}
I am trying to get the "contact_dt" as the title of each accordion tab and then format the rest of the elements in the body of the accordion tabs. Currently I'm getting a busy spinner when I select the Contact History tab that contains the accordion but this only yields a tiny square box in the body and does not alter the title. Here is the code that I'm sure I have mangled. First for the HTML portion...
<div id="history" title="Prospect Contact History" closable="true" style="padding:10px;">
<h2 class="atitle">Prospect Details</h2>
<div id="aa" class="easyui-accordion" style="width:500px;height:300px;">
<div title="Title1" data-options="iconCls:'icon-save'" style="overflow:auto;padding:10px;">
<h3 id="hist_title" style="color:#0099FF;">Accordion for jQuery</h3>
<p>Accordion is a part of easyui framework for jQuery.
It lets you define your accordion component on web page more easily.</p>
</div>
</div>
</div>
Now for the jQuery pieces... First is the JS to basically call the function. This is in the body at the end of the page.
<script type="text/javascript">
$('#tt').tabs({
onSelect:function(title){
if (title == 'Prospect Contact History'){
//$( "#hist_title" ).html( "Accordion function is working.");
accordionHistory();
}
}
});
</script>
Now for the function that is defined in the head and where I think the real mess is at.
function accordionHistory() {
$( "#hist_title" ).html( "Accordion function is working.");
var pp = $('#aa').accordion('getSelected'); // get the selected panel
if (pp){
pp.panel('refresh','contact_history.php?phone=' + phone); // call 'refresh' method to load new content
var temp = $('#aa').form('load',pp);
$.each( temp, function( i, val ) {
var txt1=$("<p>Time: ").html(val.contact_dt);
var txt2=$("</p><p>Method: ").html(val.method);
var txt3=$("</p><p>Who: ").html(val.who);
var txt4=$("</p><p>Note: ").html(val.note);
//$("#hist_title").html(val.contact_dt);
$("#hist_item").html(txt2,txt3,txt4);
});
}
}
I'm sure I'm displaying gross ignorance here in basic JS concepts. As I mentioned at the beginning I'm really using this as a learning exercise as well as building something useful. Any help would be greatly appreciated. Additionally, any online tutorials that might help walk me thru some of my conceptual shortcomings would be most welcome. Thanks in advance.
Well... I finally have figured out my issues. Here is the function that I'm now using to get this working.
function accordionHistory() {
var pp = $('#aa').accordion('getSelected'); // get the selected panel
if (pp){
$.ajax({
post: "GET",
url: "get_history.php?phone=" + phone,
dataType: 'json',
success: function( details ) {
$.each(details.rows, function(index, element) {
$('#hist_title').replaceWith(
'Phone: '
+ element.phone
+ 'Contact time: '
+ this.contact_dt
+ '<br/>Method: '
+ this.method
+ '<br/>Who: '
+ this.who
+ '<br/>Note: '
+ this.note
);
});
}
});
}
}
I hope some other noob like myself finds this useful.

Change javascript onclick event to jquery click and still pass parameters

I think I may be missing something or haven't grasped a fundamental of jQuery. I have searched for hours but yet to find an answer to my question.
I've got an old website that I'm upgrading to use jQuery and many of the links call a JavaScript onClick call that passes multiple parameters, as per the example below:
View Details
The problem is that I've updated the old displayData function with various jQuery code and the displayData function is within the
$(document).ready(function() {
});
code, and this seems to prevent the function displayData being called using the onClick as it says object expected. I've moved the displayData function out from the $(document).ready() but by doing so, this has prevented references to other functions within the $(document).ready() code being referenced.
A cut down example of what I have is below:
<script>
$(document).ready(function() {
function displayData(title, isbn, dt, price) {
// there's a call to jQuery AJAX here
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "WebServices/BookService.asmx/GetBookReviews",
data: "{isbn: '" + isbn + "'}",
dataType: "json",
success: function(msg) {
DisplayReviews(msg.d);
}
});
return false;
}
function DisplayReviews(data) {
// data normally formatted here and passed to formattedData variable
var formattedData = FormatData(data);
$('#reviewScreen').html(formattedData);
}
function FormatData(data) {
// function reformats data... code removed for space..
return data;
}
});
</script>
<table>
<tr><td>View Reviews</td><td>Book Title</td></tr>
<tr><td>View Reviews</td><td>Book Title 2</td></tr>
</table>
What I'd like to do is to be able to remove the onclick="displayData();" within the link and instead us a jQuery click reference, something like
$('a.reviewLink').click(function() {
displayData(parameters go here....);
});
I just don't know how I'd pass the parameters to the function from the link as they would not longer be in the HTML onclick attribute.
If I continue to use the onclick attribute in the link, and move the displayData(params) out of the $(document).ready() code block, it works fine, but the moment I try and reference any of the other functions within the $(document).ready() code block I get the dreaded object expected error with the other functions such as DisplayReviews(param).
I don't know if this makes any sense.... sorry if it's confusing, I'm not the worlds best programmer and don't know all the terminology necessarily, so have tried as best I can to explain. I hope you can help.
Many thanks
The init code should go into the .ready(), not your library functions, those can be defined in a seperate .js file.
<script src="yourFunctions.js"></script>
<script>
$(document).ready(function(){
$('a.reviewLink').click(function() {
displayData(parameters go here....); // in yourFunctions.js
});
});
</script>
An alternative to passing inline parameters without using inline javascript, is to use HTML5's 'data-' attribute on tags. You can use it in xhtml, html etc as well and it just works.
html:
<div data-name="Jack" data-lastname="black">My name is</div>
jquery:
$('div').click(function(){
alert($(this).attr('data-name') + ' ' + $(this).attr('data-lastname'));
});
Note: You HAVE to use either jQuery's .attr() or native .getAttribute() method to retreive 'data-' values.
I use 'data-' myself all the time.
As pointed out by Skilldrick, displayData doesn't need to be defined inside your document ready wrapper (and probably shouldn't be).
You are correct in wanting to use the jQuery click event assignment rather than onClick - it makes your code easier to read, and is required by the principle of Unobtrusive Javascript.
As for those parameters that you want to pass, there are a few ways to go about the task. If you are not concerned with XHTML compliance, you could simply put some custom attributes on your link and then access them from your script. For example:
View Details
And then in your click event:
$('a.reviewLink').click(function() {
var booktitle = $(this).attr('booktitle');
var isbn = $(this).attr('isbn');
var pubdate = $(this).attr('pubdate');
var price = $(this).attr('price');
displayData(booktitle, isbn, pubdate, price);
});
I'm sure someone on here will decry that method as the darkest evil, but it has worked well for me in the past. Alternatively, you could follow each link with a hidden set of data, like so:
View Details
<ul class="book-data">
<li class="book-title">Book Title</li>
<li class="book-isbn">ISBN</li>
<li class="book-pubdate">Publish Date</li>
<li class="book-price">Price</li>
</ul>
Create a CSS rule to hide the data list: .book-data { display: none; }, and then in your click event:
$('a.reviewLink').click(function() {
var $bookData = $(this).next('.book-data');
var booktitle = $bookData.children('.book-title').text();
var isbn = $bookData.children('.book-isbn').text();
var pubdate = $bookData.children('.book-pubdate').text();
var price = $bookData.children('.book-price').text();
displayData(booktitle, isbn, pubdate, price);
});
There are lots of ways to accomplish your task, but those are the two that spring most quickly to mind.
I worked this up, so even though the question is answered, someone else might find it helpful.
http://jsbin.com/axidu3
HTML
<table border="0" cellspacing="5" cellpadding="5">
<tr>
<td>
View Reviews
<div class="displayData">
<span class="title">Book Title 2</span>
<span class="isbn">516AHGN1515</span>
<span class="pubdata">1999-05-08</span>
<span class="price">$25.00</span>
</div>
</td>
<td>Book Title 2</td>
</tr>
</table>
JavaScript
<script type="text/javascript" charset="utf-8">
jQuery(".reviewLink").click(function() {
var title = jQuery(".title", this.parent).text();
var isbn = jQuery(".isbn", this.parent).text();
var pubdata = jQuery(".pubdata", this.parent).text();
var price = jQuery(".price", this.parent).text();
displayData(title, isbn, pubdata, price);
});
function displayData(title, isbn, pubdata, price) {
alert(title +" "+ isbn +" "+ pubdata +" "+ price);
}
</script>
CSS
<style type="text/css" media="screen">
.displayData {
display: none;
}
</style>

Categories