How to append table after complate all ajax request - javascript

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.

Related

Continue counting serial number affer page on pagination

I am displaying data results from database with php, ajax and jquery.
I have used codeigniter 4 pager library for pagination. But when I click the next page of pagination the serial number reset and start again from 1-10, all I want is when i click the next page to continue counting a serial number from 11-20, 21-30 etc...
Help please. Thank you.
//html table
<table>
<thead>
<tr>
<th>No.</th>
<th>MyColumn</th>
</tr>
</thead>
<tbody class="result"></tbody>
</table>
//jquery
show();
function show(){
let ajax = $.ajax({
url : '/Controller/getAll',
method : 'post',
dataType: 'json',
cache : false
});
ajax.done(function(data){
let serialNumber = 1;
$.each(data.result, function(k, v){
html += `<tr>
<td>${serialNumber}</td>
<td>${v.myColums}</td>
</tr>`;
serialNumber++;
});
});
$('.result').html(html);
}
// php controller
public function getAll()
{
$result = $this->model->getData()->asObject()->paginate('10');
$pager = $this->model->pager;
foreach($result as $row){
$output[] = [
'id' => $row->id,
'myColumn' => $row->myColumn,
];
}
$jsonArray = [
'result' => $output,
'pager' => $pager->links(),
];
return $this->response->setJSON($jsonArray);
}
You are initializing serialNumber when you receive a ajax response. Do it on page load.
function show(){
let ajax = $.ajax({
url : '/Controller/method',
method : 'post',
dataType: 'json',
cache : false
});
ajax.done(function(data){
let serialNumber = 1; // move this to page load
$.each(data.result, function(k, v){
html += `<tr>
<td>${serialNumber}</td>
<td>${v.myColums}</td>
</tr>`;
serialNumber++;
});
});
$('.result').html(html);
}
Declare a variable outside of the function
let serialNumber = 1;
function show(){
let ajax = $.ajax({
url : '/Controller/getAll',
method : 'post',
dataType: 'json',
cache : false
});
ajax.done(function(data){
$.each(data.result, function(k, v){
html += `<tr>
<td>${serialNumber}</td>
<td>${v.myColums}</td>
</tr>`;
serialNumber++;
});
});
}
Another option is to return the page number from PHP and calculate the start point of the serial
You can try this:
$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 1;
$data["slno_start"] = (($page-1) * $config["per_page"]) + 1;

Redirect to URL in json response

