best way to put ajax data into html and display on page - javascript

I'm loading quite a bit of json data through a jquery/ajax/php get. When I get the data, I display it in some tables on a modal i pop up. And I do it sort of like this.
str1 = "<table class='line_item_order_info_table'>";
str1 += "<tr><td class='line_item_label' >";
str1 += "Order no.";
str1 += "</td></tr>";
str1 += "<tr><td class='line_item_data' id='order_number_td'>";
str1 += data.order_number;
str1 += "</td></tr>";
str1 += "</table>";
str1 += "</td>";
str1 += "<td>";
str1 += "<table class='line_item_order_info_table'>";
str1 += "<tr><td class='line_item_label'>";
str1 += "Order date";
str1 += "</td></tr>";
str1 += "<tr><td class='line_item_data'>";
str1 += data.order_date;
str1 += "</td></tr>";
str1 += "</table>";
//many, many more lines that look like this
$('#modal-div').html(str1);
Is this the best way to put this data into html via javascript? It's sort of difficult to keep track of like this. This much html, without any indentations anywhere to make it easier to read, is sort of painful to look at or try to find something in.
Grateful if you can point me in the direction of a better strategy! Thanks!

If you absolutely have to write out your HTML as you've described, you can just add line escapes to your markup after each line.
var myHTML = '<div class="bleh"> \
<ul class="bleh2"> \
<li>'+ data.order_number +'</li> \
<li>'+ data.order_date +'</li> \
</ul> \
</div>';

If you pass an array of objects from your server code (rather than a string of HTML) you can then loop through the array using JavaScript, grabbing each of the properties of the objects in the array.
On each iteration $.append the html into your #modal-div.
something along the lines of this:
for (int i = 0: i<msg.d.length; i++) {
var order_number = msg.d[i].order_number;
...
$('#modal-div').append('<li>'+order_number +'</li>');
}

You can markup #modal-div in HTML as a template with specific ids and replace with actual data before showing the modal window.
example
<div id="modal-div">
<table class='line_item_order_info_table'>
<tr>
<td class='line_item_label' >Order Number</td>
<td id="order_num">order_num</td>
</tr>
<tr>
<td class='line_item_label'>Order date</td>
<td id="order_date">order_date</td>
</tr>
</table>
</div>
$(document).ready(function(){
var data ={"ordernumber":"123", "orderdate":"12/01/1999"};
$('#modal-div').hide();
$('#submit').click(function(){
$('#order_num').html(data.ordernumber);
$('#order_date').html(data.orderdate);
$('#modal-div').show();
});
});

Related

textarea clears when using innerhtml [duplicate]

I have a problem concerning multiple file uploads in javascript. I am trying to create my own multiple file upload by dynamically adding inputs. This is all easy as pie, but the problem is that whenever I add a new , my previous input-fields of the type "file" get reset.
If I remove the last lines of code where I alter the innerHTML of my parent div, the values of my do not get reset. Does anyone know how this problem can be solved? The javascript code can be found below. Thanks in advance.
if(document.getElementById("upload_queue").innerHTML.indexOf(_item) == -1)
{
var _row = "<tr id='queue_row_" + items_in_queue + "'>";
_row += "<td>";
_row += "<div class='remove_uploaded_image' onclick='remove_from_queue(" + items_in_queue + ")'></div>";
_row += "</td>";
_row += "<td>";
_row += _item;
_row += "</td>";
_row += "</tr>";
document.getElementById("upload_queue").innerHTML += _row;
document.getElementById("upload_image_" + items_in_queue).style.display = "none";
items_in_queue++;
document.getElementById("uploader_holder").innerHTML +=
'<input id="upload_image_' + items_in_queue +
'" name="upload_image_' + items_in_queue + '" accept="image/jpeg" type="file"' +
'onchange="add_to_upload_queue()" style="display: inline;" />';
}
Yeah... you're going to want to use appendChild instead of modifying the inner HTML:
var myInput = document.createElement("INPUT");
// do stuff to my input
var myContainer = document.getElementById("uploader_holder");
myContainer.appendChild(myInput);
That's the general gist of what you have to do - let me know if you need somethign more specific, but it looks like you've got a good hold on JS already... You're going to want to do that in almost all cases rather than setting inner HTML... So, building your TR as well... you'll have to append the TD to the TR, you'll have to append the TD with your input, you'll have to append your targeted table with the TR, etc.

