Jquery sortable not working after ajax refresh - javascript

I have a table filled with data from my database. This table is sortable and saves the order with ajax. Now I made the option to delete the selected row. When the row is deleted the table is refreshed with ajax.
My only problem now is when I delete a row and my table is refreshed, the table can't be sorted any more (until I refresh).
Is there a way to fix this?
This is my jquery/ajax code:
$(document).ready(function () {
$('#sortable').sortable({
axis: 'y',
update: function (event, ui) {
var data = $(this).sortable('serialize');
$.ajax({
data: data,
type: 'POST',
url: 'includes/saveorder.php'
});
}
});
});
function deleteFromDatabase(id) {
if (confirm("Weet u zeker dat u deze pagina wilt verwijderen?")) {
$.ajax({
url: "includes/paginas_del.php",
type: "POST",
data:'id='+id,
success: function(data){
document.getElementById("alert").style.display = "block";
$("#myTable").load("paginas.php #myTable");
}
});
} else {
document.getElementById("alert").style.display = "none";
}
}
This is my table:
<table class="table table-hover table-cust" id="myTable">
<thead>
<tr>
<th scope="col" width="80%">Pagina</th>
<th width="10%"></th>
<th width="10%"></th>
</tr>
</thead>
<tbody id="sortable">
<?php $result = mysql_query("SELECT * FROM pagina WHERE active = '1' ORDER BY sort");
while ($data = mysql_fetch_assoc($result)) { ?>
<tr id="item-<?php echo $data['id'] ?>">
<td><?php echo $data['titel'] ?></td>
<td><i class="fas fa-edit"></i></td>
<td><i class="fas fa-trash-alt"></i></td>
</tr>
<?php } ?>
</tbody>
</table>

This issue is caused by the fact that what the call to jquery's load method does is "load data from the server and place the returned HTML into the matched element".
This means that the whole table is replaced with a new table. So the old <tbody id="sortable"> element is replaced with a new one which doesn't have the sortable behavior you attached to the old one.
Try rerunning the sortable method after the table is rebuilt:
function deleteFromDatabase(id) {
if (confirm("Weet u zeker dat u deze pagina wilt verwijderen?")) {
$.ajax({
url: "includes/paginas_del.php",
type: "POST",
data:'id='+id,
success: function(data){
document.getElementById("alert").style.display = "block";
$("#myTable").load("paginas.php #myTable");
$('#sortable').sortable({
axis: 'y',
update: function (event, ui) {
var data = $(this).sortable('serialize');
$.ajax({
data: data,
type: 'POST',
url: 'includes/saveorder.php'
});
}
});
}
});
} else {
document.getElementById("alert").style.display = "none";
}
}

Related

request ajax doesn't call the good function

