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

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?

Related

How do I apply the data I received as AJAX from my label to my blade template?

I used Ajax to get JSON's data from the controller. However, I don't know how to forward the data I received to the foreach statement of the blade template in the table tag.
Ajax
$.ajax({
url: '{{route('translation.recodes')}}',
type: 'post',
data: {_token: "{{ csrf_token() }}"},
success: function (data) {
console.log(data); // get controller data -> $translationRecords
}, error: function () {
alert("error!!!!");
}
});
HTML
<table class="table table-hover">
#if($translationRecords)
#foreach($translationRecords as $translationRecord)
<tr>
<td id="recodeValue{{ $translationRecord->id }}" style="display:none">{{ $translationRecord->id }}</td>
<td>{{ $translationRecord->korean }}</td>
<td>{{ $translationRecord->japanese }}</td>
<td><button id="recodeRemoveBtn{{ $translationRecord->id }}" type="button" class="btn btn-danger float-right">삭제</button></td>
</tr>
#endforeach
#endif
</table>
My prediction is that I'm thinking about using the jQuery to create dynamically in the table tags, but I don't know how to return the data from the controller either.
Simply give an id to the table body and use template literals
<table class="table table-hover">
<thead>
</thead>
<tbody id="transRecords">
</tbody>
</table>
and then in your ajax function use Template Literals ``
$.ajax({
url: '{{route('translation.recodes')}}',
type: 'post',
data: {_token: "{{ csrf_token() }}"},
success: function (data) {
data.forEach((rec)=>{
document.querySelector('#transRecords').innerHTML +=
`
<tr>
<td id="recodeValue-${rec.id}" style="display:none">${rec.id}</td>
<td>${rec.korean}</td>
<td>${rec.japanese}</td>
<td><button id="recodeRemoveBtn-${rec.id}" type="button" class="btn btn-danger float-right">삭제</button></td>
</tr>
`
})
}, error: function () {
alert("error!!!!");
}
});
You can achieve by doing something this.
data[i] depends on how you are sending your data from the controller.
$.ajax({
url: '{{route('translation.recodes')}}',
type: 'post',
data: {_token: "{{ csrf_token() }}"},
success: function (data) {
console.log(data); // get controller data -> $translationRecords
$('#datatable tr').not(':first').not(':last').remove();
var html = '';
for(var i = 0; i < data.length; i++){
html += '<tr>'+
'<td '+id="recodeValue'+data[i].id+'" style="display:none"+'>' + data[i].id + '</td>' +
'<td>' + data[i].korean + '</td>' +
'<td>' + data[i].japanese + '</td>' +
'<td>' + data[i].var4 + '</td>' +
'</tr>';
}
$('#datatable tr').first().after(html);
}, error: function () {
alert("error!!!!");
}
});
<table id="datatable">
</table>
here is the answer for you link
You can't.
What you could do:
Either use React, Vue.js or Angular
Create the HTML elements after received the response and insert them by JS
Return the content already rendered (not recommended) and simply insert it in the view
Simply reload the page with the query parameter id and render the page accordingly

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

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.

Page getting stuck after Ajax Call