Using javascript to populate a html table

Im trying to add input where you can select different options for a location. my issue is that its messing up the table and it just does not see me new input option that i've added. I can list other files or pictures if needed.
var items = 0;
function addItem() {
items++;
var html = "<tr>";
html += "<td>" + items + "</td>";
html += "<td><input type='number' name='idNumber[]'></td>";
html += "<td><input type='text' name='itemName[]'></td>";
html += "<td><input type='number' name='itemQuantity[]'></td>";
html += "<td><select name='itemLocation[]' id='location'><option value="Shop" name="Shop">Shop</option></select></td>";
html += "<td><input type='text' name='itemIndex[]'></td>";
html += "<td><button type='button' onclick='deleteRow(this);'>Delete</button></td>"
html += "</tr>";
Just trying to change to location button to a multiple choice selection
you have double quotes inside your string which is breaking your template
to avoid this kind of error you should use template literals its fully supported
Note it is backtick (`) not singlequote (')
see example
var value = "new entry"
var tr = `
<tr>
<td>${value}</td>
<td>${value}</td>
<td>${value}</td>
<td>${value}</td>
<td>${value}</td>
</tr>
`

Chaging innerHTML of DIV changes table properties

I have to show dynamically checkboxes in a HTML page and get their value from database.
The trick I used is to create the whole table HTML in java and then using AJAX I do this
var div = document.getElementByID("div").innerHTML = htmlCode;
but issue is
in htmlCode variable, the html is like
<table width="100%">
<tr>
<td width="50%">......
but when I check div.innerHTML it shows like
<TABLE width="100%">
<TBODY>
<TR>
<TD width="50%">
<?xml:namespace prefix = ....
Why they become uppercase and why is xml:namaesapce prefix added ?
This causes issue as table is not properly displayed.
Is there any other better way to do this without using innerHTML ?
The code for generation of table is
String html = "<table width=\"100%\">";
for (Iterator it = lookupList.iterator (); it.hasNext ();)
{
HashTree lookupElement = (HashTree) it.next ();
String code = lookupElement.getChildTagValue ("CODE");
String text = lookupElement.getChildTagValue ("TEXT");
String labelText = "";
if(indexLookupElement == 0)
labelText = "First Checkbox label";
html = html + "<tr><td width=\"50%\" >" +
+
"<input type=\"checkbox\" id=\"item" + code + "\" />" +
"<html:label " +
"id=\"_Description\"" +
"name=\"_Description\"" +
">" + text +
"</html:label>" +
"<td width=\"50%\" >" +
"</td></tr>";
indexLookupElement += 1;
}
html = html + "</table>";
Thanks,
Aiden
It's not a best practice to create the HTML code server-side. If you are sure you'll have the table in your document it's better to make it part of the structure of the document and feed only the variables from your Java code. Even if the table is conditional you may consider hide/unhide it with a variable. I believe this approach will solve your problem if the HTML code of your webpage is correct.
Update
Test it like this:
html = html + "<tr><td width=\"50%\"><input type=\"checkbox\" id=\"item" + code + "\" /><label id=\"_Description\" name=\"_Description\">" + text + "</label></td><td width=\"50%\"></td></tr>";
In your code you have missing TD closing tag and I made some changes. See if this will fix your problem.

building a table-like structure from data

Is there a way to build dynamically a table-like structure from a data-set on websites (in javascript)?
In pseudo-code something like:
function pseudo(dataset) {
<table>
<th>dataset.name, dataset.id</th>
foreach dataset.schedular.array as a {
<tr><td>a.start_time</td><td>a.end_time</td><td>a.client.name</td></tr>
}
</table>
}
and executed like:
<div>
<script>pseudo(json[employee[0]]);</script>
</div>
In php i used smarty-templates to "fill" data into similar masks, now i need something similar in javascript.
Are jquery widgets or plugins that what i m looking for? And where can i find helpful tutorials or books?
your html page:
<div id="dataToDisplay"></div>
your java script function:
function pseudo(dataset) {
var tableContents = "<table>";
tableContents = tableContents+ "<th>"+dataset.name, dataset.id+"</th>";
foreach dataset.schedular.array as a {
tableContents =tableContents + "<tr><td>"+a.start_time+"</td><td>"+a.end_time+"</td><td>"+a.client.name+"</td></tr>";
}
tableContents = tableContents + "</table>";
document.getElementById("dataToDisplay").innerHTML = tableContents;
}
I use jQuery and the following construct. employees is an JS array of objects. The HTML table is prepared like this:
<table id="clients">
<thead><tr><th>Start</th><th>End</th><th>Name</th></tr></thead>
<tbody></tbody>
</table>
Then the following jQuery-loop using each is used to append the lines:
$.each(employees, function(index, employee){
$('#clients > tbody').append(listItem(index, employee));
});
where listItem() is a function that returns the table line. Of course, this could be done more elegantly:
function listItem(index, employee) {
var item = '<tr>';
item += '<td>' + employee.start_time + '</td>';
item += '<td>' + employee.end_time + '</td>';
item += '<td>' + employee.name + '</td>';
item += '</tr>';
return item;
}
Take a look at "jqGrid"
http://www.trirand.com/blog/
it's a plugin which takes JSON and biulds tables from it. However it uses jQuery.

Displaying table using Javascript breaks inside for loop

I have a code to populate a table using Javascript as:
var myResponse = document.getElementById("jsonPlaceHolder");
myResponse.innerHTML += "<table border=1> <tr> <td> User Id </td> <td> Question </td> <td> Link Question </td> </tr>";
for (var i = 0; i < 25; i++) {
myResponse.innerHTML += "<tr>"
myResponse.innerHTML += "<td>" + jsonObj[i]["user_id"] + "</td>";
myResponse.innerHTML += "<td>" + jsonObj[i]["text"] + "</td>";
myResponse.innerHTML += "</tr>"
}
myResponse.innerHTML += "</table>";
Problem with this code is when I run this table is not continued inside for loop. If I add
myResponse.innerHTML += "<table><tr>"
inside my for loop, table is created. Isn't this bit odd?,
since i am using += to add to current innerHTML of the DOM element.
One of the most misunderstood thing about innerHTML stems from the way the API is designed. It overloads the + and = operators to perform DOM insertion. This tricks programmers into thinking that it is merely doing string operations when in fact innerHTML behaves more like a function rather than a variable. It would be less confusing to people if innerHTML was designed like this:
element.innerHTML('some html here');
unfortunately it's too late to change the API so we must instead understand that it is really an API instead of merely an attribute/variable.
When you modify innerHTML it triggers a call to the browser's HTML compiler. It's the same compiler that compiles your html file/document. There's nothing special about the HTML compiler that innerHTML calls. Therefore, whatever you can do to a html file you can pass to innerHTML (the one exception being that embedded javascript don't get executed - probably for security reasons).
This makes sense from the point of view of a browser developer. Why include two separate HTML compilers in the browser? Especially considering the fact that HTML compilers are huge, complex beasts.
The down side to this is that incomplete HTML will be handled the same way it is handled for html documents. In the case of elements not inside a table most browsers will simply strip it away (as you've observed for yourself). That is essentially what you're trying to do - create invalid/incomplete HTML.
The solution is to provide innerHTML with complete HTML:
var htmlString = "<table border=1> <tr> <td> User Id </td> <td> Question </td> <td> Link Question </td> </tr>";
for (var i = 0; i < 25; i++) {
htmlString += "<tr>"
htmlString += "<td>" + jsonObj[i]["user_id"] + "</td>";
htmlString += "<td>" + jsonObj[i]["text"] + "</td>";
htmlString += "</tr>"
}
htmlString += "</table>"
myResponse.innerHTML += htmlString;
Use the DOM API to manipulate the DOM:
var myResponse = document.getElementById("jsonPlaceHolder");
var table = document.createElement('table'),
headings = ["User ID", "Question", "Link Question"];
table.style.border = "1";
var r = table.insertRow(-1);
for (var i = 0; i < 3; i++) {
(function(){
return r.insertCell(-1);
})().innerHTML = heading[i];
}
for (var i = 0; i < 25; i++) {
r = table.insertRow(-1);
var userid = r.insertCell(-1),
text = r.insertCell(-1);
userid.innerHTML = jsonObj[i]["user_id"];
text.innerHTML = jsonObj[i]["text"];
}
myResponse.appendChild(table);

Categories

Resources