I have a trouble with my request AJAX. When I click on it, in the process, it calls an other php function which I don't need for this request (function switch, change statut).
http://www.noelshack.com/2022-31-1-1659342824-undefined-index.png
This line with error corresponds to another function.
My HTML :
<table id="list_client_pris" border=1>
<tr>
<td>#</td>
<td>Nom</td>
</tr>
<?php
$clients = $db->query('SELECT * FROM client');
foreach ($clients as $client) :
?>
<tr id="tr1">
<td><?php echo $client["id_client"]; ?></td>
<td><?php echo $client["nom_client"]; ?></td>
<td><button data-id="<?php echo $client["id_client"]; ?>" type="button" class="info">Info client</button></td>
<td><button type="button" class="hide_client" data-id="<?php echo $client["id_client"]; ?>">Masquer client</button></td>
<td><button data-id="<?php echo $client["id_client"]; ?>" type="button" class="switch">Change statut</button></td>
</tr>
<?php endforeach; ?>
</table>
3 buttons call each their ajax's request.
The conflict is between the first button (class info) and the last, (class switch)
Why ?
The buttton class' info call a function which correspond to the error showed, but which is not called with the last button.
My JS , request for the first button, info:
$(".info").click(function () {
var datas = {
cmd :' id_client',
id_client: $(this).attr('data-id'),
};
$.ajax({
type: "POST",
url: "function.php",
data: datas,
cache: false,
}).done(function (result) {
$('#nom').html(result.nom_client),
$('#prenom').html(result.prenom_client),
$('#date').html(result.client_date_naissance),
$('#adresse').html(result.client_adresse),
$('#mail').html(result.client_mail),
$('#tph').html(result.client_tph),
$('#age').html(result.age)
$("#info_client").css("display", "block");
date_client = (result.client_date_naissance);
return date_client;
});
});
PHP corresponding function :
function read()
{
global $db;
$id_client = $_POST['id_client']; **(error showed)**
$query = $db->prepare("SELECT *,FROM client WHERE id_client = :id_client");
$query->bindValue(':id_client', $id_client, PDO::PARAM_INT);
$query->execute();
$result = $query->fetch(PDO::FETCH_ASSOC);
return ($result);
}
My other ajax's request for button switch :
$(".switch").click(function () {
var datas = {
cmd :' id_client_statut',
id_client: $(this).attr('data-id_statut'),
};
console.log(id_client);
$.ajax({
url: 'function.php',
type: 'POST',
data: datas,
done: function (click_result) {
console.log(click_result);
if (click_result.statut=2){
//transfer to libre
$('#tr2').append($('#tr1').html());
$('#tr1').html('');
}
}
}
);
});
Corresponding php function :
function change_statut(){
global $db;
$id_client_statut = $_POST['id_client'];
$query=$db->prepare(" UPDATE alarme INNER JOIN client_alarme ON client_alarme.id_alarme = alarme.id_alarme
INNER JOIN client on client.id_client=client_alarme.id_client
SET id_statut = 2
WHERE client.id_client= :id_client");
$query->bindValue(':id_client', $id_client_statut, PDO::PARAM_INT);
$query->execute();
$click_result = $query->fetch(PDO::FETCH_ASSOC);
return ($click_result);
}
My php function to distinguish :
if (isset($_POST['cmd'])){
if ($_POST['cmd'] == 'id_client_statut') {
change_statut();
}
else if ($_POST['cmd'] == 'id_client') {
read();
}
}
I don't really see why the first button would call the wrong function, but there is a problem with the way you setup the button events: via the onclick you are just binding the event handlers.
In function d_info() you currently just tell what should happen when the button .info is clicked. Idem for function change_statut().
So currently you have to click the buttons twice. First to bind the event and again to trigger the event (the second time it will also rebind the event).
You should get rid of the onclick attributes and bind the button events via the document ready event.
$( document ).ready(function() {
$(".switch").click(function () {
//...
});
$(".info").click(function () {
//...
});
});
In your Request you write :
$(".info").click(function () {
var datas = {
id_client: $(this).attr('data-id'),
};
$.ajax({
type: "GET",
url: "function.php",
data: {cmd :' id_client', datas},
cache: false,
}).done(function (result) {
$('#nom').html(result.nom_client),
$('#prenom').html(result.prenom_client),
$('#date').html(result.client_date_naissance),
$('#adresse').html(result.client_adresse),
$('#mail').html(result.client_mail),
$('#tph').html(result.client_tph),
$('#age').html(result.age)
$("#info_client").css("display", "block");
date_client = (result.client_date_naissance);
return date_client;
});
But the line data: {cmd :' id_client', datas}, gives you a new object witch is :
data: {
cmd :' id_client',
datas: {
id_client: $(this).attr('data-id'),
}
},
Now you can easily understand why your php gives you an error while reading $id_client = $_GET['id_client']; **(error showed)** as the real path to your value is $id_client = $_GET['datas']['id_client'];
But why using this kind of syntax while you have create datas in order to prepare ajax data object ?
The simpliest way to correct the error is to replace all object argument in the datas :
$(".info").click(function () {
var datas = {
cmd :' id_client',
id_client: $(this).attr('data-id'),
};
$.ajax({
type: "GET",
url: "function.php",
data: datas,
cache: false,
}).done(function (result) {
$('#nom').html(result.nom_client),
$('#prenom').html(result.prenom_client),
$('#date').html(result.client_date_naissance),
$('#adresse').html(result.client_adresse),
$('#mail').html(result.client_mail),
$('#tph').html(result.client_tph),
$('#age').html(result.age)
$("#info_client").css("display", "block");
date_client = (result.client_date_naissance);
return date_client;
});
Hope it's helpfull ;)
Happy coding

Displaying data in table(view) passed from Controller - Codeigniter

I want to display data in table on inserting data as well as when the page is loaded. Storing data successfully works with the code but the issue is;
When I use POST, the form data is completely visible in the URL.
How do i display all data passed in json format in html table.
HTML:
<table class="table table-striped table-bordered" id="myTable">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Match</th>
<th scope="col">Match Date</th>
<th scope="col">Winner</th>
<th scope="col">Loser</th>
<th scope="col">Man of the Match</th>
<th scope="col">Bowler of Match</th>
<th scope="col">Best Fielder</th>
</tr>
</thead>
</table>
JAVASCRIPT:
<script>
$(function() {
$("#submit").on("click", function(e) {
var team_one = $('#team_one').val();
var team_two = $('#team_two').val();
var match_summary = $('#match_summary').val();
var match_date = $('#match_date').val();
var winner = $('#winner').val();
var loser = $('#loser').val();
var man_of_the_match = $('#man_of_the_match').val();
var bowler_of_the_match = $('#bowler_of_the_match').val();
var best_fielder = $('#best_fielder').val();
$.ajax(
{
type: "POST", //HTTP POST Method
url: '<?php echo base_url(); ?>/MatchController/storeMatch',
data: { //Passing data
'team_one': team_one,
'team_two': team_two,
'match_summary' : match_summary,
'match_date' : match_date,
'winner' : winner,
'loser' : loser,
'man_of_the_match' : man_of_the_match,
'bowler_of_the_match' : bowler_of_the_match,
'best_fielder' : best_fielder
},
success: function (response) {
console.log("Response: " + response);
alert("Data stored successfully");
},
});
});
});
//FETCH ALL MATCH DATA USING PASSED API IN CONTROLLER
$(document).ready(function (){
getData();
function getData(){
$.ajax({
url : "<?php echo base_url(); ?>/MatchController/fetchMatchData",
method : 'get',
dataType: "json",
success: function(data){
}
});
}
});
CONTROLLER:
public function storeMatch()
{
$team_one = $_POST['team_one'];
$team_two = $_POST['team_two'];
$match_date = $_POST['match_date'];
$match_summary = $_POST['match_summary'];
$winner = $_POST['winner'];
$loser = $_POST['loser'];
$man_of_the_match = $_POST['man_of_the_match'];
$bowler_of_the_match = $_POST['bowler_of_the_match'];
$best_fielder = $_POST['best_fielder'];
$data = array(
'team_one' => $team_one,
'team_two' => $team_two,
'match_date' => $match_date,
'match_summary' => $match_summary,
'winner' => $winner,
'loser' => $loser,
'man_of_the_match' => $man_of_the_match,
'bowler_of_the_match' => $bowler_of_the_match,
'best_fielder' => $best_fielder
);
$this->MatchModel->saveMatchData($data);
}
public function fetchMatchData()
{
$match_data = $this->MatchModel->fetchMatchList();
return $match_data;
}
Try to pass the result to <tbody> use JQuery
success: function(data){
//delete old tbody block
$('#myTable tbody').remove()
//add tbody block
$('#myTable').append('<tbody><tr><td>'+data.someValue+'</td></tr></tbody>')
}
And when you want add new data just call your getData().
success: function (response) {
getData()
console.log("Response: " + response);
alert("Data stored successfully");
},
Also look at e.preventDefault for your ajax call. If you use ajax needlessly reload page

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.

Two different table with 2 different AJAX JSON response data

I'm new to javascript.
I need to fetch JSON response from 2 different AJAX request and create a 2 different table.
I have achieved it for 1 JSON response and 1 Table.
HTML :
<div style="width:700px;padding:20px;S">
<table id="host_table" class="table">
<tr>
<th>Server Name</th>
<th>Availability %</th>
</tr>
</table>
</div>
JavaScript :
$(function() {
// kick off with fetchdata
fetchData();
// fetchServiceData();
});
function make_base_auth(user, password) {
var tok = user + ':' + password;
var hash = btoa(tok);
return 'Basic ' + hash;
}
function fetchData() {
var time = new Date();
var end = Math.floor((new Date).getTime()/1000);
//var end = ~~(Date.now() /1000) ;
var start = Math.floor(time.setDate(time.getDate() - 1)/1000);
Availreport = "http://xx.xx.xx.xx/nagios/cgi-bin/archivejson.cgi?query=availability&availabilityobjecttype=hostgroups&hostgroup=ALM&assumedinitialhoststate=up&assumedinitialservicestate=ok&starttime=" + start + "&endtime=" + end;
$.ajax({
type: "GET",
url: Availreport,
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization',
make_base_auth("nagiosadmin", "nagiosadmin"));
},
dataType: 'json', //data format
//async: false,
//success: onOutboundReceived //on receive of reply
timeout: 0,
success: availshow
});
function availshow(series) {
// 1. remove all existing rows
$("tr:has(td)").remove();
$.each(series.data.hostgroup.hosts, function (index, test) {
$('<tr>').append(
$('<td>').text(test.name),
$('<td>').text(parseInt(((test.time_up - test.time_down)/test.time_up)*100)),
).appendTo('#host_table');
});
$('#host_table tr').each(function() {
var $td = $(this).find('td:eq(1)');
var value = $td.text();
if (parseInt(value) < 100) {
$td.css('background-color', 'red');
}
});
}
This works perfect for 1 table creation.
But I'm unable to proceed for 2 table creation for 2 JSON response.
I can able to create 2 tables in HTML.
But unable to feed the JSON response to specific table.
HTML for 2 table Creation :
<table id="host_table" class="inlinetable" style="display: inline-block;">
<tr>
<th>Server Name</th>
<th>Availability %</th>
</tr>
</table>
<table id="service_table" class="inlinetable" style="display: inline-block;">
<tr>
<th>Service Name</th>
<th>Availability %</th>
</tr>
</table>
How to achieve my task?
make tables side by side like this
its another question but
use for first table
style="display: inline-block;"
and for second table
style="float: left;">
<table id="host_table" class="inlinetable" style="display: inline-block;">
<thead>
<tr>
<th>Server Name</th>
<th>Availability %</th>
</tr>
</thead>
<tbody></tbody>
</table>
<table id="service_table" class="inlinetable" style="float: left;">
<thead>
<tr>
<th>Service Name</th>
<th>Availability %</th>
</tr>
</thead>
<tbody></tbody>
</table>
JS
$(function() {
// kick off with fetchdata
// service_table();
service_table();
// host table();
fetchData2();
});
function service_table() {
$.ajax({
type: "GET",
url: Availreport,
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization',
make_base_auth("nagiosadmin", "nagiosadmin"));
},
dataType: 'json',
timeout: 0,
success:function(series) {
$('#service_table tbody').empty();
// your row loop code
}
});
function service_table() {
$.ajax({
type: "GET",
url: Availreport,
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization',
make_base_auth("nagiosadmin", "nagiosadmin"));
},
dataType: 'json',
timeout: 0,
success:function(series) {
$('#host_table tbody').empty();
// your row loop code
}
});
}
its just how it can work for your understanding, more dynamic solution can be made

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.

Categories

Resources