Fill table in javascript with data from db - javascript

I have an html <table> that I need to fill with data from a database query. The query returns 10 rows and then sends the data to the method fill(data) to fill the table:
function getTopQ() {
alert("Get top Qs");
callServer('fill', 'checkConnection', false, 'SelectTopQues.php');
}
function fill(data) {
alert("ready to fill now");
$('#table').html('');
var search = '#table';
for (var i = 0; i < data.length; i++) {
$('#table').listview("refresh");
var Questions = data[i];
var str = '<td " ID="' + Questions[0] +
'" Question="' + Questions[1] +
'" UserID="' + Questions[2] +
'"CategoryId"' + '" SubCategoryId"' + '" DatePosted"' + '"';
str += '">'; //end li
str += '<a href="" data-transition="fade">';
str += Questions[1];
str += '</a>';
//str += '<span class="hiddenData">' + item[13] + '</span>';
str += '</td>';
$('#table').append(str);
$('#table').listview("refresh");
}
console.log(data);
console.log($('#table'));
$('#table').listview("refresh");
}

Related

How to by pass HTML encoding string in text fields?

I am setting a field in my HTML label from Viewbag which has a "'" in the text. when the HTML pulls up it shows ' in place of "'". How do I stop it from getting encoded?
Please find the code below.
setting text fileds in the HTML view.
$('#thStudentName').text('#ViewBag.Name');
if (sessionData.data.EventDate2Def != '' || sessionData.data.EventDate2Def != null)
$('#tdWhen').text(sessionData.data.EventDate1Def + ' and ' + sessionData.data.EventDate2Def);
else
$('#tdWhen').text(sessionData.data.EventDate1Def);
$('#tdWhere').text(sessionData.data.FacilityName);
$('#tdLocated').text(sessionData.data.Address1 + ', ' + sessionData.data.City + ', ' + sessionData.data.State + ' ' + sessionData.data.Zip);
$('#tdPhone').text(sessionData.data.Phone);
$('#tdDirections').text(sessionData.data.Directions);
$('#tdRoom').text(sessionData.data.RoomNumber);
Populating a different section with Dynamic data.
function populateSessionTable() {
var count = 1;
$('#SessionTable').html('');
var tableContent = '';
var record = '';
var Sessions = sessionData.data.Sessions;
tableContent = generateTableContent(count, Sessions[0].StartDateTimeDef);
tableContent += '</tbody></table></div>';
$('#SessionTable').html(tableContent);
var radioStatus = '';
for (var i = 0; i < Sessions.length; i++) {
var content = Sessions[i];
radioStatus = '';
if (content.Capacity == content.Registered || content.Closed)
radioStatus = '<input disabled class="selected-session radio" name="SessionId" type="radio" value="' + content.SessionId + '">';
else if (content.StartDateTimeDef == '#ViewBag.WorkshopDateDef' && t24to12Convert(content.StartTimeString) == t24to12Convert('#ViewBag.WorkshopTime'))
radioStatus = '<input class="selected-session radio" checked name="SessionId" type="radio" value="' + content.SessionId + '">';
else
radioStatus = '<input class="selected-session radio" name="SessionId" type="radio" value="' + content.SessionId + '">';
record += '<tr>';
record += '<td class="session-schedule-table-btn">';
record += radioStatus;
record += '</td>';
record += '<td class="session-schedule-table-session-number"> ' + content.Number + ' </td>';
record += '<td class="session-schedule-table-session-start-time">' + t24to12Convert(content.StartTimeString) + '</td>';
record += '</tr>';
$('#SessionTBody' + count).append(record);
record = '';
if(Sessions.length != i + 1)
{
if(Sessions[i].StartDateTimeDef != Sessions[i + 1].StartDateTimeDef)
{
tableContent = '';
count++;
tableContent = generateTableContent(count, Sessions[i+1].StartDateTimeDef);
tableContent += '</tbody></table></div>';
$('#SessionTable').append(tableContent);
}
}
}
}
populateSessionTable();
The preview shows the name in the correct format, but when it gets rendered instead of having the quote, it shows '
This is how the output is coming up
So finally it was a stupid problem and I swear I had tried this before, but this is the code that worked.
var stuName = '#ViewBag.Name';
stuName = stuName.replace("'", "'");
$('#thStudentName').text(stuName);

Dynamic Row addition to the Table

