How to get user profile Information from JSON API using Jquery? - javascript

I am creating a simple script to display a list of active users from JSON API if you click one of the listed users its should display user information eg username, name, description, city, email, avatar and a static map with the location selected With Google APIs for static maps.
What should I do to accomplish that?
I am able to get the list of active users, so far this is what I have done.
NOTE: I am a newbie.
$.getJSON('profile.json', function(data) {
var output = '<ul>';
$.each(data, function(key, val) {
//check the user if is active then display the active users
if(val['active'] == true)
{
output += '<li>'+ val.first_name + " " + val.last_name + " " + val.username +'</li>';
}
});
});
sample json.api
{"id":987,"username":"jstephensre","active":false,"password":"8de90ec658d72b54ef0b270611ef9eb6241fa59b77b5c98b9bffb4fd631a4b10","first_name":"Johnny","last_name":"Stephens","last_login":"6/7/2016","email":"jstephensre#opensource.org","avatar":"https://robohash.org/nihilpariaturrepudiandae.jpg?size=50x50&set=set1","gender":[],"favorites":{"book-isbn":"117187617-3","color":"#6adf06","drugs":["Zicam Cold Remedy Ultra Rapidmelts","BUTALBITAL, ACETAMINOPHEN AND CAFFEINE"]},"coordinates":{"lat":"8.65972","lng":"-75.12809"}},
{"id":988,"username":"dtorresrf","active":true,"password":"443f2261332613a2da952d05a25ceec2d8eb9ed177ce830b3b4d6fbbe536e2c0","first_name":null,"last_name":"Torres","last_login":null,"email":"atorresrf#facebook.com","avatar":"https://robohash.org/idnihilut.bmp?size=50x50&set=set1","gender":["Female","Female"],"favorites":{"book-isbn":null,"color":"#a04fce","drugs":["Cockroach, American","Lisinopril and Hydrochlorothiazide"]},"coordinates":{"lat":"9.86667","lng":"6.71667"}},
{"id":989,"username":"jsmithrg","active":false,"password":"4e9750746ad03f82717ebd702c03c92749de1cbc820798ab409fb5e6760101ad","first_name":null,"last_name":"Smith","last_login":null,"email":"tsmithrg#creativecommons.org","avatar":null,"gender":["Male"],"favorites":{"book-isbn":null,"color":"#3bff1e","drugs":["Yellow Pine","Meprobamate","GenRx Daily Defense Antifungal"]},"coordinates":{"lat":"-16.00528","lng":"-41.29722"}},
{"id":990,"username":"sroserh","active":false,"password":"ab83a77062c8ee868f3b966d50a8ee39f63e3cec81349b83b81adcd3c6fa5da3","first_name":"Sarah","last_name":null,"last_login":"12/19/2015","email":"sromerorh#about.me","avatar":null,"gender":[],"favorites":{"book-isbn":"117541910-9","color":"#ac8603","drugs":["MORUS ALBA POLLEN","enema","Altipres-B"]},"coordinates":{"lat":"32.26616","lng":"35.00893"}},
{"id":991,"username":"sholmesri","active":false,"password":"11802fc53531079cdf8033e6772ffc5ac47c8ea8a453b66e8ac8df9ae29d9543","first_name":"Susan","last_name":"Holmes","last_login":"1/28/2016","email":"sholmesri#mozilla.com","avatar":"https://robohash.org/doloreshicqui.png?size=50x50&set=set1","gender":["Male","Male"],"favorites":{"book-isbn":"658583882-3","color":"#04da21","drugs":["Tempra","Estradiol Transdermal System"]},"coordinates":{"lat":"-39.23686","lng":"-70.9197"}},
{"id":992,"username":"rhayesrj","active":true,"password":"beae358b1eb873bac4fa640410520157f26738ee4d2de1144f30101c6af8e259","first_name":"Rachel","last_name":"Hayes","last_login":"12/7/2015","email":null,"avatar":"https://robohash.org/teneturautest.jpg?size=50x50&set=set1","gender":["Male"],"favorites":{"book-isbn":"291847889-X","color":null,"drugs":["BUDESONIDE","Doxorubicin Hydrochloride","Hydrocodone Bitartrate and Acetaminophen"]},"coordinates":{"lat":"-20.58333","lng":"48.53333"}},
{"id":993,"username":"jcampbellrk","active":false,"password":"9602ccbe7599aefea9a25eb05ab2ede44302f57fd153bad07aa0f5a2f46be537","first_name":"Joan","last_name":"Campbell","last_login":"8/29/2016","email":"jcampbellrk#bravesites.com","avatar":"https://robohash.org/numquamutquae.png?size=50x50&set=set1","gender":["Male"],"favorites":{"book-isbn":"588841638-X","color":"#7c5963","drugs":[]},"coordinates":{"lat":"57.6531","lng":"14.6968"}},
{"id":994,"username":"ejamesrl","active":false,"password":"55b1d2418621cda82225bf569f5f30c5b5fcfe5ae7aef6b1e3418a97335b47ab","first_name":"Elizabeth","last_name":"James","last_login":"1/14/2016","email":"ejamesrl#geocities.jp","avatar":null,"gender":["Female"],"favorites":{"book-isbn":"026417147-0","color":"#ba1d5c","drugs":["Losartan Potassium and Hydrochlorothiazide","Ramipril"]},"coordinates":{"lat":"54.64043","lng":"32.87811"}},
{"id":995,"username":"krogersrm","active":true,"password":"c5a8921245a345fb133193f8ceb14021469b4f42a7d945e835b9497081fb7130","first_name":"Kathleen","last_name":null,"last_login":"6/13/2016","email":"khansenrm#nationalgeographic.com","avatar":"https://robohash.org/mollitiasuscipitmagnam.jpg?size=50x50&set=set1","gender":["Male"],"favorites":{"book-isbn":"636138809-3","color":"#1c858e","drugs":["Tramadol Hydrochloride","iBlanc Restora-Bright"]},"coordinates":{"lat":"12.71402","lng":"121.51242"}},
{"id":996,"username":"sperkinsrn","active":false,"password":"c0f48289a4145ffd34374f7236ea4e650df57cff11f4f77b865a44dde410cfb8","first_name":"Sarah","last_name":"Perkins","last_login":"8/31/2016","email":null,"avatar":"https://robohash.org/consequaturculpavelit.png?size=50x50&set=set1","gender":["Male","Male"],"favorites":{"book-isbn":"561211079-0","color":null,"drugs":["Caduet"]},"coordinates":{"lat":"43.30472","lng":"124.32778"}},
{"id":997,"username":"jlanero","active":false,"password":"0430117ff30143b0f3727527f62346351582a396cc60a5bf599e674cc34c07c5","first_name":"Jack","last_name":"Lane","last_login":"3/20/2016","email":null,"avatar":null,"gender":[],"favorites":{"book-isbn":"819102101-3","color":null,"drugs":["RIFAMPIN"]},"coordinates":{"lat":"51.8796","lng":"4.5059"}},
{"id":998,"username":"wroserp","active":true,"password":"626e6d1a1a92ff6e741ae21e3bbbae265000ca0f87306590c2344d4130dd57a9","first_name":"Willie","last_name":"Rose","last_login":"10/16/2016","email":null,"avatar":null,"gender":["Male"],"favorites":{"book-isbn":"108540866-3","color":null,"drugs":["OXYGEN","Garnier Fructis Antidandruff"]},"coordinates":{"lat":"57.58167","lng":"83.76917"}},
{"id":999,"username":"sphillipsrq","active":false,"password":"de0a87749bb04b2630ac6dbeb7259947383189afb6c2b458d80a15f6881b0439","first_name":"Stephanie","last_name":"Phillips","last_login":"11/24/2016","email":"sphillipsrq#wikia.com","avatar":"https://robohash.org/laborerepellendustemporibus.jpg?size=50x50&set=set1","gender":[],"favorites":{"book-isbn":"721916787-3","color":"#9eee74","drugs":[]},"coordinates":{"lat":"51.0016","lng":"21.71474"}},
{"id":1000,"username":"phicksrr","active":false,"password":"2a27d007956e55da298aa3fb427a5a8ed7a8d661f4d4a2e340a98026996521eb","first_name":"Phyllis","last_name":"Hicks","last_login":"2/14/2016","email":null,"avatar":"https://robohash.org/sedsednon.bmp?size=50x50&set=set1","gender":["Female","Female"],"favorites":{"book-isbn":"268196481-4","color":null,"drugs":["Ibuprofen"]},"coordinates":{"lat":"-6.22625","lng":"106.0253"}}]

