I'm using the following function to ready and draw the grid as soon as the HTML page is clicked
$(document).ready(function () {
FillGrid();
});
And I'm using the following FillGrid function to draw and show the data from the MSSQL
function FillGrid() {
//if ($('#grid').length == 1) {
// $('#grid tr').not(':first-child').remove();
$.ajax({
//beforeSend: function () {
// $('.grid').show();
// $("#loadingProjects").show();
//},
//complete: function () {
// ShowGrid();
// $("#loadingProjects").hide();
//},
// method: 'POST',
success: function (data) {
//if (data.length == 0) {
// $('<tr><td colspan="4">No Record Found</td></tr>').appendTo($('#grid'));
//}
$.each(data, function (index, item) {
$('<tr>' +
'<td>' + item.ReservationDate + '</td>' +
'<td>' + item.Name1 + '</td>' +
'</tr>').appendTo($('#grid'));
});
},
error: function (xhr, status, error) {
console.log(error);
}
});
}
And this is my HTML code of the grid.
<table class="table table-striped" id="grid" style="display:none;">
<tr>
<th>Reservation No</th>
<th>Name</th>
</tr>
</table>
But the grid is never been drawn when its loaded.
Is this correct or am I'm doing something wrong.
Can anyone help me? This is for a school project.
Related
I'm developing a live search function in a Laravel application, but I'm having some problems because i'm getting duplicate appends, for example I type in "Andrew".
Every key I hit starting with "A" until "W", im appending the results over and over, so Andre creates 6 table rows, but I want it to be only one.
The second problem is that if I delete all the input, I'm trying to show my "initial_table", but that doesn't work.
I tried changing $('#ajax').append(row); from append to html, but then I have only one result no matter how many matches I get.
<table id="usertable">
<thead>
<tr>
<th>Name</th>
<th>Tier</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Name</th>
<th>Tier</th>
</tr>
</tfoot>
<tbody id="ajax">
{{-- search results here --}}
</tbody>
<tbody id="initial_table">
#foreach ($users as $user)
<tr>
<td>{{$user->username}} </td>
<td>{{$user->tier}}</td>
</tr>
#endforeach
</tbody>
</table>
This is my Javascript
<script>
});
// })
document.getElementById("search").addEventListener("keyup", searchUsers);
document.getElementById("search").addEventListener("change", searchUsers);
function searchUsers(){
if(this.value != '') {
$.ajax({
url: '/admin/searchUsers?search=' + this.value,
method: 'GET'
}).done(function(response){
console.log(typeof response);
console.log(response);
if(response.length < 1) {
$('#ajax').append('<span class="text-center">No results found!</span>');
$('#initial_table').hide();
}
else {
$.each(response, function(index, obj){
var row = $('<tr>');
row.append('<td> <a href="/admin/user/' + obj.id + '">' + obj.username + ' AJAX' + '</td>');
row.append('<td>' + obj.tier + '</td>');
$('#ajax').append(row);
$('#initial_table').hide();
});
}
});
}
}
</script>
Tried to add some comments to explain . Hope it helps
document.getElementById("search").addEventListener("keyup", searchUsers);
document.getElementById("search").addEventListener("change", searchUsers);
function searchUsers(){
if((this.value.trim()) != '') // even for extra space it should not allow in
{
$.ajax({
url: '/admin/searchUsers?search=' + this.value,
method: 'GET'
}).done(function(response)
{
console.log(typeof response);
console.log(response);
$('#ajax').empty(); //for 1st query :-on every ajax call it will first empty "#ajax" tbody
$('#initial_table').hide();
if(response.length < 1)
{
$('#ajax').append('<span class="text-center">No results found!</span>');
}
else
{
$.each(response, function(index, obj)
{
var row = $('<tr>');
row.append('<td> <a href="/admin/user/' + obj.id + '">' + obj.username + ' AJAX' + '</td>');
row.append('<td>' + obj.tier + '</td>');
$('#ajax').append(row);
});
}
});
}else // for 2nd query :- your code missing this part to show initial tbody if search text is all blank
{
$('#initial_table').show();
$('#ajax').hide();
}
}
I have a datatable that use two Ajax Calls to load data in it. I was following demo here JSFiddle
I'm trying to get from the first Ajax call all data about replies, and load them in the parent row.
then I'm trying to get from the second Ajax call all attachments related to the reply, by reply id, so I want to get in each parent row (reply id, and other data related to the reply), and I want to get in the child row all attachments related to this particular (reply id) , [for now I'm using fileName for loading the attachments]
so the table will load all replies, and when the user click on the first "td" to open the child row, the user must see only attachments that are related to this reply, and when the user open another child row , will see different attachment, which are related only to the reply that he clicked on its "td"
my problem is with the child row, it doesn't load anything, and when I put fixed id in the ajax call, it load same files in all child rows, but I don't want that, I want each child row to load only related attachments (attachments by reply id)
I spent 5 days trying , but I couldn't solve it, and also I didn't find any similar problem in the net that can help.
is it possible to achieve what I want using datatable?
here is my HTML code
<table id="replyTable" class="display table-bordered nowrap" cellspacing="0" width="100%">
<thead>
<tr>
<th>Attachments</th>
<th>Reply ID</th>
<th>Ticket ID</th>
<th>Message</th>
<th>Transaction Status</th>
<th>Created Date</th>
</tr>
</thead>
<tbody></tbody>
</table>
here is my JS code
<script>
$(document).ready(function () {
var TicketID = $("#txtTicketID").val();
var table = $('#replyTable').DataTable({
ajax: {
type: "GET",
url: "/api/TicketsReplies/GetTicketsRepliesByTicketID/" + TicketID,
dataSrc: "",
datatype: 'json',
cache: false,
},
columns: [
{
className: "details-control",
orderable: false,
defaultContent: ""
},
{
className: "replyIdClass",
data: "id",
},
{ data: "ticketsId" },
{ data: "message" },
{ data: "transactionStatus.nameEnglish" },
{ data: "createdDate" }
],
"order": [[1, 'asc']]
});
// Add event listener for opening and closing details
$('#replyTable').on('click', 'td.details-control', function () {
var tr = $(this).closest('tr');
var row = $('#replyTable').DataTable().row(tr);
if (row.child.isShown()) {
// This row is already open - close it
row.child.hide();
tr.removeClass('shown');
} else {
// Open this row
format(row.child);
tr.addClass('shown');
}
});
function format(callback) {
var IdValue = $('#replyTable').find('.replyIdClass').text();
$('.replyIdClass').each(function (i) {
var repId = $(this).text();
$.ajax({
url: '/api/TicketAttachmentApi/GetRepliesAttachments/' + repId,
dataType: "json",
complete: function (response) {
var data = JSON.parse(response.responseText);
console.log(data);
var tbody = '';
$.each(data, function (i, d) {
tbody += '<tr><td>' + d.fileName + '</td><td>' + d.id + '</td></tr>';
});
console.log('<table>' + tbody + '</table>');
callback($('<table>' + tbody + '</table>')).show();
},
error: function () {
$('#output').html('Bummer: there was an error!');
}
});
});
}
});
</script>
Finally after 4 days trying, I could solve the problem, after better understanding how the datatable and child row work, so I would like to put my solution here, so maybe I can benefit others who have same problem.
well the problem here is using foreach in format function to get the replies ids, it is wrong, I must pass the reply id from the child row where I clicked the cell, to the format function and retrieve only the attachment where the reply id = the reply id in the cell where I clicked
here is my solution, it is working perfectly.
This is the HTML
<input type="hidden" value='#ViewContext.RouteData.Values["id"]' id="txtTicketID" />
<table id="replyTable" class="display table-bordered table-hover" cellspacing="0" width="100%">
<thead>
<tr>
<th>Attachments</th>
<th>Reply ID</th>
<th>Message</th>
<th>Transaction Status</th>
<th>Created Date</th>
</tr>
</thead>
<tbody></tbody>
</table>
here is the Ajax and jQuery code
<script>
$(document).ready(function () {
var TicketID = $("#txtTicketID").val();
// Get Replies From API by TicketID
var table = $('#replyTable').DataTable({
ajax: {
type: "GET",
url: "/api/TicketsReplies/GetTicketsRepliesByTicketID/" + TicketID,
dataSrc: "",
datatype: 'json',
cache: false,
},
columns: [
{
className: "details-control",
orderable: false,
defaultContent: ""
},
{
className: "replyIdClass",
data: "id",
},
{
data: "message",
},
{ data: "transactionStatus.nameEnglish" },
{ data: "createdDate" }
],
"order": [[1, 'asc']]
});
// Add event listener for opening and closing details
$('#replyTable').on('click', 'td.details-control', function () {
var id = $(this).closest("tr").find('.replyIdClass').text();
var tr = $(this).closest('tr');
var row = $('#replyTable').DataTable().row(tr);
if (row.child.isShown()) {
// This row is already open - close it
row.child.hide();
tr.removeClass('shown');
} else {
// Open this row
format(row.child, id); // here pass the reply id to function format
tr.addClass('shown');
}
});
function format(callback, vRid) {
var TicketID = $("#txtTicketID").val();
var repId = $(this).text();
$.ajax({
type: "GET",
url: "/api/TicketAttachmentApi/GetRepliesAttachments/" + vRid,
dataType: "json",
cache: false,
complete: function (response) {
var data = JSON.parse(response.responseText);
console.log(data);
var tbody = "";
$.each(data, function (i, d) {
tbody += "<tr><td><a href='/Attachments/Tickets/" + TicketID + "/Replies/"
+ vRid + "/" + d.fileName + "' target='_blank'>" + d.fileName + "</a></td></tr>";
});
console.log("<table>" + tbody + "</table>");
callback($("<table>" + tbody + "</table>")).show();
},
error: function () {
$('#output').html('Bummer: there was an error!');
}
});
} //-- end format (callback)
});
</script>
I have this JavaScript
function pickdet(Id) {
//alert(Id);
var dd = Id;
$.ajax({
cache: false,
url: "/PVSigns1/GetDetails",
data: { 'Id' : Id },
type: "GET",
dataType: "json",
success: function (data) {
//alert('i dey here')
var row = "";
var baseurl = '#Url.Action("Edit","PVSigns1")' + '?Id=';
$.each(data, function (index, item) {
var clickUrl = baseurl + item.PVSignId;
//row += "<tr><td>" + item.VitalSigns.Sign + "</td><td>" + item.SignValue + "</td><td> <input type= 'button' onclick= location.href = + '<Url.Action("Create", "PVSigns1", new { Id = item.PVSignId }) ' />" + "</td></tr>";
row += "<tr><td>" + item.VitalSigns.Sign + "</td><td>" + item.SignValue +
"</td><td> <button class='editbtn btn btn-xs btn-success' data-url = '" + clickUrl + "'> <i class='fa fa-edit fa-lg'></i> Edit</button></td></tr>";
});
$("#pvv").html(row);
},
error: function (result) {
$("#pvv").html('Nothing to show <br /> <p />' + result);
}
});
}
$(function () {
$("button.editbtn").click(function (e) {
alert("url");
e.preventDefault();
//e.defaultPrevented();
window.location.href = $(this).attr("url");
});
});
When I run it, it display perfectly on the browser, but the link created don't work, and when I view the page source, the tbody part which the code above is supposed to inject, doesn't get rendered.
This is what I get, Click on any of the green buttons
in the top table, it loads the second table. The issue is with the second table.
Note: I am using JQuery Datatables.
This the rendered output from page source
<div>
<h3> Details</h3>
<table id="Pv" class="table table-condensed">
<thead>
<tr>
<th>Sign</th>
<th> Value </th>
<th></th>
</tr>
</thead>
<tbody id="pvv">
</tbody>
</table>
Notice <tbody id="pvv"> is empty, not table elements there. What is the issue?
You need to use delegation of dom element for click event. which element generated after binding event after existing dom
$("#Pv").on('click','button.editbtn', function (e) {
alert("url");
e.preventDefault();
//e.defaultPrevented();
window.location.href = $(this).attr("url");
});
I want to check domain availability with php and ajax request. Requests will be sent to "whois.apitruck.com" API like this: "whois.apitruck.com/domain.com".
For each domain, a request is sent. I want to append table after complate all ajax request but this not work!
$(document).ready(function () {
$("#submit").click(function () {
var domain = $('#domains').val().split("\n");
var all_suffix = ["com","net","org","ir","biz","info","us","name","pro","eu","in","me","tv","cc"];
var counter = 0;
var TableDataString = '<table class="table table-bordered table-striped table-responsive domain-table"><thead><tr><th>ID</th><th>Domain Name</th><th>.Com</th><th>.Net</th><th>.Org</th><th>.Ir</th><th>.Biz</th><th>.Info</th><th>.Us</th><th>.Name</th><th>.Pro</th><th>.In</th><th>.Me</th><th>.Tv</th><th>.Cc</th></tr></thead><tbody>';
var domain_count = domain.length;
$.each(domain, function (i, val) {
//increase i counter
counter++;
TableDataString += '<tr><td>'+ counter +'</td><td>'+ val +'</td>';
$('input[type=checkbox]:checkbox:checked').each(function () {
var flag = '';
var suffix = $(this).val();
$.ajax({
type: "POST",
url: "includes/ajax/ajax.php",
dataType: "json",
data: {domain: val, suffix: suffix},
success: function (msg) {
flag = msg.suc;
},
error: function (err) {
$('#domain_tables').html(err.error);
}
});//end $.ajax
if(flag){TableDataString += '<td><i class="fa fa-times"></i></td>';}else{TableDataString += '<td><i class="fa fa-check"></i></td>';}
});//end get each suffix
TableDataString += '</tr>';
});//end each domain
TableDataString += '</tbody></table>';
if(counter === domain_count){
$(document).ajaxComplete(function(){
$('#domain_tables').append(TableDataString);
});
}
});
});
I am used a flag and check this after $.ajax. The display problem solved. But for each ajax request echo a new table, If that display one table for all ajax request. How to append table after complate all ajax request?! Another problem is that check flag does not work properly! why?!
You're using .append() on your $('#domain_tables'), so that each time a new table is generated. You should empty the #domain_tables div before making another AJAX request(s) queue.
You're not checking which check-boxes are checked and which are not, so that you only create <td> elements for chechbox:checked.
Even if you add all necessary <td> elements, these generated in AJAX success callback will be added at the end of the table, because your loop runs faster than AJAX request (simply saying). You have to state which <td> element belong to which AJAX request.
I'd go this way:
$(document).ready(function () {
$("#submit").click(function () {
// check if anything is selected:
if(!$('#domains').val() || !$('[type="checkbox"]:checked').length){
return false;
}
// disable the button:
var btn = $(this).prop('disabled', true);
var domain = $('#domains').val().split("\n");
var counter = 0;
// an indicator to state when the button should be enabled again:
var ajaxQueue = 0;
var Table = '<table class="table table-bordered table-striped table-responsive domain-table"><thead><tr><th>ID</th><th>Domain Name</th><th>.Com</th><th>.Net</th><th>.Org</th><th>.Ir</th><th>.Biz</th><th>.Info</th><th>.Us</th><th>.Name</th><th>.Pro</th><th>.Eu</th><th>.In</th><th>.Me</th><th>.Tv</th><th>.Cc</th></tr></thead><tbody>';
// create the td elements, but do not perform AJAX requests there:
$.each(domain, function (i, val) {
counter++;
Table += '<tr><td>'+ counter +'</td><td>'+ val +'</td>';
$('input[type=checkbox]').each(function () {
if($(this).is(':checked')){
ajaxQueue++;
// if checkbox is checked make td element with specified values and a "load-me" class:
Table += '<td class="load-me" data-domain="'+val+'" data-suffix="'+$(this).val()+'"><small>loading...</small></td>';
}else{
Table += '<td><span class=text-muted><i class="fa fa-minus"></i></span></td>';
}
});
Table += '</tr>';
});
// Replace HTML of the 'domain_tables' div and perform AJAX request for each td element with "load-me" class:
$('#domain_tables').html(Table+'</tbody></table>').find('td.load-me').each(function(){
var td = $(this);
$.ajax({
type: "POST",
url: "includes/ajax/ajax.php",
dataType: "json",
data: {domain: td.attr('data-domain'), suffix: td.attr('data-suffix')},
success: function (msg) {
// decrease ajaxQueue and if it's 0 enable button again:
ajaxQueue--
if(ajaxQueue === 0){
btn.prop('disabled', false);
}
if(msg.suc == false){
td.html('<span class=text-danger><i class="fa fa-times"></i></span>');
}else{
td.html('<span class=text-success><i class="fa fa-check"></i></span>');
}
},
error: function (err) {
$('#domain_tables').html(err.error);
}
});
});
});
});
My final answer is look like this:
$(document).ready(function () {
$("#submit").click(function () {
var domain = $('#domains').val().split("\n");
var all_suffix = ["com","net","org","ir","biz","info","us","name","pro","eu","in","me","tv","cc"];
var counter = 0;
var TableDataString = '<table class="table table-bordered table-striped table-responsive domain-table"><thead><tr><th>ID</th><th>Domain Name</th><th>.Com</th><th>.Net</th><th>.Org</th><th>.Ir</th><th>.Biz</th><th>.Info</th><th>.Us</th><th>.Name</th><th>.Pro</th><th>.In</th><th>.Me</th><th>.Tv</th><th>.Cc</th></tr></thead><tbody>';
var domain_count = domain.length;
$.each(domain, function (i, val) {
//increase i counter
counter++;
TableDataString += '<tr><td>'+ counter +'</td><td>'+ val +'</td>';
$('input[type=checkbox]:checkbox:checked').each(function () {
var flag = false;
var suffix = $(this).val();
$.ajax({
type: "POST",
url: "includes/ajax/ajax.php",
dataType: "json",
data: {domain: val, suffix: suffix},
success: function (msg) {
flag = msg.suc;
if(flag){TableDataString += '<td><i class="fa fa-times"></i></td>';}else{TableDataString += '<td><i class="fa fa-check"></i></td>';}
TableDataString += '</tr>';
},
error: function (err) {
$('#domain_tables').html(err.error);
}
});//end $.ajax
});//end get each suffix
});//end each domain
if(counter === domain_count){
TableDataString += '</tbody></table>';
$('#domain_tables').append(TableDataString);
}
});
});
I think this will solve your last two mentioned problem.
I'm aware that there are other questions similar to this one, however the way I've executed my code is much different and so it's complicated in how I'm supposed to implement the code into the script.
After executing an Ajax function when I click a button to delete a row, I want that row to fade out however each time I add to code to fade out there's always an error in the console.
Here is the HTML
<tr class="shift_type1">
<td>Date</td>
<td>Location</td>
<td>Name</td>
<td>Time One</td>
<td>Time Two</td>
<td class="controlbuttons">
<div class="settings">
<span class="icons"><img src="http://i.imgur.com/nnzONel.png" alt="X" /></span>
<span class="icons" onclick="deleteRow('rowcodehereinphp')">Delete</span>
<div class="icons">Edit</div>
<div class="icons">Fill</div>
</div>
</td>
</tr>
Here is the jQuery I use to delete the entry from my SQL database
<script type="text/javascript">
function fadeTr(code) {
$(this).closest('tr').find('td').fadeOut(1000,
function(){
// alert($(this).text());
$(this).parents('tr:first').remove();
});
}
function deleteRow(code) {
var proceed = true;
if (proceed) {
post_data = {'code': code};
$.post('DeletePush.php', post_data, function (response) {
if (response.type == 'error') {
output = '<div class="error">' + response.text + '</div>';
} else {
output = '<div class="success">' + response.text + '</div>';
}
if (response.type == 'error') {
$("#result").hide().html(output).slideDown();
}
else {
$("#result").hide().html(output).slideDown().fadeTr(code);
}
}, 'json');
}
};
Console Log Error
Uncaught TypeError: undefined is not a function
(anonymous function)
j
k.fireWith
x
b
Do this in a little different and easier way :
Suppose your html markup is like this below.
Just add the code to the class or the row. For example
<tr class="shift_type1_<?php echo $rowcodehereinphp; ?>">
.
.
.
</tr>
After this in your jquery or javascript
$(".shift_type1_"+code).fadeOut(slow);
Here "code" is the parameter which you will receive in your deleteRow(code) function.
Hope that helps.. Cheers..
you have to pass the selector of the row to be deleted and remove live function in fadeTr function. You can do something like this
<script type="text/javascript">
function deleteRow(code) {
var proceed = true;
if (proceed) {
post_data = {'code': code};
$.post('DeletePush.php', post_data, function (response) {
if (response.type == 'error') {
output = '<div class="error">' + response.text + '</div>';
} else {
output = '<div class="success">' + response.text + '</div>';
}
if (response.type == 'error') {
$("#result").hide().html(output).slideDown();
}
else {
$("#result").hide().html(output).slideDown().live(fadeTr(this));
}
}, 'json');
}
};
</script>
<script>
function fadeTr(row) {
$(row).closest('tr').find('td').fadeOut(1000,
function(){
// alert($(this).text());
$(this).parents('tr:first').remove();
});
}
</script>