I'm trying to use Mustache.js but while my table is being created is not applying the Boostrap class properly. Only the header gets the css. I tried applying the class with jquery after the button click but did not help. I also try embedding the template inside the table but id did not work.
I have this html.
<table id="mTable" class="table table-striped">
<tr>
<th>FY</th>
<th>COST</th>
</tr>
</table>
then my template
<script id="priceTemplate" type="text/template">
<tr>
<td>{{FY}}</td>
<td>{{COST}}</td>
</tr>
</script>
my Ajax code.
$('#cmdSubmit').on('click', function () {
event.preventDefault();
var PriceTemplate = $('#priceTemplate').html();
$priceTable = $('#mTable');
$.ajax({
type: "GET",
url: "mywebservice.asmx/GetData",
contentType: "application/json; charset=utf-8",
datatype: "json",
success: function (msg) {
var pricedata = eval(msg.d);
$.each(pricedata, function (i, price) {
$priceTable.append(Mustache.render(PriceTemplate, price));
});
}
});
});
my table is showing data but is looks like the template is not getting stylized by bootstrap.
TIA,
Related
I am getting data as form of Java Bean and I am inserting each value into a table.
Values are retrieved as common way at first.
But I added some Javascript source, so that I can modify the value if I click any area near it.
Now I would like to save the data in database as well if there was any change after I modify.
How can I do that?
Here is my HTML code
<table class="bg-light table table-hover" style="overflow:hidden">
<th>Word</th>
<th>Dialogue</th>
<th>Practice</th>
<c:forEach items="${list}" var="engboardVO">
<tr>
<td data-editable>${engboardVO.word}</td>
<td data-editable>${engboardVO.dialogue}</td>
<td data-editable>${engboardVO.practice}</td>
</tr>
</c:forEach>
</table>
And Javascript
$("body").on("click", "[data-editable]", function() {
var $el = $(this);
/* var $input = $('<input style="width:500px; height:100px"/>').val( $el.text() ); */
var $input = $('<textarea rows=5 style="width:500px"/>').val($el.text());
$el.replaceWith($input);
var save = function() {
var $td = $("<td data-editable />").text($input.val());
$input.replaceWith($td);
};
$($input).blur(function() {
save();
})
});
You can use ajax for submitting data without form.
I can see you are using jQuery library. So I am writing code based on this library.
In HTML:
<table class="bg-light table table-hover" style="overflow:hidden">
<th>Word</th>
<th>Dialogue</th>
<th>Practice</th>
<c:forEach items="${list}" var="engboardVO">
<tr>
<td data-name="word" data-editable>${engboardVO.word}</td>
<td data-name="dialogue" data-editable>${engboardVO.dialogue}</td>
<td data-name="practice" data-editable>${engboardVO.practice}</td>
</tr>
</c:forEach>
</table>
In javascript:
$("body").on("click", "[data-editable]", function() {
var $el = $(this);
var $input = $('<textarea rows=5 style="width:500px"/>').val($el.text());
$el.html($input);
var field_name = $el.attr('data-name');
var save = function() {
var $val= $input.val();
$.ajax({
type: "POST",
url: "update-url",
data: {fieldname: field_name, fieldvalue:$input.val()},
dataType: "json",
success: function(msg) {
// do something on success
$el.html($val);
},
error: function(msg){
// do something on error
}
});
};
$($input).blur(function() {
save();
})
});
Then in server side, you can save fieldvalue as value of fieldname in your database.
Basically what we are doing here is:
Added an attribute data-name in td tag, its value can be related to your field name in table.
Get the name of attribute in javascript using var field_name = $el.attr('data-name');.
Using post request in ajax call passed the field_name and and value of this field to server.
$.ajax({
type: "POST",
url: "update-url",
data: {fieldname: field_name, fieldvalue:$input.val()},
dataType: "json",
success: function(msg) {
// do something on success
$el.html($val);
},
error: function(msg){
// do something on error
}
});
Now in server side, you need to fetch this data as you fetch normally for post request in submit of a form and save this data in database.
url is same as action you provide in form tag.
Edit:
Check now. You were replacing the td, whereas you had to replace html inside td.
Don't worry if you don't have a form or can't have it for some reasons
You can still read the inputs of your web page and use them or send them to the server.
See below a simple example:
var inputs = document.getElementsByTagName('input');
var data = []
for (index = 0; index < inputs.length; ++index) {
// deal with inputs[index] element.
data.push(inputs[index].value)
}
var json = JSON2.stringify(data);
$.ajax({
type: "POST",
url: "your-api-url",
data: json,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
// done code
}
});
I have a dynamic table that displays data from a mysql database. My database is updated every time in the server. I want to refresh only the table every 2 seconds without refreshing the whole page. How can do this? Please help how accomplish this?.
Parts of my table look like this:
<table id="getdata" border="0" align="left" cellpadding="0" cellspacing="0">
<tr>
<td bgcolor="#CCFF00">Name</td>
<td bgcolor="#CCFF00">Comment</td>
<td bgcolor="#CCFF00">DatePosted</td>
</tr>
</table>
You will need to use a client-side scripting language such as javascript in order to be able to refresh certain contents on your HTML page. A very common library that is used is jQuery.
PHP
# ajax.php
$contents = '<table class="table table-hover">
<thead>
<tr>
<th>Sound</th>
</tr>
</thead>
<tbody>
<tr>
<td>Bzzz Bzz</td>
</tr>
</tbody>
</table>';
echo json_encode($content);
HTML/Javascript
<button class="refresher">Refresh table</button>
<table id="table-to-refresh">
<thead>
<tr>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
</tr>
</tbody>
</table>
<script type="text/javascript">
$(document).ready(function () {
$(document).on('click', '.refresher', function () {
$.ajax({
url: 'ajax.php',
method: get,
dataType: 'json',
success: function(response) {
$('#table-to-refresh').html(response);
}
});
});
});
</script>
Additional reading
jQuery Docs - Ajax
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/
libs/jquery/1.3.0/jquery.min.js"></script>
<script type="text/javascript">
var auto_refresh = setInterval(
function ()
{
$('#load_tweets').load('file.php').fadeIn("slow");
}, 10000); // refresh every 10000 milliseconds
</script>
in file put your full html and php sql code like full code by which you are generating that table.
check this for refrence http://www.9lessons.info/2009/07/auto-load-refresh-every-10-seconds-with.html
Use ajax on an specified time interval like:
$.ajax({
url: 'your_url',
method: get,
data:
{
var1 : val1
},
success: function(response)
{
$('#getdata').html(response); // it will update the html of table body
}
});
just do this:
$.ajax({
contentType: contentType,
dataType: dataType,
type: type,
url: urlGetsearch,
data: '{textvalue: "' + $("#tableId").val() + '" }',
success: function (textvalue) {
$("#tableId").html(htmlData);
},
});
}
The controller is look like this:-
[HttpPost]
public ActionResult Getsearch(string textvalue)
{
your code.....
}
function GetEmp() {
$.ajax({
type: "POST",
url: "EMService.asmx/GetEmployee",
data: '{}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg, status, metaData) {
if (msg.d && msg.d.length > 0) {
BindTable(msg.d);
}
},
});
}
to bind the json(collection)
function BindTable(data) {
$('#tblEmployee tr:gt(0)').remove();
$("#employeeTemplate").tmpl(data).appendTo("#tblEmployee");
}
<script id="employeeTemplate" type="text/html">
<tr>
<td>${Id}</td>
<td>${Code}</td>
<td>${Name}</td>
</tr>
</script>
You just have to add the a delete button in your template, and bind an event handler (event delegation works great here):
<script id="employeeTemplate" type="text/html">
<tr>
<td>${Id}</td>
<td>${Code}</td>
<td>${Name}</td>
<td><button data-id="${Id}" class=".delete" type="button">Delete</button></td>
</tr>
</script>
And the event handler:
$('#tblEmployee').on('click', '.delete', function() {
var $this = $(this);
var id = $this.data('id');
// this is where you would make the Ajax call to remove the record from
// the server
deleteRecord(id).then(function() {
// at some point, e.g. after the Ajax request was successful, you
// would also remove the row
$this.closest('tr).remove();
});
});
Where deleteRecord would look something like:
function deleteRecord(id) {
return $.ajax({ ... });
}
This makes use of the jqXHR's promise interface. You can find more about promises in the jQuery tutorial.
Try below code, you can add Delete button to every row with different ids
function BindTable(data) {
$('#tblEmployee tr:gt(0)').remove();
$("#employeeTemplate").tmpl(data).appendTo("#tblEmployee");
}
Add the button to the template
<tr>
<td>${Id}</td>
<td>${Code}</td>
<td>${Name}</td>
<td><input type="button" value="Delete" id="delete${Id}"></td>
</tr>
I am trying to update a record list with ajax, represented on a table, where each record as an javascript delete link. If I preload the table, the RemoveLink works fine, but once the div "RecordListPartialView" is updated via ajax, It no longer works.
I checked with firebug that the generated html code is correct for each row. It looks like the browser isn't aware of the new code and so it doesn't trigger the javascript links.
Can someone please explain me what is going on?
(1) Here is the View code:
$(".RemoveLink").click(function () {
var _id = $(this).attr("data-id");
var recordToDelete = { id: _id };
var json = $.toJSON(recordToDelete);
$.ajax({
url: '/MortagePayment/RemoveMortageRecord',
type: 'POST',
dataType: 'json',
data: json,
contentType: 'application/json; charset=utf-8',
success: function (data) {
$("#RecordListPartialView").empty();
$("#RecordListPartialView").html(data.Message);
}
});
});
$(".AddLink").click(function () {
var _year = $("#NewRecord_year").val();
var _month = $("#NewRecord_month").val();
var _mortageValue = $("#NewRecord_mortageValue").val();
var newRecord = { year: _year, month: _month, mortageValue: _mortageValue };
var json = $.toJSON(newRecord);
$.ajax({
url: '/MortagePayment/AddMortageRecord',
type: 'POST',
dataType: 'json',
data: json,
contentType: 'application/json; charset=utf-8',
success: function (data) {
$("#RecordListPartialView").empty();
$("#RecordListPartialView").html(data.Message);
$("#NewRecord_year").val(0);
$("#NewRecord_month").val(0);
$("#NewRecord_mortageValue").val(0);
}
});
});
<div id="RecordListPartialView">
#Html.Partial("MortageRecordList", Model.MortageRecordList)
</div>
(2) the Partial View
<table id="mortageRecordListTable">
<tr>
<th colspan=4>Current reductions</th>
</tr>
<tr>
<th>Year</th>
<th>Month</th>
<th>Value</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr id="row-#item.mortageRecordId">
<td>
#item.year
</td>
<td>
#item.month
</td>
<td>
#item.mortageValue
</td>
<td>
<p class="RemoveLink" data-id="#item.mortageRecordId">Remove</p>
</td>
</tr>
}
</table>
(3) and the Controller:
[HttpPost]
public ActionResult AddMortageRecord(MortageRecord newRecord) {
var mortageRecordSet = MortageRecordSet.GetMortageSet(this.HttpContext);
if (ModelState.IsValid)
mortageRecordSet.AddMortageRecord(newRecord);
string partialViewHtml = RenderPartialViewToString("MortageRecordList", mortageRecordSet.GetMortageItems());
return Json(new { Success = true, Message = partialViewHtml });
}
[HttpPost]
public JsonResult RemoveMortageRecord(int id) {
var mortageRecordSet = MortageRecordSet.GetMortageSet(this.HttpContext);
mortageRecordSet.RemoveMortageRecord(id);
string partialViewHtml = RenderPartialViewToString("MortageRecordList", mortageRecordSet.GetMortageItems());
return Json(new { Sucess = true, Message = partialViewHtml });
}
If I understand you correctly.
If I preload the table, the RemoveLink works fine, but once the div
"RecordListPartialView" is updated via ajax, It no longer works.
Change your your .click event with .live
$(".RemoveLink").live("click",function(){
//any click event code comes here
});
I think you might need to call the click handler again in order to reattach it to the new DOM elements, since jQuery iterates through all the elements with the correct class when you actually call the $(".RemoveLink").click() and $(".AddLink").click() functions, not lazily whenever something is clicked.
OK, do you have a jquery event in a separate .js script file and have attached an event to an element inside a PartialView?
well! if yes, whenever the PartialView renders itself again (no matter what is the reason) all of it's bound events will be gone! then you should rebind them again after rendering the PartialView.
there are different approaches, for example:
In the Ajax.ActionLink (or any ajax call that makes the
PartialView re-render ) set OnSuccess to a jquery function that
rebinds PartialView's events.
Move all of your jquery event bindings codes from separate .js
script file to the inside of your PartialView's file (cstml). in
this case every time PartialView has been rendered, those events
will be bound again.
I have a file data.php, when a user clicks update the database is updated in background with jquery but in response i want to reload the particular table whose data was updated.
my html:
<div id="divContainer">
<table id="tableContainer" cellspacing='0' cellpadding='5' border='0'>
<tr>
<td>No.</td>
<td>Username</td>
<td>Password</td>
<td>Usage Left</td>
<td>%</td>
</tr><!-- Multiple rows with different data (This is head of table) -->
my jquery:
$('#UpdateAll').click(function() {
$.ajax({
type: 'post',
url: 'update.php',
data: 'action=updateAll',
success: function(response) {
$('#response').fadeOut('500').empty().fadeIn('500').append(response);
$('<div id="divContainer" />').slideUp('500').empty().load('data.php #tableContainer', function() {
$(this).hide().appendTo('#divContainer').slideDown('1000');
});
}
});
});
Everything is working fine the database is getting updated and in success #response is getting loaded with success message but the table is not refreshing.
You already have a div with an id of divContainer but you are creating this element again
$('<div id="divContainer " />').slideUp....
you need
$('#divContainer')
.slideUp('500')
.empty()
.load('data.php #tableContainer', function() {
$(this).slideDown('1000');
});
$('#UpdateAll').click(function () {
$.ajax({
type: 'post',
url: 'update.php',
data: 'action=updateAll',
success: function (response) {
$('#response').fadeOut('500').empty().fadeIn('500').append(response);
$('#divContainer').slideUp('1000').load('data.php #tableContainer', function () {
$(this).hide().appendTo('#tableContainer').slideDown('1000');
});
}
});
});