1st : First set the unique id in href attribute
2nd : Onlcik of anchor tag prevent the default behaviour of anchor tag . and grab the id from href attribute .
3rd : Again loop the json data and compare with currently clicked id if it is current id then break the loop using return false; then prepare the information like below .
var data =[{"id":987,"username":"jstephensre","active":false,"password":"8de90ec658d72b54ef0b270611ef9eb6241fa59b77b5c98b9bffb4fd631a4b10","first_name":"Johnny","last_name":"Stephens","last_login":"6/7/2016","email":"jstephensre#opensource.org","avatar":"https://robohash.org/nihilpariaturrepudiandae.jpg?size=50x50&set=set1","gender":[],"favorites":{"book-isbn":"117187617-3","color":"#6adf06","drugs":["Zicam Cold Remedy Ultra Rapidmelts","BUTALBITAL, ACETAMINOPHEN AND CAFFEINE"]},"coordinates":{"lat":"8.65972","lng":"-75.12809"}},
{"id":988,"username":"dtorresrf","active":true,"password":"443f2261332613a2da952d05a25ceec2d8eb9ed177ce830b3b4d6fbbe536e2c0","first_name":null,"last_name":"Torres","last_login":null,"email":"atorresrf#facebook.com","avatar":"https://robohash.org/idnihilut.bmp?size=50x50&set=set1","gender":["Female","Female"],"favorites":{"book-isbn":null,"color":"#a04fce","drugs":["Cockroach, American","Lisinopril and Hydrochlorothiazide"]},"coordinates":{"lat":"9.86667","lng":"6.71667"}},
{"id":989,"username":"jsmithrg","active":false,"password":"4e9750746ad03f82717ebd702c03c92749de1cbc820798ab409fb5e6760101ad","first_name":null,"last_name":"Smith","last_login":null,"email":"tsmithrg#creativecommons.org","avatar":null,"gender":["Male"],"favorites":{"book-isbn":null,"color":"#3bff1e","drugs":["Yellow Pine","Meprobamate","GenRx Daily Defense Antifungal"]},"coordinates":{"lat":"-16.00528","lng":"-41.29722"}},
{"id":990,"username":"sroserh","active":false,"password":"ab83a77062c8ee868f3b966d50a8ee39f63e3cec81349b83b81adcd3c6fa5da3","first_name":"Sarah","last_name":null,"last_login":"12/19/2015","email":"sromerorh#about.me","avatar":null,"gender":[],"favorites":{"book-isbn":"117541910-9","color":"#ac8603","drugs":["MORUS ALBA POLLEN","enema","Altipres-B"]},"coordinates":{"lat":"32.26616","lng":"35.00893"}},
{"id":991,"username":"sholmesri","active":false,"password":"11802fc53531079cdf8033e6772ffc5ac47c8ea8a453b66e8ac8df9ae29d9543","first_name":"Susan","last_name":"Holmes","last_login":"1/28/2016","email":"sholmesri#mozilla.com","avatar":"https://robohash.org/doloreshicqui.png?size=50x50&set=set1","gender":["Male","Male"],"favorites":{"book-isbn":"658583882-3","color":"#04da21","drugs":["Tempra","Estradiol Transdermal System"]},"coordinates":{"lat":"-39.23686","lng":"-70.9197"}},
{"id":992,"username":"rhayesrj","active":true,"password":"beae358b1eb873bac4fa640410520157f26738ee4d2de1144f30101c6af8e259","first_name":"Rachel","last_name":"Hayes","last_login":"12/7/2015","email":null,"avatar":"https://robohash.org/teneturautest.jpg?size=50x50&set=set1","gender":["Male"],"favorites":{"book-isbn":"291847889-X","color":null,"drugs":["BUDESONIDE","Doxorubicin Hydrochloride","Hydrocodone Bitartrate and Acetaminophen"]},"coordinates":{"lat":"-20.58333","lng":"48.53333"}},
{"id":993,"username":"jcampbellrk","active":false,"password":"9602ccbe7599aefea9a25eb05ab2ede44302f57fd153bad07aa0f5a2f46be537","first_name":"Joan","last_name":"Campbell","last_login":"8/29/2016","email":"jcampbellrk#bravesites.com","avatar":"https://robohash.org/numquamutquae.png?size=50x50&set=set1","gender":["Male"],"favorites":{"book-isbn":"588841638-X","color":"#7c5963","drugs":[]},"coordinates":{"lat":"57.6531","lng":"14.6968"}},
{"id":994,"username":"ejamesrl","active":false,"password":"55b1d2418621cda82225bf569f5f30c5b5fcfe5ae7aef6b1e3418a97335b47ab","first_name":"Elizabeth","last_name":"James","last_login":"1/14/2016","email":"ejamesrl#geocities.jp","avatar":null,"gender":["Female"],"favorites":{"book-isbn":"026417147-0","color":"#ba1d5c","drugs":["Losartan Potassium and Hydrochlorothiazide","Ramipril"]},"coordinates":{"lat":"54.64043","lng":"32.87811"}},
{"id":995,"username":"krogersrm","active":true,"password":"c5a8921245a345fb133193f8ceb14021469b4f42a7d945e835b9497081fb7130","first_name":"Kathleen","last_name":null,"last_login":"6/13/2016","email":"khansenrm#nationalgeographic.com","avatar":"https://robohash.org/mollitiasuscipitmagnam.jpg?size=50x50&set=set1","gender":["Male"],"favorites":{"book-isbn":"636138809-3","color":"#1c858e","drugs":["Tramadol Hydrochloride","iBlanc Restora-Bright"]},"coordinates":{"lat":"12.71402","lng":"121.51242"}},
{"id":996,"username":"sperkinsrn","active":false,"password":"c0f48289a4145ffd34374f7236ea4e650df57cff11f4f77b865a44dde410cfb8","first_name":"Sarah","last_name":"Perkins","last_login":"8/31/2016","email":null,"avatar":"https://robohash.org/consequaturculpavelit.png?size=50x50&set=set1","gender":["Male","Male"],"favorites":{"book-isbn":"561211079-0","color":null,"drugs":["Caduet"]},"coordinates":{"lat":"43.30472","lng":"124.32778"}},
{"id":997,"username":"jlanero","active":false,"password":"0430117ff30143b0f3727527f62346351582a396cc60a5bf599e674cc34c07c5","first_name":"Jack","last_name":"Lane","last_login":"3/20/2016","email":null,"avatar":null,"gender":[],"favorites":{"book-isbn":"819102101-3","color":null,"drugs":["RIFAMPIN"]},"coordinates":{"lat":"51.8796","lng":"4.5059"}},
{"id":998,"username":"wroserp","active":true,"password":"626e6d1a1a92ff6e741ae21e3bbbae265000ca0f87306590c2344d4130dd57a9","first_name":"Willie","last_name":"Rose","last_login":"10/16/2016","email":null,"avatar":null,"gender":["Male"],"favorites":{"book-isbn":"108540866-3","color":null,"drugs":["OXYGEN","Garnier Fructis Antidandruff"]},"coordinates":{"lat":"57.58167","lng":"83.76917"}},
{"id":999,"username":"sphillipsrq","active":false,"password":"de0a87749bb04b2630ac6dbeb7259947383189afb6c2b458d80a15f6881b0439","first_name":"Stephanie","last_name":"Phillips","last_login":"11/24/2016","email":"sphillipsrq#wikia.com","avatar":"https://robohash.org/laborerepellendustemporibus.jpg?size=50x50&set=set1","gender":[],"favorites":{"book-isbn":"721916787-3","color":"#9eee74","drugs":[]},"coordinates":{"lat":"51.0016","lng":"21.71474"}},
{"id":1000,"username":"phicksrr","active":false,"password":"2a27d007956e55da298aa3fb427a5a8ed7a8d661f4d4a2e340a98026996521eb","first_name":"Phyllis","last_name":"Hicks","last_login":"2/14/2016","email":null,"avatar":"https://robohash.org/sedsednon.bmp?size=50x50&set=set1","gender":["Female","Female"],"favorites":{"book-isbn":"268196481-4","color":null,"drugs":["Ibuprofen"]},"coordinates":{"lat":"-6.22625","lng":"106.0253"}}];
var output = '<ul>';
$.each(data, function(key, val) {
if(val['active'] == true)
{
output += '<li><a class="new_href" href="'+val.id+'">'+ val.first_name + " " + val.last_name + " " + val.username +'</a></li>';
}
});
output +='</ul>';
$('#list').html(output);
$(document).on('click','.new_href',function(event){
event.preventDefault();
var current_id = $(this).attr('href');
var details='<ul>';
$.each(data, function(key, val) {
if(val['active'] == true && val['id']==current_id)
{
details+="<li>username : "+val['username']+" </li>";
details+="<li>firstname : "+val['first_name']+" </li>";
details+="<li>lastname : "+val['last_name']+" </li>";
details+="<li>email : "+val['email']+" </li>";
return false;
}
});
details+="</ul>";
$('#info').html(details);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="list">
</div>
<div id="info">
</div>

Related

Trying to get strings from specific sites (same domain) and place them in a chart

I have a chrome extension that, right now, is purely a cosmetic addition to a Counter-Strike forum and matchmaking site. I'm trying to implement some Javascript to show players ranks when looking at the statistics of a match. Currently, it looks like this: statistics page imgur
I'm trying to add a new column to the left of where players' names appear that shows their ranks. Ranks are currently only stored on the players' profile page, so I'm trying to write code that will go to each players' profile (currently hyperlinked to their name), get their rank and display that as text.
I have 0 understanding of Javascript despite trying to learn it many times but this is a heavily requested feature and I'd like to implement it for my users.
sample statistics page
sample profile page
As of a few months ago, the following code worked:
function findRanks(i) {
var allUsers = $(document).find("#body-match-total" + i + " tr");
$.each($(document).find("#body-match-total" + i + " tr"), function(index, value){
var userLink = "https://play.esea.net/users/" + allUsers[index].children[0].children[1].innerHTML
$.get(userLink, function(data) {
var parsed = $('<div/>').append(data);
rank = $(parsed).find("#rankGraph h1").text();
allUsers[index].children[0].children[1].innerHTML += " (" + rank + ") ";
});
});
}
findRanks(1);
findRanks(2)
Was missing a bracket. Thanks to some random guy on ESEA forums for the help.
Here is the functional code for people with the same issue
function findRanks(i) {
var allUsers = $(document).find("#body-match-total" + i + " tr");
$.each($(document).find("#body-match-total" + i + " tr"), function(index, value){
var userLink = "https://play.esea.net/users/" + allUsers[index].children[0].children[1].innerHTML
$.get(userLink, function(data) {
data = data.replace(/<img[^>]*>/g,"");
var parsed = $('<div/>').append(data);
rank = $(parsed).find("#rankGraph h1").text();
allUsers[index].children[0].children[1].innerHTML += " (" + rank + ") ";
});
});
}
findRanks(1);
findRanks(2);

How do I move 1 object in an array to another array in javascript and then show both in a listview ( jquery )

So for a school assignment I need to write a basic mobile web application, using jquery and javascript. I need to make a page where you can add a title and author of a book and add it to a list using local storage. So far so good but I want to make 2 lists, one for books to read and one for read books. Now I made the listview with a split icon so when it's clicked that book should move to the other list. That listview contains also a split icon which should remove the book in it's whole.
The adding part is working and the added books are displayed in the listview but I can't seem to get the button working to change the list the book is in. Please help me I'm loosing my mind. Here is my html and javascript code:
<!-- OVERVIEW -->
<section id="overview" data-role="page" data-theme="b">
<!-- CONTENT -->
<div class="ui-content">
<div>
Add a new book
<h1>Books to read</h1>
</div>
<ul id="booksToRead" data-role="listview" data-split-icon="check" data-theme="b" data-split-theme="b" data-inset="true"></ul>
<h1>Read books</h1>
<ul id="readBooks" data-role="listview" data-split-icon="delete" data-theme="b" data-split-theme="b" data-inset="true"></ul>
</div>
</section>
And the javascript code
function add() {
// Retrieve the entered form data
var title = $('[name="bookTitle"]').val();
var author = $('[name="bookAuthor"]').val();
var book = {title:title, author:author};
// Fetch the existing books to read
var booksToRead = getObjects("booksToRead");
// Push the new item into the existing list
booksToRead.push(book);
// Store the new list
saveObjects(booksToRead, "booksToRead");
//reset textfields
$('[name="bookTitle"]').val('');
$('[name="bookAuthor"]').val('');
// Load the page with all the books
window.location.href = "#overview";
}
function getObjects(name) {
// See if objects are inside localStorage
if (localStorage.getItem(name)) {
// If yes, then load the objects
var objects = JSON.parse(localStorage.getItem(name));
} else {
// Make a new array of objects
var objects = new Array();
}
return objects;
}
function saveObjects(objects, name) {
// Save the list into localStorage
localStorage.setItem(name, JSON.stringify(objects));
}
function read(dit){
var readBooks = getObjects("readBooks");
var booksToRead = getObjects("booksToRead");
var book = booksToRead[dit];
// Push the new item into the existing list
readBooks.push(book);
// Store the new list
saveObjects(readBooks, "readBooks");
//Delete from the old list
deleteme(dit, "booksToRead");
//Reload page
window.location.reload();
}
function deleteme(dit, listName) {
// Fetch existing objects
var objects = getObjects(listName);
// Delete given object from list
objects.splice(dit, 1);
// Save list
saveObjects(objects, listName);
//Reload page
window.location.reload();
}
function loadPage() {
// Fetch the existing objects
var booksToRead = getObjects("booksToRead");
var readBooks = getObjects("readBooks");
// Clear the lists
$('#booksToRead').find('li').remove();
$('#readBooks').find('li').remove();
// Add every object to the objects list
$.each(booksToRead, function(index, item) {
var title = item.title;
var author = item.author;
$('#booksToRead').append('<li><a>' + title + ' - ' + author + '</a><a class="read" onclick="read(' + booksToRead.index + ')" data-transition="none"></a></li>');
});
$.each(readBooks, function(index, item) {
var title = item.title;
var author = item.author;
var listName ="readBooks";
$('#readBooks').append('<li><a>' + title + ' - ' + author + '</a><a class="delete" onclick="delete(' + readBooks.index + ', ' + listName + ')" data-transition="none"></a></li>');
});
$('#booksToRead').listview();
$('#booksToRead').listview("refresh");
$('#readBooks').listview();
$('#readBooks').listview("refresh");
}
$(document).on('pagebeforeshow', '#overview', function(event) {
loadPage();
});
I've think i got your error, in your $.each loop try removing your
booksToRead.index
// and
readBooks.index
for just
index
So, your $.each loops will look like that:
$.each(booksToRead, function(index, item) {
var title = item.title;
var author = item.author;
$('#booksToRead').append('<li><a>' + title + ' - ' + author + '</a><a class="read" onclick="read(' + index + ')" data-transition="none">ddddd</a></li>');
});
$.each(readBooks, function(index, item) {
var title = item.title;
var author = item.author;
var listName ="readBooks";
$('#readBooks').append('<li><a>' + title + ' - ' + author + '</a><a class="delete" onclick="delete(' + index + ', ' + listName + ')" data-transition="none"></a></li>');
});
Your are trying to get the property "index" of the object booksToRead while what you need to do is get the index param property of the $.each loop function, so you will get the correct index of the book you want to move.
You don't get error in the console because booksToRead.index === undefined and don't generates any exception, so, your index become ..."onclick="read(undefined)"...
Hope i've helped, good luck with your project!

javascript not adding html div to string

I'm working with a wordpress plugin called Wordpress Simple Paypal Shopping Cart, when the form is sent it starts this script. It takes a product, and three dropdown and puts them into a format in one string like this:
SHOP ITEM (dropdown1) (dropdown2) (dropdown3)
Here is the code.
<script type="text/javascript">
<!--
//
function ReadForm (obj1, tst)
{
// Read the user form
var i,j,pos;
val_total="";val_combo="";
for (i=0; i<obj1.length; i++)
{
// run entire form
obj = obj1.elements[i]; // a form element
if (obj.type == "select-one")
{ // just selects
if (obj.name == "quantity" ||
obj.name == "amount") continue;
pos = obj.selectedIndex; // which option selected
val = obj.options[pos].value; // selected value
val_combo = val_combo + " (" + val + ")";
}
}
// Now summarize everything we have processed above
val_total = obj1.product_tmp.value + val_combo;
obj1.product.value = val_total;
}
//-->
</script>';
I need to change the output so I can style the three options with specific CSS. The output in HTML is in a span.
I notice the line val_combo = val_combo + " (" + val + ")"; adds the brackets around the output so I tried to change it to val_combo = val_combo + " <div>" + val + "</div>"; but the output strips the divs, leaving the output like:
SHOP ITEM dropdown1 dropdown2 dropdown3
I'm not clever with Javascript so any examples as if for a child would be highly appreciated.

How to parse a JSON response in jQuery?

I'm creating a small web-app for my girlfriend and I that will allow us to keep track of the movies we want to watch together. To simplify the process of adding a movie to the list, I'm trying to use TheMovieDatabase.org's API (supports JSON only) to allow us to search for a movie by title, let the database load a few results, and then we can choose to just add a movie from the database or create our own entry if no results were found.
I'm using jQuery to handle everything and, having never used JSON before, am stuck. I wrote a short bit of code to get the JSON based on my search query, and am now trying to populate a <ul> with the results. Here's what I have.
var TMDbAPI = "https://api.themoviedb.org/3/search/movie";
var moviequery = $("#search").val();
var api_key = "baab01130a70a05989eff64f0e684599";
$ul = $('ul');
$.getJSON( TMDbAPI,
{
query: moviequery,
api_key: api_key
},
function(data){
$.each(data, function(k,v) {
$ul.append("<li>" + k + ": " + v + "</li>");
}
);
});
The JSON file is structured as
{
"page":1,
"results":[
{
"adult":false,
"backdrop_path":"/hNFMawyNDWZKKHU4GYCBz1krsRM.jpg",
"id":550,
"original_title":"Fight Club",
"release_date":"1999-10-14",
"poster_path":"/2lECpi35Hnbpa4y46JX0aY3AWTy.jpg",
"popularity":13.3095569670529,
"title":"Fight Club",
"vote_average":7.7,
"vote_count":2927
}, ...
"total_pages":1,
"total_results":10
}
but all I'm getting is
page: 1
results: [object Object], ...
total_pages: 1
total_results: 10
I've searched quite extensively on the Internet for a solution, but with the little knowledge I have of JSON I wasn't able to learn much from the various examples and answers I found scattered about. What do?
It looks like what you'd like to do is write out some properties of each movie in the list. This means you want to loop over the list in data.results, like this:
// Visit each result from the "results" array
$.each(
data.results,
function (i, movie) {
var $li = $('<li></li>');
$li.text(movie.title);
$ul.append($li);
}
);
This will make a list of movie titles. You can access other properties of movie inside the each function if you want to show more elaborate information.
I added the title to the li using $li.text rather than simply doing $('<li>' + movie.title + '</li>') since this will avoid problems if any of the movie titles happen to contain < symbols, which could then get understood as HTML tags and create some funny rendering. Although it's unlikely that a movie title would contain that symbol, this simple extra step makes your code more robust and so it's a good habit to keep.
You need to traverse the results object. In the $.each function change data for data.results
You can use a simple for loop to iterate over the list/array. in the example below i am appending a list item containing the value of the key results[i].title. you can append the values of as many valid keys as you would like to the div.
var TMDbAPI = "https://api.themoviedb.org/3/search/movie";
var moviequery = $("#search").val();
var api_key = "baab01130a70a05989eff64f0e684599";
$ul = $('ul');
$.getJSON( TMDbAPI,
{query: moviequery,api_key: api_key},function(data){
var results = data.results;//cast the data.results object to a variable
//iterate over results printing the title and any other values you would like.
for(var i = 0; i < results.length; i++){
$ul.append("<li>"+ results[i].title +"</li>");
}
});
html
<input id="search" type="text" placeholder="query" />
<input id="submit" type="submit" value="search" />
js
$(function () {
$("#submit").on("click", function (e) {
var TMDbAPI = "https://api.themoviedb.org/3/search/movie";
var moviequery = $("#search").val();
var api_key = "baab01130a70a05989eff64f0e684599";
$.getJSON(TMDbAPI, {
query: moviequery,
api_key: api_key
},
function (data) {
$("ul").remove();
var ul = $("<ul>");
$(ul).append("<li><i>total pages: <i>"
+ data.total_pages + "\n"
+ "<i>current page: </i>"
+ data.page
+ "</li>");
$.each(data.results, function (k, v) {
$(ul).append("<li><i>title: </i>"
+ v.original_title + "\n"
+ "<i>release date: </i>" + v.release_date + "\n"
+ "<i>id: </i>" + v.id + "\n"
+ "<i>poster: </i>"
+ v.poster_path
+ "</li>");
});
$("body").append($(ul))
});
});
});
jsfiddle http://jsfiddle.net/guest271314/sLSHP/

Saving JQuery-UI Sortable Connected Lists Custom Configuration to Local Cookie

Please Skip to Update #2 at the Bottom if you don't want to read the whole post.
I have created a customizable UI using jquery-ui connected lists:
http://jqueryui.com/sortable/#connect-lists
I now want to save the user's configuration of the UI to a cookie on their local machine so that the next time they load the page the layout they previously setup will be loaded, as discussed on this page:
http://devheart.org/articles/jquery-customizable-layout-using-drag-and-drop/
The problem is that after discussing how to save the custom configuration of multiple connected lists in part 2 of his writeup, he neglects to include multiple connected lists in part 3 where he implements the code into an actual design. I have been able to get everything on my page to work like the final example on that page, but whenever I try to modify the code to work with connected lists the page no longer works.
I understand the basic idea behind what the code is doing, but I don't know JavaScript and have had no success in modifying the code to work with connected lists. I'm hoping that someone who does know JavaScript will be able to easily modify the code below to work with connected lists like part 2 does.
Part 2 saves the order of multiple connected lists, but doesn't load external html pages with the corresponding name.
Part 3 loads external html pages with the corresponding names of the item, but only supports a single list.
Code for Connected Lists from Part 2:
// Load items
function loadItemsFromCookie(name)
{
if ( $.cookie(name) != null )
{
renderItems($.cookie(name), '#wrapper');
}
else
{
alert('No items saved in "' + name + '".');
}
}
// Render items
function renderItems(items, container)
{
var html = '';
var columns = items.split('|');
for ( var c in columns )
{
html += '<div class="column"><ul class="sortable-list">';
if ( columns[c] != '' )
{
var items = columns[c].split(',');
for ( var i in items )
{
html += '<li id="' + items[i] + '">Item ' + items[i] + '</li>';
}
}
html += '</ul></div>';
}
$('#' + container).html(html);
}
Code from part 3 that does not support connected lists (Trying to modify this to support connected lists):
// Get items
function getItems(id)
{
return $('#' + id + '-list').sortable('toArray').join(',');
}
// Render items
function renderItems(id, itemStr)
{
var list = $('#' + id + '-list');
var items = itemStr.split(',')
for ( var i in items )
{
html = '<li class="sortable-item';
if ( id == 'splash' )
{
html += ' col3 left';
}
html += '" id="' + items[i] + '"><div class="loader"></div></li>';
list.append(html);
// Load html file
$('#' + items[i]).load('content/' + items[i] + '.html');
}
}
Update #1:
I think I almost have it, I just can't get it to insert html from the external html files. It was able to get it to insert variables and plain text, just not the external html.
// Render items
function renderItems(items)
{
var html = '';
var columns = items.split('|');
for ( var c in columns )
{
html += '<div class="column';
if ( c == 0 )
{
html += ' first';
}
html += '"><ul class="sortable-list">';
if ( columns[c] != '' )
{
var items = columns[c].split(',');
for ( var i in items )
{
html += '<li class="sortable-item" id="' + items[i] + '">';
//---------This Line Isn't Working--------->
$('#' + items[i]).load(items[i] + '.html');
//---------This Line Isn't Working--------->
html += '</li>';
}
}
html += '</ul></div>';
}
$('#example-2-3').html(html);
}
Update #2:
I've been looking up exactly what each JavaScript command in the example does and I think I've figured out the problem. I can't just load the page, I need to append the code from the external page to the html variable. I think I need to use the .get command, something like:
var pagedata = '';
.get(items[i] + '.html', function(pagedata);
html += pagedata;
Anyone know what the correct syntax to accomplish this would be?
I finally got the code to work. Here is the full code (not including jquery-ui related code). External pages need to be named the same as the list id.
HTML
<div id="example-2-3">
<div class="column first">
<ul class="sortable-list">
<li class="sortable-item" id="id1"></li>
<li class="sortable-item" id="id2"></li>
<li class="sortable-item" id="id3"></li>
</ul>
</div>
<div class="column">
<ul class="sortable-list">
<li class="sortable-item" id="id4"></li>
</ul>
</div>
<div class="column">
<ul class="sortable-list">
<li class="sortable-item" id="id5"></li>
<li class="sortable-item" id="id6"></li>
</ul>
</div>
</div>
Script
$(document).ready(function(){
window.onload = loadItemsFromCookie('cookie-2');
// Get items
function getItems(exampleNr)
{
var columns = [];
$(exampleNr + ' ul.sortable-list').each(function(){
columns.push($(this).sortable('toArray').join(','));
});
return columns.join('|');
}
// Load items from cookie
function loadItemsFromCookie(name)
{
if ( $.cookie(name) != null )
{
renderItems($.cookie(name));
}
else
{
alert('No items saved in "' + name + '".');
}
}
// Render items
function renderItems(items)
{
var html = '';
var pagedata = '';
var columns = items.split('|');
for ( var c in columns )
{
html += '<div class="column';
if ( c == 0 )
{
html += ' first';
}
html += '"><ul class="sortable-list">';
if ( columns[c] != '' )
{
var items = columns[c].split(',');
for ( var i in items )
{
html += '<li class="sortable-item" id="' + items[i] + '">';
var pagedata = '';
var scriptUrl = items[i] + ".html"
$.ajax({
url: scriptUrl,
type: 'get',
dataType: 'html',
async: false,
success: function(data) {
result = data;
html += data;
}
});
html += '</li>';
}
}
html += '</ul></div>';
}
$('#example-2-3').html(html);
}
$('#example-2-3 .sortable-list').sortable({
connectWith: '#example-2-3 .sortable-list',
update: function(){
$.cookie('cookie-2', getItems('#example-2-3'));
}
});
});
</script>

Categories