Retrieve data from a json object with square brackets enclosing the data - javascript

I got this data that are am getting from the database using an xmlhttprequest.
[{"description":"welcome","location":"Nairobi","name":"Equity Bank","created_at":"2013-02-07 21:12:45"},{"description":"very nice job","location":"Kisumu","name":"Equity Bank","created_at":"2013-02-16 12:19:46"},{"description":"welcome all","location":"nairobi","name":"Equity Bank","created_at":"2013-02-16 13:28:26"},{"description":"Very nice","location":"Nairobi","name":"Equity Bank","created_at":"2013-07-08 01:50:11"},{"description":"bad job","location":"eldoret","name":"Safaricom","created_at":"2013-02-03 00:00:00"},{"description":"very nice job","location":"mombasa","name":"Deep Africa","created_at":"2013-02-05 00:00:00"}]
My main aim is to arrange the data in a column form as follows:
description location name created_at
The square brackets confuse me a little bit but it seems like a javascript array but i just cant parse it correctly.

You could just loop through it, and access each element. Here is an example formatting it into some HTML tables.
var data = [{"description":"welcome","location":"Nairobi","name":"Equity Bank","created_at":"2013-02-07 21:12:45"},{"description":"very nice job","location":"Kisumu","name":"Equity Bank","created_at":"2013-02-16 12:19:46"},{"description":"welcome all","location":"nairobi","name":"Equity Bank","created_at":"2013-02-16 13:28:26"},{"description":"Very nice","location":"Nairobi","name":"Equity Bank","created_at":"2013-07-08 01:50:11"},{"description":"bad job","location":"eldoret","name":"Safaricom","created_at":"2013-02-03 00:00:00"},{"description":"very nice job","location":"mombasa","name":"Deep Africa","created_at":"2013-02-05 00:00:00"}];
var results = document.getElementById('results');
htmlString = '<table><tr>';
for( a=0; a<data.length; a++) {
htmlString = htmlString + '<tr><td>' + data[a]['description'] + '</td><td>' + data[a]['location'] + '</td><td>' + data[a]['name'] + '</td><td>' + data[a]['created_at'] + '</tr>';
}
htmlString = htmlString + '</table>';
results.innerHTML = htmlString;
There's a jsfiddle at http://jsfiddle.net/R63BJ/

As If ur using a XMLHTTRequest you will get the data in responesText
var jsonData=eval('('+responseText+')');
var text="<table><tr><th>description</th><th>location</th>" +
"<th>name</th><th>created_at</th></tr>";
for(var i=0;i<jsonData.length;i++){
text+="<td>"+jsonData[i].description+"</td>";
text+="<td>"+jsonData[i].location+"</td>";
text+="<td>"+jsonData[i].name+"</td>";
text+="<td>"+jsonData[i].created_at+"</td>";
text+="</tr>";
}
text+="</table>"
document.getElementById("tag").innerHTML="";// make sure that data is not Present
document.getElementById("tag").innerHTML=text;
and In the Jsp Page:
<div id="tag"></tag>

Related

How can I load data from a service that returns JSON and create content using jQuery?