I have two files fetch.php and index.php. The fetch.php file does a search and converts the results to Json.
Index.php has Jquery which loops through the Json result. One of the cells contains a URL. How can I get a user to redirect to the URL.
//index.php==============================
<script>
$(document).ready(function(){
function load_data(query)
{
$.ajax({
url:"fetch.php",
method:"POST",
data:{query:query},
dataType:"json",
success:function(data)
{
$('#total_records').text(data.length);
var html = '';
if(data.length > 0)
{
for(var count = 0; count < data.length; count++)
{
html += '<hr>';
html += '<tr>';
html += '<div>'+data[count].title+'</div>';
html += '<td>'+data[count].book+'</td><tr/>';
html += '<br/><td>'+data[count].description+'</td><tr/>';
html += '<td><button> VIEW </button> '+data[count].url+'</td>'; //Is there a way to redirect to this URL by clicking on the VIEW button
html += '<hr>';
}
}
else
{
html = '<tr><td colspan="5">No Data Found</td></tr>';
}
$('tbody').html(html);
}
})
}
$('#search').click(function(){
var query = $('#search_id').val();
load_data(query);
});
</script>
Simple solution:
html += '<td><button onclick="window.location.href=\''+data[count].url+'\'"> VIEW </button> '+data[count].url+'</td>';
Consider the following suggestions:
$(function() {
function load_data(q) {
$.ajax({
url: "fetch.php",
method: "POST",
data: {
query: q
},
dataType: "json",
success: function(data) {
$('#total_records').text(data.length);
var row;
if (data.length > 0) {
$.each(data, function(k, d) {
row = $("<tr>");
$("<td>").html(d.title).appendTo(row);
$("<td>").html(d.book).appendTo(row);
$("<td>").html(d.description).appendTo(row);
var e = $("<td>").appendTo(row);
$("<button>").html("VIEW").click(function(e) {
window.location.href = d.url;
}).appendTo(e);
});
} else {
row = $("<tr>");
$("<td>", {
colspan: 4
}).html("No Results Found.").appendTo(row);
}
}
});
}
$('#search').click(function() {
var query = $('#search_id').val();
load_data(query);
});
});
As you can see, this makes use of a few more jQuery parts to help slimline your code. Additionally, we create a Click event callback when the button is created and added to the table.
You had a lot of improper HTML Syntax. My example does not replicate that. A Row Element should contain Cells and not other elements. Yes, you can do it, yet it's not good practice. This is why I removed them. If they are needed for some reason, you should provide a more complete example so it's clear why they are needed.

Select Row from table with JSON values using JQuery

I have JSON data from an MVC controller with the values
[{"OperationName":"All","PrivilegeName":"Roles Crud"},{"OperationName":"Read","PrivilegeName":"Roles Read Delete"},{"OperationName":"Delete","PrivilegeName":"Roles Read Delete"},{"OperationName":"Read","PrivilegeName":"Roles Update"},{"OperationName":"Update","PrivilegeName":"Roles Update"}]
I have Displayed this JSON data into an HTML table using AJAX.
$(document).ready(function () {
//debugger;
$.ajax({
url: "/Home/GetOpPriv",
type: "GET",
contentType: "application/json; charset=utf-8",
data: "source={}",
dataType: "json",
success: function (data) {
var row = "";
$.each(data, function (index, item) {
row += "<tr id='trName_" + index + "'>";
row += "<td id='td_OpName" + index + "'>" + item.OperationName + "</td>";
row += "<td id='td_PrivName" + index + "'>" + item.PrivilegeName + "</td>";
row += "<tr>";
});
$("#table1").html(row);
console.log(data);
var source = [];
source.push(data);
console.log(source);
},
error: function (result) {
alert("Error");
}
})
});
I'm Trying to select individual rows from the table when I click the particular row, it should display its value in the alert box
But instead, it's displaying the entire table JSON data onClick.
What correction should I make to this JQuery Function?
$(document).ready(function () {
$("#table1 tr").click(function () {
debugger;
$('.selected').removeClass('selected');
$(this).parents('tr').addClass('selected');
})
});
As I understand your question, you want to display the selected row data, for this scenario, you can try like this
$("#table1 tr").click(function () {
$('.selected').removeClass('selected');
$(this).addClass('selected');
var _index = $(this).attr("id").replace("trName_", "");
var _currentSelectedRow = source[_index];
console.log(_currentSelectedRow);
});
And in ajax success block you are declaring the variable as
var source = [];
source.push(data);
Instead of this declare the 'source' variable as global variable and assign the json data to 'source' in ajax success block.
source = data;
If I understand your question correctly, then the solution is this:
$(document).ready(function () {
$("#table1 tr").click(function () {
$('.selected').removeClass('selected');
$(this).addClass('selected'); // remove .parents('tr')
})
});
By making the change above, this will cause only the row that the user clicks in #table1 (i.e. the row element corresponding to $(this) ) to have the selected class applied.
You are guaranteed to have $(this) inside of your click handler correspond to a table row element, seeing that the click handler is bound to tr elements via the #table tr selector. Hope this helps!

How to make table updating content without refresh the whole page

i've made a project using php ajax i use it for input data and displaying data into a table. the code work fine but when displaying data the table content didnt update the latest input in there i need to refresh page to update them.
anyone know how to make it update without refresh the whole page?
this my ajax function for input and displaying
INPUT
$(document).on('click','#ok',function(e) {
if ($('#netto').val() == '') {
alert('Kolom Netto Tolong Di Isi');
} else {
var data = $("#form_input").serialize();
$.ajax({
data: data,
type: "post",
url: "../php/bkk/bkk_i.php",
success: function(data){
alert("Data: " + data);
}
});
}
clearInput();
});
$("#form_input").submit( function() {
return false;
});
function clearInput() {
$("#form_input :input").each( function() {
$('#nopol').val('');
$('#netto').val('');
});
}
Display
$(document).ready(function(){
$.ajax({
type: "Post",
url: "../php/bkk/bkk_isel.php",
success: function(data){
var list = JSON.parse(data);
for(var i = 0; i < list.length; i++){
$('#mat').val((list[i]['material']));
$('#lok').val((list[i]['lokasi']));
$('#kpl').val((list[i]['kapal']));
$('#po_numb').val((list[i]['po']));
$('#dok').val((list[i]['doc_mat']));
var tr = "<tr>";
tr += "<td>"+list[i]['no']+"</td>";
tr += "<td>"+list[i]['tanggal']+"</td>";
tr += "<td>"+list[i]['no_pol']+"</td>";
tr += "<td>"+list[i]['netto']+"</td>";
tr += "</tr>";
$("#table_s tbody").append(tr);
}
return false;
}
});
});

jQuery: Appeding tr to table tbody prevents tr click functions [duplicate]

This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 7 years ago.
After executing a query, a table row is added, good, it gives the user the option to delete that row with a Delete button, here is when things start to get fussy, any function related to the appended tr just won't work,even when I changed the button.click to a whole tr, it deletes the headers tr and every other table tr except for the appended ones!
Just to clarify, the table is inside a form that is not #codbar
$('#codbar').submit(function(e)
{
e.preventDefault();
$.ajax(
{
url: "/GoogleStore/ajax/venta.php",
data: {'iditem': $('#id-item').val()},
dataType: "json",
type: "GET",
success: function (data, status, jqXhr)
{
var i = 0;
var end = parseInt($('input[name = "contador"]').val());
for(i = 0; i <= end; i++)
{
if($('input[name = "cod'+i+'"]').length && $('input[name = "cod'+i+'"]').val() == data["Cod"])
{
$('input[name = "cant'+i+'"]').val(parseInt($('input[name = "cant'+i+'"]').val()) + 1);
$('span[name = "total'+i+'"]').text(parseFloat($('input[name = "cant'+i+'"]').val()) * parseFloat($('input[name = "precio'+i+'"]').val()));
i = end;
}
else if(i == end)
{
$('input[name = "contador"]').val();
$('table[name = "venta"]').find('tbody').append($('<tr><td><span>'+data["Prod"]+'</span></td><td><input type="hidden" name="cod'+i+'" value="'+data["Cod"]+'"><span>'+data["Cod"]+'</span></td><td><input type="text" name="cant'+i+'" value="1"></td><td><input type="hidden" name="precio'+i+'" value="'+data["Precio"]+'"><span>'+data["Precio"]+'</span></td><td><span name="total'+i+'">'+data["Precio"]+'</span></td><td><input type="button" class="red" name="DeleteRow" value="Eliminar"></td></tr>'));
$('input[name = "contador"]').val(end + 1);
}
}
},
error: function (jqXhr, textStatus, errorThrown)
{
console.log("Error response:", jqXhr.responseText);
}
});
});
$("input[name = 'DeleteRow']").click(function()
{
alert('');
$(this).closest('tr').fadeOut('slow', function()
{
$(this).closest('tr').remove();
});
});
You need to delegate the event to the static parent:
$(document).on('click', "button[value = 'Eliminar']", function()
change to this as above.
Because you are appending the tr dynamically so any event registered on static elements won't be bound on newly created element.
Try this
$("table[name = "venta"]").on("click","button[value = 'Eliminar']",function()
{
alert('');
$(this).closest('tr').fadeOut('slow', function()
{
$(this).closest('tr').remove();
});
});

Categories