After Ajax call succeed, DataTables search box doesn't work - javascript

I'm working on a project that php, js, jquery, datatables are included.
I'm sending post call to a PHP page to change my table data, it's running successfully as you see. After this call, I can't use my DataTable search feature strangely. May be the error is about $(".gunlukgelir").load(" .gunlukgelir"); when Ajax call is succeed, I reflesh the tables with the .gunlukgelir class name.
Libraries:
https://cdn.datatables.net/1.10.16/css/dataTables.bootstrap.min.css
https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js
https://cdn.datatables.net/1.10.16/js/dataTables.bootstrap.min.js
https://code.jquery.com/jquery-3.3.1.min.js
my Ajax call:
$(function() {
$("#gelirgetir").click(function() {
var gelirtablosecimi = $("#select1").val();
if (gelirtablosecimi) {
$.ajax({
type: "POST",
url: "tabloyenile.php",
data: {
"gelirtablosecimi": gelirtablosecimi
},
success: function(result) {
$(".gunlukgelir").load(" .gunlukgelir");
//$(".gunlukgelir").load(window.location + " .gunlukgelir");
notifyUser('success', 'Başarılı!', 'Tablo başarıyla güncellendi');
},
error: function(result) {
notifyUser('error', 'Hata', 'error');
}
});
} else {
notifyUser('info', 'Dikkat', 'Tablo seçimi yapmadınız!');
}
});
HTML part:
<div class="form-group col-xs-6">
<select id="select1" class="selectpicker" data-live-search="true" title="Gelirler">
<?php echo $geliroptions;?>
</select>
<input type="submit" id="gelirgetir" value="Getir" class="btn btn-success" />
<h1>Aylık Gelir Raporları</h1>
<table id="" class="display table table-stripe table-hover table-row-border table-order-column table-nowrap gunlukgelir">
<thead>
<tr>
<th>Tarih</th>
<th>Günlük Toplam</th>
</tr>
</thead>
<?php
$gelirtabloadi = $_SESSION["gelirtabloadi"];
$gelirgunluktoplam = $db->prepare("select tarih, hasilat + visa + butce_ici + hisse_satis + sosyal_konut + elektrik + haberlesme + iller_bank + diger AS Toplam from $gelirtabloadi");
$gelirgunluktoplam->execute();
while($row = $gelirgunluktoplam->fetch()){
echo '
<tr>
<td>'.$row["tarih"].'</td>
<td>'.$row["Toplam"].'</td>
</tr>
';
}
?>
</table>
</div>
and PHP that Ajax calls:
<?php
session_start();
if($_POST['gelirtablosecimi'] && $_POST['gidertablosecimi']){
$gidertabloadi = $_POST["gidertablosecimi"];
$gelirtabloadi = $_POST["gelirtablosecimi"];
$_SESSION["gelirtabloadi"] = $gelirtabloadi;
$_SESSION["gidertabloadi"] = $gidertabloadi;
}
if($_POST["gelirtablosecimi"]){
$gelirtabloadi = $_POST["gelirtablosecimi"];
$_SESSION["gelirtabloadi"] = $gelirtabloadi;
}
if($_POST['gidertablosecimi']){
$gidertabloadi = $_POST["gidertablosecimi"];
$_SESSION["gidertabloadi"] = $gidertabloadi;
}
?>
Any suggestion? Thanks in advance!

I also had such a problem. Just add .DataTable() in success function of ajax after assigning the data to data table.
It has been working for me.
Just write it as follows:
function TaxLoad() {
$.ajax({
url:"myCode.php",
type:"POST",
data:{functionName:"showTax"},
success:function(data) {
$("#tblTaxBody").html(data);
var table= $("#dtTable").DataTable();
}
});
}`

Probably this issue related with my problem in the Docs. If It reinitialised, it would be searching: false Anyway, If one day anybody sees this problem, just change your table choice to Bootstrap-Table. It's much more stable.

Related

Refreshing a table without reloading a page in spring mvc using javascript

I am having a simple table which shows basic details about cusotmers. Each customer belongs to one of available customer groups. I also have a dropdown on the top of it where I can toggle between available customer groups and want to update the table with customers belonging to that particular group. Right now everything happens using page reload which is quite inefficient I know. Is there a way to use js here and make only the table section refresh without reloading the entire page.
#GetMapping(WebControllerConstants.RIDER_MAPPING)
public ModelAndView riderMapping(#RequestParam(value = "groupId", required = false) String groupId) {
String group = "1";
if (groupId != null) {
group = groupId;
}
ModelAndView model = new ModelAndView("riderGroupDetails");
model.addObject("list", riderService.findRiderByGroupId(group));
model.addObject("riderGroupList", riderGroupService.findAllGroups());
return model;
}
<select id="category" name="category" onchange="GetAllDetails(this.value);">
//some options here
</select>
<table class="table table-striped table-bordered zero-configuration dataTable">
<thead>
<tr>
<th>ID</th>
<th>FirstName</th>
<th>LastName</th>
<th>Mobile No</th>
</thead>
<tbody>
<c:set var="id" value="${1}" />
<c:forEach var="rider" items="${list}">
<tr>
<td>
<c:out value="${id}" />
</td>
<td>
<c:out value="${rider.firstname}" />
</td>
<td>
<c:out value="${rider.lastname}" />
</td>
<td>
<c:out value="${rider.mobile}" />
</td>
</tr>
<c:set var="id" value="${id + 1}" />
</c:forEach>
</tbody>
</table>
<script>
$(window).on(
'load',
function() {
$.urlParam = function(name) {
var results = new RegExp('[\?&]' + name + '=([^&#]*)')
.exec(window.location.search);
return (results !== null) ? results[1] || 0 : false;
}
if ($.urlParam('groupId') == false) {
} else {
var groupId = $.urlParam('groupId');
console.log('groupId ' + groupId);
$("#category").val(groupId);
}
});
function GetAllDetails(value) {
groupvalue = value;
console.log(groupvalue);
var url = "${context}/rider/mapping?groupId=" + value;
//AJAX works here to send a request but table doesn't refresh.
window.location = url;
}
</script>
//AJAX works here to send a request but table doesn't refresh.
Here your AJAX could listen to a response code. If the code says transaction happened correctly you could create a js function that updates the page info while not refreshing it. The new info can be handled from js from the begining or on the response you can pass the info to be updated and pass it to the redrawing function.
Example:
function updateDBService(request){
var dataStr = JSON.stringify(request);
var url = '/updateDBService';
$.ajax({
url: url,
contentType: "application/json",
data: dataStr,
type: "POST",
statusCode: {
403: function () {
},
404: function () {
},
500: function (data) {
}
},
//This is your response object (data), which you can use to update the onscreen info
success: function (data) {
redrawInfo();
},complete: function(data) {
}
});
}
For this I usually create a controller different from the views controller so I can handle response classes, request classes and all sorts of stuff. Here a controller that uses POST method would be required.
Hopefully this helps you!

jquery $(this).data not working properly in dataTables

I have a table in html and I use DataTable for my tables I show a brief info of my users data in this table, and I have a button in the last column
<tr role="row" class="odd">
<td class="sorting_1">1</td>
<td>یوسف توکلی</td>
<td>۲۹۶۰۰۰۰۴</td>
<td>۹۸۷۶۵۴۳۲۱</td>
<td>مهندسی فناوری اطلاعات</td>
<td>دیپلم</td>
<td>کاربر</td>
<td><button type="button" data-toggle="modal" data-user="192" data-target=".bs-example-modal-lg1" class="detailes btn btn-default btn-md m-t-10">جزئیات</button></td>
</tr>
this button show a modal contain details of that user. I use AJAX for getting data from server using data-user as a key.
This ajax request work fine for top 10 user but for others request not sent and when we click on button in model showed last request data
this is my ajax request
$(document).ready(function () {
$(".detailes").click(function (event) {
event.preventDefault();
var user_id = $(this).attr('data-user');
jQuery.ajax({
type: "POST",
url: "<?php echo base_url(); ?>" + "admin/user_detailes",
dataType: 'json',
data: {view_id: user_id},
success: function(res) {
// res = JSON.stringify(res);
console.log(res);
if (res){
$("#myLargeModalLabel").html(' <i class=" ti-angle-double-left"></i> ' + res.firstname + " " + res.lastname );
$(".code").html(res.code);
$(".ncode").html(res.ncode);
$(".firstname").html(res.firstname + " " + res.lastname);
$(".jplace").html(res.jplace);
$(".phone").html(res.phone);
$(".mobile").html(res.mobile);
$(".mail").html(res.mail);
$(".website").html(res.website);
$(".gender").html(res.gender);
$(".marriage").html(res.marriage);
$(".field").html(res.field);
$(".degree").html(res.degree);
$(".father").html(res.father);
$(".last_click_time").html(res.last_click_time);
$(".birthday").html(res.birthday);
$(".job").html(res.job);
$(".username").html(res.username);
$(".level").html(res.level);
$(".birthdate").html(res.birthdate);
$(".reg_time").html(res.reg_time);
}
}
})
})
});
Any one knows what happens?

Store HTML Table Data into Javascript Array

I'm trying to store table data to Javascript array and send the array to php.
<div>
<h5>PUT SOMETHING 1</h5>
<input type="text" id="sample1" palceholder="SOMETHING" required>
</div>
<div>
<h5>PUT SOMETHING 2</h5>
<input type="text" id="sample2" palceholder="SOMETHING" required>
</div>
<div>
<h5>PUT SOMETHING 3</h5>
<input type="text" id="sample3" palceholder="SOMETHING" required>
</div>
<div>
<button style="margin-top: 20px;" type="button" onclick="output();">OUTPUT</button>
</div>
<div style="margin-top: 10px;">
<table class="table table-striped projects" id="table">
<thead>
<tr>
<th>sample1</th>
<th>sample2</th>
<th>sample3</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
<div>
<button type="button" onclick="submit();">SUBMIT</button>
</div>
Here's my script
function delete_row(r) {
var result = confirm("Are you sure? Delete row from order?");
if (result) {
var i = r.parentNode.parentNode.rowIndex;
document.getElementById("table").deleteRow(i);
}//if(result)
}//delete_row();
function output() {
var sample1 = document.getElementById("sample1").value;
var sample2 = document.getElementById("sample2").value;
var sample3 = document.getElementById("sample3").value;
var table = document.getElementById("table");
var row = table.insertRow(table).outerHTML = "<tr id='row'><td>" + sample1
+ "</td><td>" + sample2 + "</td><td>" + sample3 +
"</td><td> <a href='#' onclick='delete_row(this)'>Remove </a></td></tr>";
}//output();
function submit() {
//Store HTML Table Values into Multidimensional Javascript Array Object
var TableData = new Array();
$('#table tr').each(function(row, tr) {
TableData[row] = {
"sample1": $(tr).find('td:eq(0)').text(),
"sample2": $(tr).find('td:eq(1)').text(),
"sample3": $(tr).find('td:eq(2)').text()
}//tableData[row]
});
TableData.shift(); // first row will be empty - so remove
alert(TableData);
var Data;
Data = $.toJSON(TableData);
$.ajax({
type: "POST",
url: "getInfo.php",
data: "pTableData=" + TableData,
success: function(msg) {
//return value stored in msg variable "success";
}//success
});
}//submit();
my php
<?php
// Unescape the string values in the JSON array
$tableData = stripcslashes($_POST['pTableData']);
// Decode the JSON array
$tableData = json_decode($tableData,TRUE);
// now $tableData can be accessed like a PHP array
echo $tableData[1]['sample1'];
?>
The submit function isn't working for me, even if i remove the $.ajax, the alert(TableData) isn't showing. thus I cant verify if my php code and storing html table data is correct, could you please take a look at my submit function and php code to see where did I go wrong?
Thank You in Advance.
function submit() {
//Store HTML Table Values into Multidimensional Javascript Array Object
var TableData = new Array();
$('#table tr').each(function(row, tr) {
TableData[row] = {
"sample1": $(tr).find('td:eq(0)').text(),
"sample2": $(tr).find('td:eq(1)').text(),
"sample3": $(tr).find('td:eq(2)').text()
}//tableData[row]
});
TableData.shift(); // first row will be empty - so remove
alert(TableData);
var Data;
Data = JSON.stringify(TableData);
alert(Data);
$.ajax({
type: "POST",
url: "getInfo.php",
data: "pTableData=" + Data,
success: function(msg) {
return value stored in msg variable "success";
}//success
});
};//submit();`enter code here`
try to change how you send post data to this:
data: { pTableData: TableData},

cannot get data-value from paragraph

I have a very frustrating issue. I have two kind of paragraphs in a div , a built in one like you see below
<div >
<table id="box">
<thead>
<tr>
<td><p class="linkin" data-value="test22">test</p></td>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
And fetched ones like this:
$('.menu').on('click', function(){
$('#box').toggle('slide').show();
$.ajax({
url:'fetchsubmenu.php',
data : {nume : $(this).attr('data-value')},
dataType : 'json',
success:function(data){
console.log(data);// process your response
showObjects(data);
}
});
});
function showObjects(obiecte){
$('#box tbody').html('');
for(var i=0; i<obiecte.length; i++){ //Functia care arata obiectele
var aparat = obiecte[i];
$('#box tbody').append(getRow(aparat));
}
}
function getRow(aparat){
var row = '<tr>'+
'<td>' + '<p class="linkin" data-value='+aparat.id+' >'+aparat.nume+'</p>' + '</td>'+ //functia care le aranjeaza
'</tr>';
return row;
}
The problem is that when I want to get the data-value attribute like this:
$('.linkin').on('click',function(){
$.ajax({
url:'test.php',
dataType:'JSON',
data : {id : $(this).attr('data-value')},
success:function(){
console.log();
alert('success');
}
});
});
the built in paragraph works just fine, I get the data-value attribute , but the fetched paragraphs don't work, I am not able to get any attributes.
Sorry for my english.
This is happening because the event listening is only being bound to objects present when the code runs. That would explain why objects that are fetched after the code runs do not work as anticipated. This can be fixed by simply binding to the document.
$(document).on('click', '.linkin', function() {
$.ajax({
url:'test.php',
dataType:'JSON',
data : {id : $(this).attr('data-value')},
success:function() {
alert('success');
}
});
});

$(this).find(".text") and (".loading") inside a AJAX success function not working

I've been searching Stack Overflow for well over an hour now and can't seem to find a solution to this problem. To reduce loading time on this PHP page I'm trying to place content from other pages into a div.
The page queries correctly and I can see the output in Safari (Inspector) and FireBug.
The content inside the success: function(output_string) will not load. I have tried every possible combination. I have also attempted var self = this; with no luck although I think this may be due to jQuery(document).ready(function() { But I am using 2 versions of jQuery.
Here's my attached code:
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery(".text").hide();
//toggle the component with class msg_body
jQuery(".ttop2").click(function() {
jQuery(this).next(".text").slideToggle(500);
var expanded = "./expand.png";
var collapsed = "./collapse.png";
var src = $(this).find(".toggle").attr('src');
<? if($show == 'off') { ?>
if (src == expanded){
$(this).find(".toggle").attr('src',collapsed);
var office = $(this).attr("id");
var month = "<? echo $month; ?>";
var year = "<? echo $year; ?>";
$(this).closest(".loading").html("Loading...");
alert(office);
$.ajax({
url: 'LTData.php',
type:'POST',
data: 'office=' + office + '&month=' + month + '&year=' + year,
dataType: 'json',
success: function(output_string){
$(this).find(".loading").html("");
$(this).find(".text").html(output_string);
} // End of success function of ajax form
}); // End of ajax call
} else {
$(this).find(".toggle").attr('src',expanded);
var office = $(this).attr("id");
alert(office);
}
});
});
<? } else {
//..... Etc.
?>
P.S: I started Javascript programming today so I would love some critical responses. Thanks!
Edit: Script is in the head.
Edit 2: Attached HTML/PHP.
$sqlb="SELECT * FROM league ORDER by total DESC";
$resultb=mysql_query($sqlb);
$num=mysql_num_rows($resultb);
while($rowsb=mysql_fetch_array($resultb)){
if($rowsb[total] == '0') {
continue;
}
if($col=='ebdff2'){
$col='efefef';
}else{
$col='ebdff2';
}
?>
<table class="ttop2" id="<? echo $rowsb["office"]; ?>" bgcolor="#<? echo $col;?>" width="100%">
<tr>
<td width="50%" align="left"><b style="text-transform: capitalize; color:rgb(98, 188, 70);"><? echo $rowsb[office];?></b></td>
<td width="20%" align="left"><b style="text-transform: capitalize; color:rgb(98, 188, 70);"><? echo $rowsb[leads];?></b></td>
<!-- <td width="200px" align="left">Total leads</td>
<td width="270px" align="left">Leads converted</td>-->
<td width="20%" align="left"><b style="text-transform: capitalize; color:rgb(98, 188, 70);"><? echo $rowsb[total];?></b></td>
<td width="10%" align="left"><img style="float: right;" class="toggle" alt="" src="./expand.png" /></td>
</tr>
</table>
<div class="text"><div class="loading"></div></div>
<? } ?>
<?
}///end of show what...
?>
In the ajax success function, you lose you this reference. You need to cache it before the function :
var $this = $(this); //Here
$.ajax({
url: 'LTData.php',
type:'POST',
data: 'office=' + office + '&month=' + month + '&year=' + year,
dataType: 'json',
success: function(output_string){
$this.find(".loading").html("");
$this.find(".text").html(output_string);
} // End of success function of ajax form
}); // End of ajax call
Or, as Kevin B said, pass it in the context option :
$.ajax({
url: 'LTData.php',
type:'POST',
data: 'office=' + office + '&month=' + month + '&year=' + year,
dataType: 'json',
context : this,
success: function(output_string){
$(this).find(".loading").html("");
$(this).find(".text").html(output_string);
} // End of success function of ajax form
}); // End of ajax call
after
jQuery(".ttop2").click(function() {
do
var parent = $(this);
and replace all your calls to $(this) with parent. You are having a lot of enclosure issues with the use of $(this) so fix this first and let us know if that helped.
The below code needs to be written under success event, where response is the returned data in html.
//use filter to find an element is at the root level of response.
if ($(response).filter('#Display').length > 0) { }
//use find to search an element is not at the root level of response.
if ($(response).find('#AddNew').length > 0) { }

Categories

Resources