I am a beginner in JS .. so I am reaching out to you, hoping someone could enlighten me! :)
I have been given a JSON link listing a lot of infos and I must create an html using at least 2 pieces of info from this JSON link.
I have already imported my stylesheets (+script) in the html and I coded this in my script.js :
$.getJSON('myjsonlink', function(json) {
console.log(json);
});
If one of you guys have a moment to give me hand, it would be awesome! Thank you so much in advance.
Athena.
There are few issues with the way you are reading data and rendering it:
There is no naruto property on response, it is results instead.
img is not a valid property, it should be image_url instead.
Let's fix it:
$('#get-data').click(function() {
var showData = $('#show-data');
$.getJSON('https://api.jikan.moe/v3/search/anime?q=naruto', function(data) {
var naruto = data.results;
for (var i = 0; i < naruto.length; i++) {
var anime = naruto[i];
var html = '<div class="card">' + '<img src="' + anime.image_url + '">' + '<div class="cardcontainer">' + '<p>' + anime.title + '</p>' + '<p>' + anime.synopsis + '</p>' + '</div>' + '</div>';
showData.append(html);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="get-data">Load Data</button>
<div id="show-data"></div>

Trying to use FOR loop inside of the string. (Js, jQuery)

I have this code:
$.each(data, function(i,v){
$('#user-grid').append(
'<a href="my_urls">' +
'<div>' + v.points + '</div>' +
'<div>' + v.other + '</div>' +
'</a>'
);
});
Into the user grid div, I append the string with the values taken from data.
v.points and v.other are the numbers.
To this moment, everything works just fine. But what I need is to embed the for loop into the divs. In the places where I have v.points and v.other I want to put two simular FOR loops.
for(var i = 0; i < v.points; i++) {
//here is the html line that should be passed to the div, where v.points are now
<div>This is the point</div>
}
And almost the same for the v.other. Only with another line that should be pasted.
So basically how can I do that? I was trying to paste this loops right inside the "append()" but that didn't work out. I was also trying to create a variable inside of the loop and pass it in to the append, but got only one result, instead of all that I have needed.
I'm not sure if this is what are you looking for, this code prints 5 "This is your point" and 3 "This is your other" inside the anchor.
var data = [
{
points: 5,
other: 3
}
]
function printPoints(vPoints){
var str = "";
for(var i=0; i<vPoints; i++) {
str+="<div>"+"This is your point"+"</div>";
}
return str;
}
function printOther(vOther){
var str = "";
for(var i=0; i<vOther; i++) {
str+="<div>"+"This is your other"+"</div>";
}
return str;
}
$.each(data, function(i,v){
$('#user-grid').append(
'<a href="my_urls">' +
printPoints(v.points)+
printOther(v.other)+
'</a>'
);
});
See it on action here

How to properly generate HTML in a JavaScript widget?

I've been following this tutorial on how to make JS widget. However I noticed that manually building html with plain JavaScript is not DRY. I am planning to build a form, tables etc. in a JS widget. Whats the best way to do this?
$.getJSON(jsonp_url, function(data) {
var fruits = ["Apples", "Mangoes", "Banana"];
var myHtml = "<ul>";
$(fruits).each(function(i){
myHtml += "<li>" + fruits[i] + "</li>";
});
myHtml += "</ul>";
$('#example-widget-container').html(myHtml);
});
if you want one of your divs or containers to continuously grow while you build dynamic content, without losing older content, use jQuery.append
$('#example-widget-container').append(myHtml);
this is probably the cleanest way. Or you can do other things like
var html = $('#example-widget-container').html();
newHtml = yourContent;
$('#example-widget-container').html(html + newHtml);
In JavaScript you can generate html content in different ways :
Create HTML with a string directly :
$("#sampleArea").append('<div class="' + newClass + '">' + newText + '</div>');
Create HTML with jQuery Api wrapping :
$("#sampleArea").append($('<div/>',{class : newClass}).text(newText));
Use a template engine in Javascript (like mustache.js) :
<script id="exampleTpl" type="x-tmpl-mustache">
<div class="{{class}}">{{text}}</div>
</script>
<script>
var data = {
class: newClass,
text: newText
}
var template = $('#exampleTpl').html();
var html = Mustache.render(template, data);
$('#sampleArea').append(html);
</script>
The best solution will depends of your use.

edit (append?) a string stored in a jquery variable

I am bringing a big html string inside an ajax call that I want to modify before I use it on the page. I am wondering if it is possible to edit the string if i store it in a variable then use the newly edited string. In the success of the ajax call this is what I do :
$.each(data.arrangement, function() {
var strHere = "";
strHere = this.htmlContent;
//add new content into strHere here
var content = "<li id=" + this.id + ">" + strHere + "</li>";
htmlContent is the key for the chunk of html code I am storing in the string. It has no problem storing the string (I checked with an alert), but the issue is I need to target a div within the stored string called .widgteFooter, and then add some extra html into that (2 small divs). Is this possible with jquery?
Thanks
Convert the string into DOM elements:
domHere = $("<div>" + strHere + "</div>");
Then you can update this DOM with:
$(".widgetFooter", domHere).append("<div>...</div><div>...</div>");
Then do:
var content = "<li id=" + this.id + ">" + domHere.html() + "</li>";
An alternative way to #Barmar's would be:
var domHere = $('<div/>').html( strHere ).find('.widgetFooter')
.append('<div>....</div>');
Then finish with:
var content = '<li id="' + this.id + '">' + domHere.html() + '</li>';
You can manipulate the string, but in this case it's easier to create elements from it and then manipulate the elements:
var elements = $(this.htmlContent);
elements.find('.widgteFooter').append('<div>small</div><div>divs</div>');
Then put the elements in a list element instead of concatenating strings:
var item = $('<li>').attr('id', this.id).append(elements);
Now you can append the list element wherever you did previously append the string. (There is no point in turning into a string only to turn it into elements again.) Example:
$('#MyList').append(item);

Pass string from one function to the next javascript

I've got a simple JavaScript client that pulls from a REST API to present some book data, however I seem unable to call the function createBookRow(bookid) and return the appropriate html string to the document ready function where it is called,
The output is currently being produced correctly as verified by the append to .row-fluid on the html page, ideas or suggestions welcome
function createBookRow(bookid)
{
$.get('http://mysite.co.uk/atiwd/books/course/'+bookid+'/xml', function(xml){
$(xml).find('book').each(function(){
var $book = $(this);
var id = $book.attr("id");
var title = $book.attr("title");
var isbn = $book.attr("isbn");
var borrowedcount = $book.attr("borrowedcount");
var html = '<div class="span3"><img name="test" src="http://covers.openlibrary.org/b/isbn/'+isbn+'-L.jpg" width="32" height="32" alt=""></p>' ;
html += '<p> ' + title + '</p>' ;
html += '<p> ' + isbn + '</p>' ;
html += '<p> ' + borrowedcount + '</p>' ;
html += '</div>';
$('.row-fluid').append($(html));
});
});
}
$(document).ready(function()
{
$.get('xml/courses.xml', function(xml){
$(xml).find('course').each(function(){
var $course = $(this);
var id = $course.attr("id");
var title = $course.text();
var html = '<div class="span12"><p>' + title + '</p><row id="'+id+'" >'+createBookRow(id)+'</row></div>' ;
$('.row-fluid').append($(html));
$('.loadingPic').fadeOut(1400);
});
});
});
The line
var html = '<div class="span12"><p>' + title + '</p><row id="'+id+'" >'+createBookRow(id)+'</row></div>' ;
should be just
var html = '<div class="span12"><p>' + title + '</p><row id="'+id+'" ></row></div>' ;
createBookRow(id);
createBookRow(id) function is making a get request to get some details, which happens asynchronously. Unless you explicitly mention it is a synchronous call(which is not advised).
I guess the functionality you need is to render some rows for course and in between you need books details displayed. In that case you need to explicitly say where your book row needs to be appended.
$('.row-fluid').append($(html));
The above code will always append book row at the end.
You aren't returning anything in the code you provided. You just append some HTML to a jQuery object. Try adding a return statement
return html;

Categories