Problems in Binding To Dynamic Table - javascript

I worked on this sample for 3 days strucked at last step!! Please some one help me!!
Any Help is appreciable!!
I am loading a dynamic table, i want to attach a grid on a column. I created a function for binding jqgrid. So when ever i am binding a table i am calling this function with a parameter,
The problem here is if i give the parameter directly it is working , but if i want to load it automatically it is not working.
I will explain below with code:
function bindData() {
$.ajax({
type: "POST",
url: location.pathname + "/getData",
data: "{}",
contentType: "application/json; charset=utf-8",
datatype: "jsondata",
async: "true",
success: function (response) {
var msg = eval('(' + response.d + ')');
if ($('#tblResult').length != 0) // remove table if it exists
{ $("#tblResult").remove(); }
var table = "<table class='tblResult' id=tblResult><thead> <tr><th>Name</th><th>SurName</th><th>Email</><th>Mobile</th><th>Address</th><th>Actions</th><th>image</th><th>Country</th><th>State</th><th>Gender</th><th>Add.Mobile</th></thead><tbody>";
for (var i = 0; i <= (msg.length - 1); i++) {
var row = "<tr>";
row += '<td>' + msg[i].Name + '</td>';
row += '<td>' + msg[i].SurName + '</td>';
row += '<td>' + msg[i].Email + '</td>';
row += '<td>' + msg[i].Mobile + '</td>';
row += '<td>' + msg[i].Address + '</td>';
row += '<td><img id="im" src="/User_Registration1/images/edit.png" title="Edit record." onclick="bindRecordToEdit(' + msg[i].EmployeeId + ')" /> <img src="/User_Registration1/images/delete.png" onclick="deleteRecord(' + msg[i].EmployeeId + ')" title="Delete record." /></td>';
row += '<td><img class="img" src=' + msg[i].FileName + ' alt="--NO IMAGE--"/></td>';
row += '<td>' + msg[i].Country + '</td>';
row += '<td>' + msg[i].StateName + '</td>';
row += '<td>' + msg[i].Gender + '</td>';
row += '<td style="width:250px;height:120px;"><table id="tblSub' + msg[i].Name + '"></table><script> $(document).ready(function () { BindGrid("AjjiAjji");});</script></td>';
row += '</tr>';
table += row;
}
table += '</tbody></table>';
$('#divData').html(table);
$("#divData").slideDown("slow");
},
error: function (response) {
alert(response.status + ' ' + response.statusText);
}
});
}
see the last column in which i am attaching a grid view by calling a javascript function.
js function:
function BindGrid(user) {
$(document).ready(function () {
$("#tblSub"+user).jqGrid({
loadError: function (xhr, status, error) {
alert('load:' + error);
},
url: 'Fetch.aspx?filter=' + user + '',
data: "{}",
datatype: 'json',
colNames: ['Name', 'Mobile'],
colModel: [
{
name: 'User',
index: 'User',
width: 100,
align: "left",
editable: true,
size: 80
},
{
.
.
.
So if i pass the BindGrid("AjjiAjji") it is working fine, But i want to load the grid automatically like BindGrid('+msg[i].Name+') , It is Showing Error "ReferenceError: AjjiAjji is not defined"

I think you are forgetting to add double quotes and the result whould be BindGrid (AjjAjj). try this:
BindGrid("'+msg[i].Name+'")
this should work fine

I think that problem is that the time you are attaching jqGrid to "$("#tblSub"+user)" is not present in DOM.
You should call BindGrid function only after $('#divData').html(table); which is adding table into DOM.
So that jqGrid can properly work.

Related

how to change one button based on value

I want to change my ajax button based on if else condition. Like if status is 1 then it will show just active button otherwise it just show the inactive button. I have two buttons. I cant find the logic where I actually put my if else condition. My code is:
function showAllArticle(status = "") {
//alert(status);
$.ajax({
//cache: false,
//headers: { "cache-control": "no-cache" },
type: 'ajax',
method: 'post',
data: {
status: status
},
url: '<?php echo base_url() ?>Article/showAllUser',
async: true,
dataType: 'json',
//cache: false,
success: function(data) {
var html = '';
var i;
for (i = 0; i < data.length; i++) {
//(data[i].status);
html += '<tr>' +
'<td>' + data[i].id + '</td>' +
'<td>' + data[i].username + '</td>' +
'<td>' + data[i].email + '</td>' +
'<td>' +
// '{% if data[i].status == 1 %}'
'Active' +
//#if(data[i].status == 1)
//'{% else %}'
'Inactive' +
//'{% endif %}'
/* '</td>' +
'<td>'+
'+#if(data[i].status == 1)+'
'tseting'+
'+#elseif(data[i].status == 0)+'
'debug'+
'+#endif+'
'</td>'+*/
'</tr>';
}
$('#showdata').html(html);
},
error: function() {
alert('Could not get Data from Database');
}
});
}
You must apply the if condition based on JS, not on the template language you are using as JS is executed on the user end.
You must do something similar do this:
html += '<tr>';
html += '<td>' + data[i].id + '</td>';
html += '<td>' + data[i].username + '</td>';
html += '<td>' + data[i].email + '</td>';
html += '<td>';
if (data[i].status == 1) {
html += 'Active';
} else if(data[i].status == 12) {
//...
} else {
html += 'Inactive' +
}
/* '</td>' +
'<td>'+
'+#if(data[i].status == 1)+'
'tseting'+
'+#elseif(data[i].status == 0)+'
'debug'+
'+#endif+'
'</td>'+*/
html += '</tr>';

How to format value to Currency or Percent in AJAX

What is the best way of formating the values to percentage or currency from Ajax and display to a Table?
I'm currently developing an application which has Money values from SQL Server and need to be format from 3569.09 to $ 3, 569.09 and also from 24.55 to 24.55 % on the Table.
I have the tried THIS but still did not help.
Here is JS my Code:
function loadMarginBelow21() {
$.ajax({
url: "/Dashboard/MarginBelow21",
type: "GET",
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (result) {
var html = '';
$.each(result, function (key, item) {
html += '<tr>';
html += '<td>' + item.Stock+ '</td>';
html += '<td>' + item.Price + '</td>'; //Must show Currency sign in the beguining like $5,664.00
html += '<td>' + item.Source + '</td>';
html += '<td>' + item.COST + '</td>';
html += '<td>' + item.Margin + '</td>'; // Must show % at the end of value
//html += '<td>Edit</td>';// | Delete</td>';
html += '<td>' +sdg + '</td>'
html += '</tr>';
});
$('.tbodyM').html(html);
},
error: function (errormessage) {
alert(errormessage.responseText);
}
});
}
Currently the table shows like:
Intl.NumberFormat is your friend. Create a new formatter with a locale and currency (I’ll assume you want US dollars here) and it’ll produce formatted strings.
let formatter = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' });
let price = formatter.format(item.Price);
Given your sample data it looks like the percentage can just be added on to the end using string concatenation.

How to call a thymeleaf modal fragment from a javascript generated link?

I have a javascript function that renders a table from an ajax call.
The row rendering bit is:
function buildTable(id) {
trHTML = null;
$.ajax({
type: "GET",
url: siteroot + "apiURL" + id,
data: {},
dataType: "json",
cache: false,
success: function (data) {
for (i = 0; i < data.length; i++) {
trHTML +=
'<tr>' +
'<td>' + data[i].value +
'<a class="pull-right" href="#" data-toggle="modal" data-target="#edit-modal" > ' +
'<span class="pull-right glyphicon glyphicon-pencil"></span>' +
'</a>' +
'</td>' +
'<td>' + data[i].text + '</td>' +
'<td>' + data[i].description + '</td>' +
'</tr>';
}
$('#resourceTable').append('<tbody>' + trHTML + '</tbody>');
},
error: function (msg) {
alert(msg.responseText);
}
});
}
And the modal is defined as:
<div th:replace="../../modals/modal"></div>
The issue I am facing is that the link is here on the rendered table, but when I click it, the modal does not come on.
What am I not seeing here?

Why javascript actionlink function under ajax not work in mvc

Under an ajax get method i need to generate table programatically.why actionlink not work with my table
ajax method
$(document).ready(function () {
//click event
$('.delete-logo').on('click', function () {
var id = $(this).data('key');
alert(id);
});
//click event
$('.edit-logo').on('click', function () {
var id = $(this).data('key');
alert(id);
});
$('.submitDetailForm').on('click', function () {
//get value from control
var ProductID = $('#ProductID').val();
var Qty = $('#Qty').val();
var Unit = $('#Unit').val();
var Amount = $('#Amount').val();
var ICMS = $('#ICMS').val();
var IPI = $('#IPI').val();
var ProductName = $('#ProductID option:selected').text();
var booksDiv = $("#booksDiv");
$.ajax({
cache: false,
type: "GET",
url: '#Url.Action("AddToCard", "Sales")',
data: { ProductID: ProductID, ProductName: ProductName, Qty: Qty, Unit: Unit, Amount: Amount, ICMS: ICMS, IPI: IPI },
success: function (data) {
console.log(data);
var result = "";
booksDiv.html('');
$.each(data, function (SalesOrderID, OrderDetails) {
result += '<tr> <td>' + OrderDetails.Name + '</td>' +
'<td>' + OrderDetails.Qty + '</td>' +
'<td>' + OrderDetails.Unit + '</td>' +
'<td>' + OrderDetails.Amount + '</td>' +
'<td>' + OrderDetails.ICMS + '</td>' +
'<td>' + OrderDetails.IPI + '</td>' +
'<td><a class="edit-logo" data-key=' + OrderDetails.SalesOrderDetailID + ' href="javascript:void(0);">' + 'Edit' + '</a></td>' +
'<td><a class="delete-logo" data-key=' + OrderDetails.SalesOrderDetailID + ' href="javascript:void(0);">' + 'Delete' + '</a></td>' +
' </tr>';
});
booksDiv.html(result);
},
error: function (xhr, AJAXOptions, thrownError) {
alert('Failed to retrieve books.');
}
});
});
});
Hyper link content
'<td><a class="edit-logo" data-key=' + OrderDetails.SalesOrderDetailID + ' href="javascript:void(0);">' + 'Edit' + '</a></td>'
'<td><a class="delete-logo" data-key=' + OrderDetails.SalesOrderDetailID + ' href="javascript:void(0);">' + 'Delete' + '</a></td>'
hyperlink display perfectly in browser but can not invoke click events
why my actionlink click event are not fired?
You need to use event delegation (using the .on() function) when adding dynamic content
$('#booksDiv').on('click', '.delete-logo', function() {
....
});
$('#booksDiv').on('click', '.edit-logo', function() {
....
});
where the element with id="booksDiv" is the closest ancestor that exists when the page is first generated.
Side note: Rather than manually generating your javascript object, you can simply use data: $('form').serialize(),

Update table row with animation upon AJAX request

I'm creating a 'live' leaderboard table. Every X seconds, an AJAX request is sent to the server to load the latest leaderboard data.
If there's a change in data, the leaderboard will instantly update upon the AJAX request.
However - If there IS a change, instead of instantly showing the new data, I want to animate the table row to its new position instead of instantly reloading it. What is the best way of achieving something like this?
I'm updating the leaderboard at the moment like so:
$(document).ready(function() {
showLeaderboard();
if (autoUpdate != false) {
window.setInterval(function(){
$('#wrapper h2, #leaderboard tbody tr').remove(updateLeaderboard());
}, reloadInterval);
}
});
function updateLeaderboard() {
leaderBoardType;
numRecords;
quizIDs;
topListTitle;
latestTitle;
$.webMethod({
url: 'xxx',
data: '{quizIDs:"'+quizIDs+'",numRecords:"'+numRecords+'"}',
type: 'POST',
cache: false,
beforeSend: function () {
$('body').append('<div class="loading"></div>');
},
success: function (ret)
{
$('.loading').remove();
$('#wrapper').prepend(topListTitle);
$.each(ret.leaderboard,function(i){
pos = i + 1;
str = '<td class="position">' + pos + '</td>';
str += '<td class="name">' + ret.leaderboard[i].first_name + ' ' + ret.leaderboard[i].last_name + '</td>';
str += '<td class="time">' + getTime(ret.leaderboard[i].time_taken) + '</td>';
str += '<td class="points">' + ret.leaderboard[i].points + '</td>';
//str += '<td>' + ret.leaderboard[i].last_name + '</td>';
//str += '<td>' + ret.leaderboard[i].incorrect_attempts + '</td>';
//str += '<td>' + ret.leaderboard[i].user_id + '</td>';
$('#leaderboard tbody').append('<tr>'+str+'</tr>');
});
},
error: function (response) { alert(response.responseText); }
});
}
HTML
<table id="leaderboard">
<thead>
<tr>
<th class="position">Position</th>
<th class="name">Name</th>
<th class="time">Time Taken</th>
<th class="points">Points</th>
</tr>
</thead>
<tbody>
</tbody>
</table>

Categories