I want to add Array elements to the table.
Array elements are dynamic coming from the database. And i am creating the Row for adding the one row from the generated data and appending rowAfter to add the other array elements
Here is the code i have written -
var rowSpan = 0;
var rowSpan1 = 0;
for (element in data)
{
// get products into an array
var productsArray = data[element].products.split(',');
var QuantityArray = data[element].quantity.split(',');
var ChemistArray = data[element].Retailername.split(',');
var PobArray = data[element].Pob.split(',');
rowSpan = productsArray.length;
rowSpan1 = ChemistArray.length;
var row = '<tr>' +
'<td rowspan="'+rowSpan+'">' + data[element].date + '</td>'+
'<td rowspan="'+rowSpan+'">' + data[element].doctor_name + '</td>';
// loop through products array
var rowAfter = "";
for (var i = 0; i < rowSpan; i++) {
if(i == 0) {
row += '<td>' + productsArray[i] + '</td>';
row += '<td>' + QuantityArray[i] + '</td>';
} else {
rowAfter += '<tr><td>' + productsArray[i] + '</td><td>' + QuantityArray[i] + '</td>';
}
}
for (var k = 0; k < rowSpan1; k++) {
if(k == 0) {
row += '<td>' + ChemistArray[k] + '</td>';
row += '<td>' + PobArray[k] + '</td>';
} else {
rowAfter += '<td>' + ChemistArray[k] + '</td><td>' + PobArray[k] + '</td> </tr>';
}
}
row +=
'<td rowspan="'+rowSpan1+'">' + data[element].locations +'</td>'+
'<td rowspan="'+rowSpan1+'">' + data[element].area + '</td>'+
'</tr>';
$('#tbody').append(row+rowAfter);
So as per the code I can finely display ProductArray and Quantity Array
And But i am not able to display the Chemist array after one another.
In the above Image i want to display data( Kapila and Kripa below the Chemist column) Some where making issue with tr and td.
Any help would really appreciated.
Data is a JSON Response -
In my case, ChemistArray(Retailername in response) contains 4 names and POBArray 4 values.
You need to add an empty <td></td> as a "placeholder".
for (element in data) {
var productsArray = data[element].products.split(',');
var quantityArray = data[element].quantity.split(',');
var chemistArray = data[element].Retailername.split(',');
var pobArray = data[element].Pob.split(',');
// find the largest row number
var maxRows = Math.max(productsArray.length, quantityArray.length, chemistArray.length, pobArray.length);
var content = '';
var date = '<td rowspan="' + maxRows + '">' + data[element].date + '</td>';
var doctorName = '<td rowspan="' + maxRows + '">' + data[element].doctor_name + '</td>';
var locations = '<td rowspan="' + maxRows + '">' + data[element].locations + '</td>';
var area = '<td rowspan="' + maxRows + '">' + data[element].area + '</td>';
content += '<tr>' + date + doctorName;
for (var row = 0; row < maxRows; row++) {
// only add '<tr>' if row !== 0
// It's because for the first row, we already have an open <tr> tag
// from the line "content += '<tr>' + date + doctorName;"
if (row !== 0) {
content += '<tr>';
}
// the ternary operator is used to check whether there is items in the array
// if yes, insert the value between the <td></td> tag
// if not, just add an empty <td></td> to the content as a placeholder
content += '<td>' + (productsArray[row] ? productsArray[row] : '') + '</td>';
content += '<td>' + (quantityArray[row] ? quantityArray[row] : '') + '</td>';
content += '<td>' + (chemistArray[row] ? chemistArray[row] : '') + '</td>';
content += '<td>' + (pobArray[row] ? pobArray[row] : '') + '</td>';
// only add "locations + area + '</tr>'" if it is the first row
// because locations and area will span the whole column
if (row === 0) {
content += locations + area + '</tr>';
} else {
content += '</tr>';
}
}
$('#tbody').append(content);
}
content += '<td>' + (productsArray[row] ? productsArray[row] : '') + '</td>'; is just a short-hand for
content += '<td>';
if (productsArray[row]) {
content += productsArray[row];
} else {
content += '';
}
content += '</td>';
If there is item in the productsArray[row], let's say productsArray[0], which is 'Sinarest', then productsArray[row] would be truthy. Else, if there is no more products in the array, such as productsArray[3] will gives us undefined, which is a falsy value and the corresponding conditional will be ran.

How to create a dynamic table in jQuery?

I want to create a dynamic table in jQuery. But my code creates a table for each of my element.
var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
var str = dataItem.Description;
var spl = str.split(','), part;
var spl2 = "";
for (var i = 0; i < spl.length; i++) {
part = spl[i].split(':');
content = "<table>" + "<tr><td>" + part[0] + "</td>" + "<td>" + part[1] + "</td></tr>";
spl2 += content;
}
content += "</table>"
var desc = "<div id='openModal' class='modalDialog'>" + "<span>" +
spl2
+ "</span><br/>" +
+ "</div>";
Which part of my code is wrong?
as you were adding table in for loop, so it was creating table for each item.Try this:
var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
var str = dataItem.Description;
var spl = str.split(','), part;
var spl2 = "";
content ="<table>"
for (var i = 0; i < spl.length; i++) {
part = spl[i].split(':');
content += "<tr><td>" + part[0] + "</td>" + "<td>" + part[1] + "</td></tr>";
spl2 = content;
}
content += "</table>"
// you can also assign spl2 = content; over here.
var desc = "<div id='openModal' class='modalDialog'>" + "<span>" +
spl2
+ "</span><br/>" +
+ "</div>";
var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
var str = dataItem.Description;
var spl = str.split(','), part;
var spl2 = "";
var content = "<table>";
for (var i = 0; i < spl.length; i++) {
part = spl[i].split(':');
content += "<tr><td>" + part[0] + "</td>" + "<td>" + part[1] + "</td></tr>";
spl2 += content;
}
content += "</table>"
var desc = "<div id='openModal' class='modalDialog'>" + "<span>" +
spl2
+ "</span><br/>" +
+ "</div>";
Updated your script

How to recreate a table dynamically in javascript

I am creating a table dynamically in a return statement from ajax. But I see only one row of the table, although debugger shows data.length as 4. How do I correct the recreating of table?
// using ajax return to recreate a table
// ...
if (data.length > 0) {
for (var i = 0; i < data.length; i++) {
var $mytablerow = $(
'<table>' +
'<tbody>' +
'<tr>' +
'<td id="td' + data[i].Value + '" >' +
data[i].Text +
'</td>' +
'</tr>' +
'</tbody>' +
'</table>'
);
}
}
var $mylst = $("#Userslist");
$mylst.html($mytablerow);
// ....
using ajax return to recreate a table
...
if (data.length > 0)
{
var $mytablerow = '<table><tbody>';
for (var i = 0; i < data.length; i++)
{
$mytablerow += $(
'<tr>' +
'<td id="td' + data[i].Value + '" >' + data[i].Text + '</td>' +
'</tr>');
}
$mytablerow += '</tbody></table>';
}
var $mylst = $("#Userslist");
$mylst.html($mytablerow);
....
I think you should use a variable outside the loop. For example:
if(data.length > 0) {
var $myTable = '<table><tbody>';
for (var i = 0; i < data.length; i++) {
$myTable += '<tr><td id="td' + data[i].Value + '" >' + data[i].Text + '</td></tr>';
}
$myTable += '</tbody></table>';
}
var $mylst = $("#Userslist");
$mylst.html($myTable);
You have problem in your script. To fix this problem replace by this script:
if (data.length > 0)
{
var $mytablerows = '<table>' + '<tbody>';
for (var i = 0; i < data.length; i++) {
$mytablerows += '<tr>' +
'<td id="td' + data[i].Value + '" >' + data[i].Text + '</td>' +
'</tr>';
}
$mytablerows += '</tbody>' + '</table>';
var $mylst = $("#Userslist");
$mylst.html($mytablerows);
}
That looks like you are creating a single row table each iteration and then only adding the last table you create. You need to create the table stuff once and then iterate to create the rows.

Need help with Flickr/JSON/Javascript issue when displaying gallery images

Wondering if anyone can help me. I'm trying to put together a weekly photo competition page by pulling in photos from a Flickr gallery, but I can't get the images to display. It works OK for groups, but having some problems with the gallery code. Getting the correct JSON response, but can't get the results to display on the page as good as the group images do.
Here's my Javascript:
$(function() {
var map;
var markers = [];
var infowindow;
// Get gallery photos
var visibleGallery;
$.getJSON("http://api.flickr.com/services/rest/" +
"?method=flickr.galleries.getPhotos" +
"&api_key=XXXX" +
"&photoset_id=XXXX" +
"&extras=geo,tags,url_sq,url_t,url_s,url_m,url_o" +
"&format=json&jsoncallback=?", function(data, textStatus) {
var htmlString = '<div id="weekContainer">';
var weeks = sortIntoWeekArrays(data.photos.photo);
$.each(weeks, function(i, week)
{
var weekNumber = i + 1;
var numberOfWeeks = weeks.length - 1;
htmlString += '<div id="week' + weekNumber + '">';
htmlString += '<ul class="weeks">';
if(i < numberOfWeeks)
{
htmlString += '<li><a class="weekLinksNext" href="#"><span>Next</span></a></li>';
}
var sunday = new Date(week.monday.toUTCString());
sunday.setDate(week.monday.getDate() + 6);
htmlString += '<li class="weekTitle">Week ' + weekNumber + ':</li><li class="weekDate"> ' + week.monday.format("ddd d mmm") + ' — ' + sunday.format("ddd d mmm") + '</li>';
if(i > 0)
{
htmlString += '<li><a class="weekLinksPrev" href="#"><span>Previous</span></a></li>';
}
htmlString += '</ul>';
if(week.winner !== undefined)
{
htmlString += '<p class="galleryTitleFirst">Photo of the Week</p>';
htmlString += '<ul class="imagesWinners">';
htmlString += '<li class="winner"><a href="http://www.flickr.com/photos/' + week.winner.owner + '/' + week.winner.id + '" target="_blank">';
htmlString += '<img title="' + week.winner.title + '" src="' + week.winner.url_m + '" alt="' + week.winner.title + '" />';
htmlString += '</a></li>';
htmlString += '<li class="name">' + week.winner.title + '</li>';
htmlString += '<li class="owner">' + 'by ' + week.winner.ownername + '</li>';
htmlString += '</ul>';
}
htmlString += '<p class="galleryTitle">Our other favourites this week</p>';
htmlString += '<ul class="imagesRunnersUp">';
$.each(week.images, function(i, item)
{
htmlString += '<li><a href="http://www.flickr.com/photos/' + item.owner + '/' + item.id + '" target="_blank">';
htmlString += '<img title="' + item.title + '" src="' + item.url_sq + '" alt="' + item.title + '" />';
htmlString += '</a></li>';
if(item.longitude == "0" && item.latitude == "0")
{
return true;
}
var latlng = new google.maps.LatLng(item.latitude, item.longitude);
var marker = new google.maps.Marker(
{
position: latlng,
map: map,
title:item.title
});
marker.content = '<img title="' + item.title + '" src="' + item.url_s + '" alt="' + item.title + '" />';
markers.push(marker);
});
htmlString += '</ul>';
htmlString += '</div>';
});
htmlString += '</div>';
$('div#weekViewer').append(htmlString);
$('div#weekContainer > div').css('float', 'left').css('margin-right', '30px');
$('div#weekContainer').width(weeks.length * 450);
$('div#weekContainer .weekLinksPrev')
.click(function(){
$('div#weekViewer').animate({scrollLeft: '-=450'}, 'slow');
return false;
});
$('div#weekContainer .weekLinksNext')
.click(function(){
$('div#weekViewer').animate({scrollLeft: '+=450'}, 'slow');
return false;
});
});
});
function sortIntoWeekArrays(items)
{
var weeks = [];
// Returns single dimension array containing single dimension arrays
$(items).each(function(i, item)
{
var monday = new Date(item.dateadded * 1000);
monday.setDate(monday.getDate() - monday.getDay() + 1);
monday.setHours(0,0,0,0);
var week, thisWeek;
for (i in weeks)
{
week = weeks[i];
if(week.monday - monday == 0)
{
thisWeek = week;
break;
}
}
if(thisWeek === undefined)
{
thisWeek =
{
monday: monday,
images: []
};
weeks.push(thisWeek);
}
if($.inArray('winner', item.tags.split(" ")) > -1)
{
thisWeek.winner = item;
}
else
{
thisWeek.images.push(item);
}
});
return weeks.sort(function(first, second)
{
return (first.monday > second.monday) - (first.monday < second.monday);
});
}
Any help would be fantastic :)
Regards,
David
Worked it out after some help from a friend. I was missing the date_upload value in the extras argument and item.dateadded needed to change to item.upload.

Categories

Resources