So this is the form I have
<form action="javascript:void(0);" class="form-inline" id="receive-order-form"> By Receiving you agree that you have received the item <b> {{ x.item_name }} </b> at the store. </br> Order Id <b> {{ x.order_id }} </b></br><input class="btn btn-primary center-block" onclick="execute({{x.linq_order_num}})" type="submit" id= 'receive-btn' value="Receive" ></form>
On submit the remote call gets executed and I get the success pop up but somehow the screen gets stuck like this. Page becomes unresponsive.
Execute Function Definition:
function execute(linq_order_num) {
var result = "";
var tableRow=document.getElementById("order_num1_"+String(linq_order_num));
var modalId = "exampleModal1_" + "{{ linq_order_num }}";
jQuery.ajax ({
url: "/receive-order/",
type: "POST",
data: JSON.stringify({"linq_order_num":linq_order_num}),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function(data){
result = data;
$("#modalId").modal('hide');
$('#alert_placeholder').html('<div class="alert
alert-success"><a class="close" data-
dismiss="alert">×</a>
<span>Successfully received the product</span>
</div>');
var htmlElement = document.getElementById("deliver-
order_"+ String(linq_order_num));
var cln = htmlElement.cloneNode(true);
cln.style.display = null;
tableRow.cells[7].innerHTML = cln.outerHTML;
}
});
return result;
}
how can I solve this ?
Assuming you were wanting to hide the modal id referenced in:
var modalId = "exampleModal1_" + "{{ linq_order_num }}";
Change:
$("#modalId").modal('hide');
Into:
$("#" + modalId).modal('hide');
In the current version, you are trying to hide the element with id="modalId" in the HTML.

How to get the data from ajax in controller codeigniter

I have an editable table in my view.. At first, there's no data in the table but the user can add data in the table since it is editable. And there's no exact number of rows in the table since I have also a button that can add new row. I want to get the data that the user have added and save it in the database.
I have this code:
VIEW:
<table class="table " id="memberTB">
<thead><tr><th >First Name</th><th >Middle Name</th><th>Last Name</th></tr></thead>
<tbody>
<tr id="first"><td><span class="edit"></span></td>
<td><span class="edit"></span></td>
<td><span class="edit"></span></td></tr>
</tbody>
<button type="button" class="btn btn-link" id="addrow"><span class="fa fa-plus"> Add new row</span></button>
</table>
<br><button type="button" class="btn" id="savebtn">Save</button> Reset
JS:
$.fn.editable.defaults.mode = 'inline';
$.fn.editable.defaults.showbuttons = false;
$.fn.editable.defaults.url = '/post';
$.fn.editable.defaults.type = 'text';
// make all items having class 'edit' editable
$('.edit').editable();
// this is to automatically make the next item in the table editable
$('.edit').on('save', function(e, params){
var that = this;
// persist the old value in the element to be restored when clicking reset
var oldItemValue = $(that)[0].innerHTML;
if (!$(that).attr('oldValue')) {
console.log('persisting original value: ' + oldItemValue)
$(that).attr('oldValue', oldItemValue);
}
setTimeout(function() {
// first search the row
var item = $(that).closest('td').next().find('.edit');
console.log(item);
if (item.length == 0) {
// check the next row
item = $(that).closest('tr').next().find('.edit');
}
item.editable('show');
}, 200);
});
$('#resetbtn').click(function() {
$('.edit').each(function() {
var o = $(this);
o.editable('setValue', o.attr('oldValue')) //clear values
.editable('option', 'pk', o.attr('pk')) //clear pk
.removeClass('editable-unsaved')
.removeAttr('oldValue');
});
});
$('#savebtn').click(function() {
var person = [];
var x=1;
$('tbody tr',$('#memberTB')).each(function(){
for(var i = 0 ; i < cells ; i++)
{
person[x][i]=$(this).find('td').eq(i).text();
}
x++;
});
$.ajax({
url: '<?php echo base_url("index.php/test/Savedata");?>',
type: "post",
data: { values: arraylng },
cache: false,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
}
});
});
$('#addrow').click(function() {
$('#memberTB > tbody:last').append(' <tr><td><span class="edit"></span></td><td><span class="edit"></span></td><td><span class="edit"></span></td></tr>');
$('.edit').editable();
});
Controller: [inside the test.php]
public function saveData(){
$this->load->model('test_model');
$myArray = $_REQUEST['values'];
echo sizeof($myArray);
}
Whenever I click the save button, there's no response at all.. Where did I go wrong? please help me..
ADDED INFO:
I didn't include my SQL insert statement here because I want to test first if there's data in $myArray if I added data in the table.
Better use this ajax
var arraylng = [3,4,7];
$.ajax({
url: '<?php echo base_url("index.php/test/Savedata");?>',
type: "post",
data: {values: JSON.stringify(arraylng)},
cache: false,
success: function (response) {
alert(response);
}
});
arraylng is an array, which doesn't exist in the code. I added it here for debugging.
Suppose you want to send person[] array, you write, data: {values: JSON.stringify(person)}.
Now, the person array may not exist, because of the "i < cells" in for. What is cells?
The word response is just a name, any name, but better avoid 'data'.
In test.php, what is sizeof($myArray)? Just, echo $myArray;
When you click save you must get the $myArray content in an alert.

$(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