I'm not any good at JavaScript (yet!) - I really need some help to get past this stuck point that is causing me lots of premature hair loss!
I just can't seem to figure out how to build the following HTML code using JSON data.
This is a sample of the JSON data that I have being generated for the new version of this page I'm working on:
[{"id":"1732","name":"1BR House","checkin":"2012-12-20","checkout":"2012-12-23","inclean_cleaner":"","inclean_datetime":"0000-00-00 00:00:00","inclean_notes":""},{"id":"1587","name":1BR House","checkin":"2012-12-23","checkout":"2013-01-01","inclean_cleaner":"","inclean_datetime":"0000-00-00 00:00:00","inclean_notes":""},{"id":"1661","name":"2BR Studio","checkin":"2012-12-25","checkout":"2013-01-02","inclean_cleaner":"","inclean_datetime":"0000-00-00 00:00:00","inclean_notes":""},{"id":"1829","name":"Studio Cottage","checkin":"2012-12-25","checkout":"2012-12-29","inclean_cleaner":"","inclean_datetime":"0000-00-00 00:00:00","inclean_notes":""},{"id":"1787","name":"Studio Cottage","checkin":"2012-12-29","checkout":"2013-01-08","inclean_cleaner":"","inclean_datetime":"2012-12-29 00:00:00","inclean_notes":""},{"id":"1843","name":"1BR House","checkin":"2013-01-07","checkout":"2013-01-19","inclean_cleaner":"","inclean_datetime":"0000-00-00 00:00:00","inclean_notes":""},{"id":"1970","name":"Studio Cottage","checkin":"2013-01-12","checkout":"2013-01-19","inclean_cleaner":"","inclean_datetime":"0000-00-00 00:00:00","inclean_notes":""},{"id":"1942","name":"Suite","checkin":"2013-01-15","checkout":"2013-01-20","inclean_cleaner":"","inclean_datetime":"0000-00-00 00:00:00","inclean_notes":""}]
To illustrate the HTML result I need, here is how I currently do it without JSON (strictly in PHP):
<div class="'.$dashboard_list_line_class.'">
<div class="dashboard_list_unitname"> '.$unit_name.'</div>
<div class="dashboard_list_cleaner_datetime"> '.$inclean_datetime.'</div>
<div class="dashboard_list_cleaner_checkin"> '.$checkin.'</div>
<div class="dashboard_list_cleaner_checkout"> '.$checkout.'</div>
<div class="dashboard_list_cleaner_inclean_cleaner"> '.$inclean_cleaner.'</div>
<div class="dashboard_list_cleaner_notes"> '.$inclean_notes.'</div>
</div>
What would the code look like in jQuery or JavaScript to grab the JSON, iterate though the arrays and create the same result as the PHP I have shown? I've been trying for hours, and get different results of puling data - but I just can't make it work.
Thanks for your help!
Here is you complete solution:
$.ajax( "example.php" ).done(function (response) {
//var data = [{"id":"1732","name":"1BR House","checkin":"2012-12-20","checkout":"2012-12-23","inclean_cleaner":"","inclean_datetime":"0000-00-00 00:00:00","inclean_notes":""},{"id":"1587","name":"1BR House","checkin":"2012-12-23","checkout":"2013-01-01","inclean_cleaner":"","inclean_datetime":"0000-00-00 00:00:00","inclean_notes":""},{"id":"1661","name":"2BR Studio","checkin":"2012-12-25","checkout":"2013-01-02","inclean_cleaner":"","inclean_datetime":"0000-00-00 00:00:00","inclean_notes":""},{"id":"1829","name":"Studio Cottage","checkin":"2012-12-25","checkout":"2012-12-29","inclean_cleaner":"","inclean_datetime":"0000-00-00 00:00:00","inclean_notes":""},{"id":"1787","name":"Studio Cottage","checkin":"2012-12-29","checkout":"2013-01-08","inclean_cleaner":"","inclean_datetime":"2012-12-29 00:00:00","inclean_notes":""},{"id":"1843","name":"1BR House","checkin":"2013-01-07","checkout":"2013-01-19","inclean_cleaner":"","inclean_datetime":"0000-00-00 00:00:00","inclean_notes":""},{"id":"1970","name":"Studio Cottage","checkin":"2013-01-12","checkout":"2013-01-19","inclean_cleaner":"","inclean_datetime":"0000-00-00 00:00:00","inclean_notes":""},{"id":"1942","name":"Suite","checkin":"2013-01-15","checkout":"2013-01-20","inclean_cleaner":"","inclean_datetime":"0000-00-00 00:00:00","inclean_notes":""}];
var data = $.parseJSON(response);
var dashboard_list_unitname = 'change_this';
var booking_id = 'also_change_this';
$(data).each(function (i, row) {
$(row).each(function (j, col) {
var html = '<div class="row_' + i + '">' +
'<div class="' + dashboard_list_unitname + '"> ' + col.name + '</div>' +
'<div class="dashboard_list_cleaner_datetime"> ' + col.inclean_datetime + '</div>' +
'<div class="dashboard_list_cleaner_checkin"> ' + col.checkin + '</div>' +
'<div class="dashboard_list_cleaner_checkout"> ' + col.checkout + '</div>' +
'<div class="dashboard_list_cleaner_inclean_cleaner"> ' + col.inclean_cleaner + '</div>' +
'<div class="dashboard_list_cleaner_notes"> ' + col.inclean_notes + '</div>' +
'</div>';
$('body').append($(html));
});
});
});
jQuery templates can help here.
http://api.jquery.com/jquery.tmpl/ shows several examples of a template being populated from a JSON-like data bundle, and the {{each}} element allows you to iterate over lists to populate rows and cells.
Template:
<li>
Title: ${Name}.
{{each Languages}}
${$index + 1}: <em>${$value}. </em>
{{/each}}
</li>
Data:
var movies = [
{ Name: "Meet Joe Black", Languages: ["French"] },
{ Name: "The Mighty", Languages: [] },
{ Name: "City Hunter", Languages: ["Mandarin", "Cantonese"] }
];
Everyone seems to be assuming knowledge of AJAX calls. It's not complicated, here is an example,
$.get('json/url', function(json_data) {
// do stuff with your data
// like, other people suggested json_data.each(function(item) {
// do stuff
// });
});
You can learn more about it straight from the jQuery docs,
http://api.jquery.com/jQuery.get/
If you need to make a post request just consult the jQuery docs for post, or for the more general article, the jQuery docs for AJAX calls: http://api.jquery.com/jQuery.ajax/.
var table = '';
$.each(json_data, function(index, obj) {
table += '<div>';
for(var x in obj) {
table += '<div class="dashboard_list_unitname"> '+ obj[x]+'</div>';
}
table += '</div>';
});
Related
Currently making a website to index and play movies stored on my hard drive that I've recently pulled off dvds just as a little side project. I have a 'master movie list' JSON file with all the data I need for each movie including the name, video source, video poster source, and genre which I would like to allow the use of placing a movie in multiple different genres.
Currently the problem I'm having is while I'm parsing through the genre list generated its not placing the html in the correct ID that id like it to on the webpage.
For example:
"genre":"comedy,recent,scifi"
I went about it how I thought I should, through getJSON and setting an output variable to which I get the genre value, split to make it an array, and get the element by going through each of them in a loop. Its not placing it in the right place though. The example above would be placed in comedy, recent, scifi, horror, and a few others for some reason and I have absolutely no reason why.
$.getJSON('/webresource/data/movies.json', function(data) {
console.log(data);
var output = '';
var ele = $('');
$.each(data, function(key, val) {
output += '<div class="video_box lazy-background" video-src="' +
val.video_src + '" video-poster-src="' +
val.video_poster_src + '">' +
'<h5>' + val.name + '</h5>' +
'</div> ';
var genres = val.genre;
var genresarray = genres.split(',');
for (i = 0; i < genresarray.length; i++) {
var genreelement = $('#' + genresarray[i]);
genreelement.html(output);
}
});
});
[ {
"name": "a star is born", "video_src":"/files/movies/A%20Star%20Is%20Born/astarisborn.mp4", "video_poster_src":"https://images-na.ssl-images-amazon.com/images/I/51R-TU6VaTL.jpg", "genre":"recently,romance,drama"
}
] // this is an example of the json
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="genre_box">
<h3>RECENTLY ADDED</h3>
<div class="scroll_box" id="recently"></div>
</div>
<div class="genre_box">
<h3>ACTION</h3>
<div class="scroll_box" id="action"></div>
</div>
<div class="genre_box">
<h3>COMEDY</h3>
<div class="scroll_box" id="comedy"></div>
</div>
Your output variable is being appended to and kept on every iteration of your $.each loop. What you want is to append to the end of $("#action"), $("#comedy"), etc. You should do something along these lines:
$.getJSON('/webresource/data/movies.json', function(data) {
console.log(data);
$.each(data, function(key, val) {
var output = '<div class="video_box lazy-background" video-src="' +
val.video_src + '" video-poster-src="' +
val.video_poster_src + '">' +
'<h5>' + val.name + '</h5>' +
'</div> ';
var genres = val.genre;
var genresarray = genres.split(',');
for (var i = 0; i < genresarray.length; i++) {
var genreelement = $('#' + genresarray[i]);
genreelement.append(output);
}
});
});
I have an array in a JSON file and what I want to do is pull a single entry from the array and display it when the page loads.
I have gotten partway there using this question and answer, however my attempt to adapt this answer causes the output html block to repeat the array items in sequence instead of simply picking one.
Here is a screenshot of what I get:
screenshot of output
I am likely doing something real stupid, and I hope someone can point this out.
My script is as follows:
$.getJSON('recommend.json', function(data) {
var entry = data[Math.floor(Math.random()*data.length)];
$.each(data, function(entryIndex, entry) {
var html = '<div class="rec_img"><img src="./recs/' + entry['img'] + '" /></div>';
html += '<span class="rec_title">' + entry['title'] + '</span><p>';
html += '<span class="rec_author">' + entry['author'] + '</span><p>';
html += '<span class="rec_blurb">' + entry['blurb'] + '</span>';
$('#recblock').append(html).fadeIn();
});
});
Any questions just let me know.
Cut this:
$.each(data, function(entryIndex, entry) {
The whole purpose of $.each is to iterate over the entire array, which is the opposite of what you want. You're already defining entry earlier as a random entry from the data.
So you'll have:
$.getJSON('recommend.json', function(data) {
var entry = data[Math.floor(Math.random()*data.length)];
var html = '<div class="rec_img"><img src="./recs/' + entry['img'] + '" /></div>';
html += '<span class="rec_title">' + entry['title'] + '</span><p>';
html += '<span class="rec_author">' + entry['author'] + '</span><p>';
html += '<span class="rec_blurb">' + entry['blurb'] + '</span>';
$('#recblock').append(html).fadeIn();
});
I have the following bit of data(JSON) stored in a session:
Prescription: [{"medID":"id1","medName":"name1","medQty":"qty1","medDirec":"Directions1"}, {"medID":"id2","medName":"name2","medQty":"qty2","medDirec":"Directions2"}]
I want to get these information automatically "displayed" inside a Listview (jQuery Mobile) on page load, for this I have come up with the following:
$(document).ready(function () {
window.addEventListener('load', OnStorage, false);
});
function OnStorage(event) {
if (window.sessionStorage) {
var retrievedData = sessionStorage.getItem("Prescription");
var PrescriptionJSON = JSON.parse(retrievedData);
var prescLength = PrescriptionJSON.Length();
for (var i = 0; i < PrescriptionJSON.Length(); i++) {
var text = '<h2>' + PrescriptionJSON[i].medName + '</h2>' +
'<p><strong>Quantity: </strong>' + PrescriptionJSON[i].medQty + '</p>' +
'<p><strong>Directions: </strong>' + PrescriptionJSON[i].medDirec + '</p>'
$('<li />', {
html: text
}).appendTo("#summaryList ul");
//$("#summaryList").append(text);
//alert(retrievedData);
}
$('#summaryList').listview("refresh");
$('#summaryList').trigger("create");
}
}
When I uncomment //alert(retrievedData); I get the JSON inside an alert popup, but when I call //alert(PrescriptionJSON); (the parsed variable) I get something like [object, Object]. Nonetheless, I don't know if this is worth mentioning but just in case I am.
Basically I don't know what is wrong in the script above, because I don't get anything from the JSON data appended to the listview.
Just for reference I have this on my HTML side.
<ul id="summaryList" data-role="listview" data-inset="true">
<li data-role="list-divider" style="text-align:center">Prescription Summary</li>
</ul>
Please note that the length of the data (Prescription) will be dynamically created so the length may not always be 2 like the example above.
I have gone through a good 2 hrs researching online and have found similar questions but none could help me solve my problem. I've also had a look at http://www.copterlabs.com/blog/json-what-it-is-how-it-works-how-to-use-it/ and learned a few more things but still have not be able to work my way around my problem.
Any suggestions or questions are greatly welcomed!
var PrescriptionJSON = '[{"medID":"id1","medName":"name1","medQty":"qty1","medDirec":"Directions1"}, {"medID":"id2","medName":"name2","medQty":"qty2","medDirec":"Directions2"}]';
localStorage.setItem("PrescriptionJSON", PrescriptionJSON);
function OnStorage(event) {
if (window.localStorage) {
var retrievedData = localStorage.getItem("PrescriptionJSON");
var obj = $.parseJSON(retrievedData);
var li = "";
$.each(obj, function(key, value) {
li += '<li><h2>' + value.medName + '</h2><p><strong>Quantity: </strong>' + value.medQty + '</p><p><strong>Directions: </strong>' + value.medDirec + '</p></li>'
})
$('#summaryList').append(li).trigger("create");
$('#summaryList').listview("refresh");
}
}
I am using MagicSuggest (http://nicolasbize.github.io/magicsuggest/) with CakePHP in a Helper as a contact search.
My MagicSuggestHelper class looks like the following:
class MagicSuggestHelper extends AppHelper {
var $name = 'MagicSuggest';
var $helpers = array('Html');
public function suggest(array $options=null){
?>
<div id='ms1'></div>
<script>
var ms = $('#ms1').magicSuggest({
width: 300,
highlight: true,
allowFreeEntries: false,
hideTrigger: true,
expandOnFocus: true,
useTabKey: true,
maxSelection: 1,
typeDelay: 0,
name: "searchId",
data: [
<?php foreach($options['data'] as $suggestions){
echo"{\n";
echo"id: ".$suggestions['id'].",\n";
echo"name: \"".$suggestions['name']."\",\n";
echo"desc: \"".$suggestions['desc']."\",\n";
echo"image: \"".$suggestions['image']."\",\n";
echo"},";
} ?>
],
renderer: function(v){
return '<div>' +
'<div style="float:left;"><img src="' + v.image + '"/ style=\"max-width:80px;max-height:80px\""></div>' +
'<div style="padding-left: 100px;">' +
'<div style="padding-top: 10px;font-style:bold;font-size:100%;color:#333">' + v.name + '</div>' +
'<div style="color: #999">' + v.desc + '</div>' +
'</div>' +
'</div><div style="clear:both;"></div>';
}
});
</script>
<?php
}
This works fine for me. But when selecting an item I want to get redirected directly to the profile I just clicked on.
I tried it with an onclick()-event in the first of the result which unfortunately didn't fired correctly when I used the CakePHP-HTML-Helper combined with $suggestions['id'].
On the MagicSuggest website I found an event that is fired when changing the selection The following code can be found in the FAQ:
$(ms).on('selectionchange', function(event, combo, selection){
alert(selection); });
I think I can use a redirect-Function here instead of the alert.
But how to get the id here? Even alert(selection) returns me an alert with "object Object" which I think should not be the case.
So how can I get the id here and redirect to my Contact view? (/contacts/view/$id).
I didn't worked alot with JavaScript in the past so please also excuse beginner's mistakes.
Thanks!
You can simply do this:
$(ms).on('selectionchange', function(e,m){
var val = this.getValue(); // this is what you want
});
I got this json object which its structure similar to this:
vendor have name, phone, fax, contacts
contacts have firstName, lastName, title, phone, email
I have created the first level in the table, but i didn't how to create the second nested level
function getData(vType) {
$.getJSON('/LocalApp/VendorController', {
vendorType : vType,
time : "2pm"
}, function(vendorsJson) {
$('#vendors').find("tr:gt(0)").remove();
var vendorTable = $('#vendors');
$.each(vendorsJson, function(index, vendor) {
$('<tr>').appendTo(vendorTable).append(
$('<td>').text(vendor.name)).append(
$('<td>').text(vendor.phone)).append(
$('<td>').text(vendor.fax)).append(
'<table class="contactTable"><tr><th>First Name</th><th>Last Name</th><th>Title</th><th>Phone</th><th>E-Mail</th></tr></table>');
});
});
}
So how can i add vendor.contacts as a nested table in jQuery code?
i know my code is not clean, jquery is confusing to me compared to Java
Not sure if you want the table in a cell of the vendor or not, but try something like this...
var contactTableHtml = '<table class="contactTable"><tr><th>First Name</th><th>Last Name</th><th>Title</th><th>Phone</th><th>E-Mail</th></tr></table>';
var vendorTableContent = $.map(vendorsJson,function (index, vendor) {
var contactTableContentHtml = $.map(vendor.contacts,function (index, contact) {
return "<tr><td>" + contact.firstName + "</td><td>" + contact.lastName + "</td><td>" + contact.title + "</td><td>" + contact.phone + "</td><td>" + contact.email + "</td></tr>";
}).join("");
return '<tr>' +
'<td>' + vendor.name + '</td>' +
'<td>' + vendor.phone + '</td>' +
'<td>' + vendor.fax + '</td>' +
'<td>' + contactTableHtml + contactTableContentHtml + '</td>' +
'</tr>';
}).join("");
vendorTable.append(vendorTableContent);
First I create a subtable as a string and then add it to the main table. I also suggest to create one big html string and add it once to the DOM. This is a lot quicker then calling $('...') everytime.
PS. Haven't been able to test it, but let me know if you get an error.
Unless you're very constrained for how much you can send with the page (that is, every single K of data counts against you), I don't think jQuery is a good fit for this kind of thing.
I think of JSON + something => HTML as templating, so I usually use a JavaScript templating tool like Handlebars to do that kind of thing. It's a more natural fit. Plus you can try right now with a site like Try Handlebars.js to interactively craft a template that takes some of your sample JSON and output the HTML you desire.
In all likelihood, a {{#each}} with another {{#each}} inside of it could probably handle the conversion of a nested JSON to whatever HTML you're after.