ajax html response can't take effect on link with javascript - php

I made a form for showing users informations about some presentations. I used ajax cause it should be loaded into a div container and not reloading each time while changing the year.
This is my JavaScript:
$("#select_coffee_talk_year").button().click(function() {
var form = $('#coffee_talk_year');
var data = form.serialize();
$.ajax({
url: 'include/scripts/select_event.php',
type: 'POST',
data: data,
dataType: 'html',
success: function (select) {
$("#coffee_talk").html(select);
$("#coffee_talk").fadeIn();
}
});
return false;
});
This is my select_event.php:
if ('POST' == $_SERVER['REQUEST_METHOD']) {
/*******************************/
/** Erzaehlcafe auswählen
/*******************************/
if (isset($_POST['coffee_talk_year_submit'])) {
$getID = array();
$getDate = array();
$getTheme = array();
$getContributer = array();
$getBegin = array();
$getPlace = array();
$getEntrance = array();
$getFlyer = array();
$sql = "SELECT
ID,
Date,
Theme,
Contributer,
Begin,
Place,
Entrance,
Flyer
FROM
Coffee_talk
WHERE
YEAR(Date) = '".mysqli_real_escape_string($db, $_POST['year_coffee_talk'])."'
ORDER BY
Date ASC
";
if (!$result = $db->query($sql)) {
return $db->error;
}
while ($row = $result->fetch_assoc()) {
$getID[$i] = $row['ID'];
$getDate[$i] = $row['Date'];
$getTheme[$i] = $row['Theme'];
$getContributer[$i] = $row['Contributer'];
$getBegin[$i] = $row['Begin'];
$getPlace[$i] = $row['Place'];
$getEntrance[$i] = $row['Entrance'];
$getFlyer[$i] = $row['Flyer'];
$i++;
}
$result->close();
/****************************/
/** Output der Tabelle
/****************************/
if ($getID[0] == '') {
echo 'Kein Eintrag vorhanden';
} else {
//Kopf
echo '<table id="table">
<thead>
<tr id="table_head">
<th>Nr.</th>
<th>Datum</th>
<th>Thema</th>
<th>Referent</th>
<th>Begin</th>
<th>Ort</th>
<th>Eintritt</th>
<th>Flyer</th>
<th>Bearbeiten</th>
</tr>
</thead>
<tbody>';
//Mittelteil
$j = 0;
for($i = 0; $i < count($getID); $i++) {
$j = $i + 1;
echo '<tr>
<td class="center">'.$j.'</td>
<td class="center">'.$getDate[$i].'</td>
<td class="center">'.$getTheme[$i].'</td>
<td class="center">'.$getContributer[$i].'</td>
<td class="center">'.$getBegin[$i].'</td>
<td class="center">'.$getPlace[$i].'</td>
<td class="center">'.$getEntrance[$i].'</td>';
if ($getFlyer[$i] == '') {
//Kein Bild vorhanden
echo '<td class="center">Kein Bild vorhanden</td>';
} else echo '<td class="center">'.$getFlyer[$i].'</td>';
echo '<td class="center">
<table id="icons">
<tr>
<td>
<a href="#" data-event-id="'.$getID[$i].'" data-table="Coffee_talk" class="edit_event">
<img src="images/edit.png" />
</a>
</td>
<td>
<a href="#" data-event-id="'.$getID[$i].'" data-table="Coffee_talk" class="delete_event">
<img src="images/delete.png" />
</a>
</td>
</tr>
</table>
</td>
</tr>';
}
//Ende
echo '</tbody>
</table>';
}
}
}
As you can see my outpt is a table. I am using links to make an edit and delete function:
<a href="#" data-event-id="'.$getID[$i].'" data-table="Coffee_talk" class="edit_event">
<img src="images/edit.png" />
</a>
and
<a href="#" data-event-id="'.$getID[$i].'" data-table="Coffee_talk" class="delete_event">
<img src="images/delete.png" />
</a>
This is my html with the placeholder div:
<div>
<p class="bold underline headline">Bereits eingetragen:</p>
<form id="coffee_talk_year" action="include/scripts/select_event.php" method="post" accept-charset="utf-8">
<select name="year_coffee_talk" id="year_coffee_talk">
<option value="none" class="bold italic">Jahr</option>
<?php
for($i=2008; $i<=$year; $i++){
if ($i == $year) {
echo "<option value=\"".$i."\" selected=\"$i\">".$i."</option>\n";
} else echo "<option value=\"".$i."\">".$i."</option>\n";
}
?>
</select>
<button id="select_coffee_talk_year">anzeigen</button>
<input type="hidden" name="coffee_talk_year_submit" value="true" />​​​​​​​​​​​​​​​​​
</form>
<br />
<div id="coffee_talk"></div>
<br />
<button id="add_coffee_talk">hinzufügen</button>
</div>
Now I want to use this JavaScript to do a delete and edit function:
$(".delete_event").click(function() {
alert('hallo');
currentUserID = $(this).data("event-id");
currentTable = $(this).data("table");
$( "#dialog_delete_event" ).dialog( "open" );
});
$( '#dialog_delete_event' ).dialog({
autoOpen: false,
resizable: false,
height: 170,
modal: true,
buttons: {
'Ja': function() {
document.location = "index.php?section=event_delete&id=" + currentUserID +"&table=" + currentTable;
$( this ).dialog( 'close' );
},
'Nein': function() {
$( this ).dialog( 'close' );
}
}
});
My problem is that the click_function (defined in the links) is not working. I Found out that the ajax form response is not written into the html code. Bet that this is the problem. What can I do to give the links a working click function?

im not sure due to your code's size but this:
$(".delete_event").click(function() {
should be
$(".delete_event").live("click",function() {
because you dynamically create html; the "live" works with that.

Like #Albit, not really sure what your question is, assuming the ajax is working correctly, and the results are visible on the screen, instead of using:
$(".delete_event").click(function() {
try
$(".delete_event").live("click", function() {
This means that elements that satisfy the selector after page load will still trigger an event.

i don't know if i undestood your problem correctly but just use the onclick event in the html tag of the anchor and you will be ok . if this is not the correct answer plese ignore me

Related

Button Submit Inside Serverside Table Codeigniter

I have datatables contain input box and button for each row data, for sure form was added outside table tag, but i have issue while clicking on button submit inside that table, the button did not work well and no appear anything error logs
My Controller.php for displaying row:
public function tagihankost()
{
$list = $this->tagihan->get_datatables();
$data = array();
foreach ($list as $tagih) {
$row = array();
$format = number_format($tagih->harga, '0', '', '.');
$row[] = "<input type='text' value='$tagih->bulan' id='bulan' class='rowtagihan' form='payment-form' readonly>";
$row[] = "<input type='number' value='$format' id='harga' class='rowtagihan' form='payment-form' readonly>";
if ($tagih->status == 200) {
$row[] = "<span class='badge bg-success' style='color:white'>Lunas</span>";
} elseif ($tagih->status == 201) {
$row[] = "<span class='badge bg-warning' style='color:black'>Pending</span>";
} else {
$row[] = "<span class='badge bg-danger' style='color:white'>Belum Bayar</span>";
};
$row[] = "<button id='pay-button'>Pay!</button>";
$data[] = $row;
}
$output = array(
"draw" => $_POST['draw'],
"recordsTotal" => $this->tagihan->count_all(),
"recordsFiltered" => $this->tagihan->count_filtered(),
"data" => $data,
);
echo json_encode($output);
}
My View.php :
<div class="card bodycontent">
<div class="card-body">
<div class="tab-pane table-responsive">
<table id="tablekost" class="table table-striped table-bordered" width="100%" cellspacing="0">
<thead>
<tr>
<td>Bulan</td>
<td>Tagihan</td>
<td>Status</td>
<td>#</td>
</tr>
</thead>
<form id="payment-form" method="post" action="<?= site_url() ?>/snap/finish">
<input type="hidden" name="result_type" id="result-type" value="">
<input type="hidden" name="result_data" id="result-data" value="">
</form>
<tbody>
</tbody>
</table>
</div>
</div>
</div>
And the last thing is my JS:
<script type="text/javascript">
$('#pay-button').click(function(event) {
event.preventDefault();
$(this).attr("disabled", "disabled");
$.ajax({
url: '<?= site_url() ?>/snap/token',
cache: false,
success: function(data) {
//location = data;
console.log('token = ' + data);
var resultType = document.getElementById('result-type');
var resultData = document.getElementById('result-data');
function changeResult(type, data) {
$("#result-type").val(type);
$("#result-data").val(JSON.stringify(data));
//resultType.innerHTML = type;
//resultData.innerHTML = JSON.stringify(data);
}
snap.pay(data, {
onSuccess: function(result) {
changeResult('success', result);
console.log(result.status_message);
console.log(result);
$("#payment-form").submit();
},
onPending: function(result) {
changeResult('pending', result);
console.log(result.status_message);
$("#payment-form").submit();
},
onError: function(result) {
changeResult('error', result);
console.log(result.status_message);
$("#payment-form").submit();
}
});
}
});
});
So what i have missed?

delete multiple row in php table data using cheque box

I have this script where the delete function is not working. The row gets removed from the table as the same was called for.. but the same re-appears as the same is not been removed from the actual database..
My table's :
This is given for the delete button:
<th >Follow Up Date</th>
<th >Name SM</th>
<th >Entered Date</th>
<th >Edit</ht>
<th ><button type="button" name="delete_all" id="delete_all" class="btn btn-danger btn-xs">Delete</button></th>
The second where the there is check box:
<td><?php echo $row["NameSM"]; ?></td>
<td><?php echo $row["EnteredDate"]; ?></td>
<td><input type="button" name="edit" value="Edit" id="<?php echo $row["id"]; ?>" class="btn btn-info btn-xs edit_data" /></td>
<td><input type="checkbox" class="delete_checkbox" value="'.$row["id"].'" /></td>
The Delete Script :
<style>
.removeRow
{
background-color: #FF0000;
color:#FFFFFF;
}
</style>
<script>
$(document).ready(function(){
$('.delete_checkbox').click(function(){
if($(this).is(':checked'))
{
$(this).closest('tr').addClass('removeRow');
}
else
{
$(this).closest('tr').removeClass('removeRow');
}
});
$('#delete_all').click(function(){
var checkbox = $('.delete_checkbox:checked');
if(checkbox.length > 0)
{
var checkbox_value = [];
$(checkbox).each(function(){
checkbox_value.push($(this).val());
});
$.ajax({
url:"delete.php",
method:"POST",
data:{checkbox_value:checkbox_value},
success:function()
{
$('.removeRow').fadeOut(1500);
}
});
}
else
{
alert("Select atleast one records");
}
});
});
</script>
The delete.php page :
<?php
//database_connection.php = $connect = new PDO("mysql:host=localhost;dbname=u771775069_data", "root", "");
include('database_connection.php');
if(isset($_POST["checkbox_value"]))
{
for($count = 0; $count < count($_POST["checkbox_value"]); $count++)
{
$query = "DELETE FROM data WHERE id = '".$_POST['checkbox_value'][$count]."'";
$statement = $connect->prepare($query);
$statement->execute();
}
}
?>

how can i update multiple use php/ajax in datatable checkbox?

I have a datatable filled in by SALARIES with checkbox and button update_all and dropdownlist contains CHANTIER_IDs, I want to do multiple update of CHANTIER_IDs using php / ajax .CHANTIER_IDs of SALARIES cheked in datatable will be modified by value select in dropdownlist.
I want when I click on button update all the values of chantire_ids of cheked SALARIES will be modified by the value selected in dropdownlist
affectation.php
<div class="container" id="app">
<h3>affecter salarie a chantier</h3>
<div class="form-group col-md-3 ">
<select class="form-control" id="chantier">
<?php
include "../conn/connexion.php";
$query = "SELECT id,chantier FROM chantier";
$result = mysqli_query($con,$query);
$n = mysqli_num_rows($result);
for ($i=0; $i <$n ; $i++) {
$row = mysqli_fetch_array($result);
?>
<option value="<?php echo $row[0]; ?>" ><?php echo $row[1];
} ?></option>
</select>
</div>
<button class="btn btn-success update-all" data-url="">Update All</button>
<button style="margin: 5px;" class="btn btn-danger btn-xs delete-all" data-url="">Delete All</button>
<table class="table table-bordered">
<tr>
<th><input type="checkbox" id="check_all"></th>
<th>S.No.</th>
<th>nom & prenom</th>
<th>cin</th>
<th>matricule</th>
<th>chantier_ids</th>
</tr>
<?php
$query1 = "SELECT id,nom,prenom,cin,matricule,chantier_id
FROM salaries";
$result1 = mysqli_query($con,$query1);
$n1 = mysqli_num_rows($result1);
for ($i=0; $i <$n1 ; $i++) {
$row1 = mysqli_fetch_array($result1);
?>
<tr id="tr_<?php $row[0] ?>">
<td><input type="checkbox" class="checkbox" data-id="<?php $row[0] ?>"></td>
<td><?php echo $row1[0]; ?></td>
<td><?php echo $row1[1]; ?> <?php echo $row1[2]; ?></td>
<td><?php echo $row1[3]; ?></td>
<td><?php echo $row1[4]; ?></td>
<td><?php echo $row1[5]; ?></td>
</tr>
<?php
}
?>
</table>
</div>
javascript
<script type="text/javascript">
$(document).ready(function () {
$('#check_all').on('click', function(e) {
if($(this).is(':checked',true)) {
$(".checkbox").prop('checked', true);
} else {
$(".checkbox").prop('checked',false);
}
});
$('.checkbox').on('click',function(){
if($('.checkbox:checked').length == $('.checkbox').length){
$('#check_all').prop('checked',true);
}else{
$('#check_all').prop('checked',false);
}
});
$('.update-all').on('click', function(e) {
if(confirm("Are you sure you want to delete this?")){
var id = [];
}
$(':checkbox:checked').each(function(i){
id[i] = $(this).val();
});
if(id.length === 0) //tell you if the array is empty
{
alert("Please Select atleast one checkbox");
}else{
$.ajax({
url:'delete.php',
method:'POST',
data:{id:id},
success:function(){
for(var i=0; i<id.length; i++){
$(this).parents("tr")
.children("td:last-child")
.text($('#app')
.children("option:selected")
.text());
}
}
});
}
});
});
</script>
updateall.php
<?php
include "conn/connexion";
if(isset($_POST["id"])) {
foreach($_POST["id"] as $id) {
$query = "UPDATE salaries
SET chantier_id = ". $id ."
WHERE id = '".$id."'";
mysqli_query($con, $query);
}
}
?>

Load more button works just once

I have a table named tbl_video that consist of two fields (video_id, video_title What I want to add a load more button using Ajax JQuery like social networking sites .I am able to get the first two records but when I try second time nothing happens. I dont get any errors .What am i doing wrong .
this my index.php file I create table structure here and then fetch two records.And get the second record's id value and send it to the more.php file
<body>
<table class="table table-bordered" id="load_data_table">
<thead>
<tr>
<td width="15%">Video Id</td>
<td>Video Title</td>
</tr>
</thead>
<?php
while ($row = mysqli_fetch_array($result)) {
$video_id = $row['video_id']; ?>
<tr>
<td><?php echo $row['video_id']; ?></td>
<td><?php echo $row['video_title']; ?></td>
</tr>
<?php
}
?>
<tr id="remove_row"><td><button type="button" id="more" class="btn btn-success form-control"
data-id="<?php echo $video_id; ?>">More</button></td></tr>
</table>
</div>
</div>
</body>
</html>
<script>
$(document).ready(function(){
$('#more').click(function(){
var id=$(this).data("id");
$.ajax({
url:"more.php",
data:{id:id},
method:"post",
success:function(data){
if(data!=''){
$('#load_data_table').append(data);
$('#remove_row').remove();
}
else{
$('#more').html("No Data");
}
}
and this the more.php file.I think it is self explanatory
$id = $_POST['id'];
$output = '';
$db = mysqli_connect('localhost', 'root', '', 'testing');
$data = mysqli_query($db, "select * from tbl_video where video_id >{$id} limit 2");
if (mysqli_num_rows($data)) {
while ($row = mysqli_fetch_array($data)) {
$output .= '
<tbody>
<tr>
<td>'.$row['video_id'].'</td>
<td>'.$row['video_title'].'</td>
</tr>
';
}
$output .= '
<tr id="remove_row"><td><button type="button" id="more" class="btn btn-success form-control"
data-id="'.$row['video_id'].'">More</button></td></tr></tbody>
';
echo $output;
}
any help would be appriciated.
When you add a new row and there is a new button for More
It has the same id as the original button so there is a conflict there
also the javascript needs to be initiliazed something like this
PHP:
$output .= '<tr id="remove_row"><td><button type="button" class="more btn btn-success form-control" data-id="'.$row['video_id'].'">More</button></td></tr></tbody>';
Javascript:
<script>
function moreButton() {
$('.more').click(function(){
var id=$(this).data("id");
$.ajax({
url:"more.php",
data:{id:id},
method:"post",
success:function(data){
if(data!=''){
$('#load_data_table').append(data);
$('#remove_row').remove();
moreButton();
}
else{
$('.more:last').html("No Data");
}
}
});
}
$(document).ready(function(){
moreButton();
});
Don't forget to remove the id of the more button to a class with .more

Check all checkboxes on the current page only in datatables

I need a solution for this. Here is what I am trying to do. I have a datatable that has some values and check boxes in the first columns. What I need is when I select the check box in the header it should select all the values in the current page only. But all the check boxes of all the pages get selected.
I also want that, When I navigate to another page of the datatable, the check box selections of all the previous page should be unchecked including the check box in the header.
Hear is my code:
<?php if($acl->can('view_article')){ ?>
<table id="articles" class="table table-striped table-bordered" cellspacing="0" width="100%">
<thead>
<tr>
<?php if($acl->can('delete_article')){ ?>
<th><input id="select_all_existent" type="checkbox" /></th>
<?php } ?>
<th>Article</th>
<th>Categories</th>
<th>Demographic</th>
<th>Intended Month</th>
<th class="text-right">Word Count</th>
</tr>
</thead>
<tbody>
<?php
foreach($articles as $article) {
$id = $article["id"];
$uid = $article["uid"];
$article_name = $article["article_name"];
$article_file_path = $article["article_file_path"];
$article_category = $article["article_category"];
$article_demographic = $article["article_demographic"];
$article_word_count = $article["article_word_count"];
$intended_month = $article["intended_month"];
$article_created = $article["article_created"];
if(!empty($article_demographic)) {
$article_demographic = implode(", ",$article_demographic);
}
$article_keywords = $article["article_keywords"];
$article_description = $article["article_description"];
$checkbox = in_array($id, $assigned_articles)? " ":"<input type='checkbox' value=".$id." />";
echo "
<tr class='' data-id='$id'>
" ;
if($acl->can('delete_article'))
echo "<td>$checkbox</td>";
if($acl->can('edit_article')){
echo "<td>" . anchor("articles/edit/$id",$article_name.'- '.$article_word_count,"class='notBtn' title=\"$article_description\"") . " </td>";
}else{
echo "<td>$article_name - $article_word_count</td>";
}
echo "
<td>".short_string($article_category)."</td>
<td>".short_string($article_demographic)."</td>
<td> $intended_month </td>
<td align='right'>$article_word_count</td>
</tr>";
}
?>
</tbody>
</table>
<?php } ?>
<script type="application/javascript">
$(document).on( 'init', function ( e, settings ) {
alert( 'Saved page length is: '+ table.state().length );
} );
$(document).ready(function(){
var oTable = $("#articles").DataTable({
"stateSave": true,
"order": [],
"dom": '<"row" <"col-md-12 space" <"datatable-action pull-left"> <"datatable-n pull-right" l > > >rt <"row" <"col-md-6" i > <"col-md-6" p > >',
"columns" : [
<?php if($acl->can('delete_article')){ ?>
{orderable: false, searchable: false},
<?php } ?>
{"width": "25%" },
null,
null,
{"width": "12%" },
{"width": "10%" },
],
"fnDrawCallback": function( oSettings ) {
$('.popupArticle').viewArticle({
url : '<?=site_url("articles/showArticleInPopup");?>',
title : 'Article Preview',
size : 'lg'
});
}
});
$('#search-inp').on('keyup',function(){
oTable.search($(this).val()).draw() ;
})
if(oTable.state().length != 0)
$('#search-inp').val(oTable.state().search.search);
checkAllCheckbox(oTable);
var deletebtn = '';
<?php if($acl->can('delete_article')){ ?>
var deletebtn = '<i class="fa fa-trash-o"></i>';
<?php } ?>
var assignbtn = '';
<?php if($acl->can('assign_article')){ ?>
var assignbtn = '<i class="fa fa-paperclip"></i>';
<?php } ?>
$("div.datatable-action").html(deletebtn + ' ' +assignbtn);
$('#assignbtn').on('click', function (e) {
e.preventDefault();
eModal.setEModalOptions({loadingHtml : ''});
eModal.iframe('<?= site_url("assignArticles/e/"); ?>', 'Assign Article').then(function (input) {
$('.modal-dialog', window.document).css('width', '80%');
if ($('.modal-footer', window.document).length == 0) {
$('.modal-content', window.document).append('<div class="modal-footer"> </div>');
}
});
});
});
</script>
Here is the code for checkAllCheckbox(oTable);
function checkAllCheckbox(oTable) {
/* Check all in Datatable*/
if ($("#select_all_existent").length != 0) {
var cells = oTable.cells().nodes();
$("#select_all_existent").change(function () {
$(cells).find(":checkbox").prop("checked", $(this).is(":checked"));
});
$(cells).find(":checkbox").change(function(){
if(!$(this).is(":checked")){
$("#select_all_existent").prop("checked", $(this).is(":checked"));
}
else{
if ($(cells).find(":checkbox").length == $(cells).find(":checked").length) {
$("#select_all_existent").prop("checked",true);
}
}
if ($(cells).find(":checked").length > 0) {
$(oTable.table().container()).siblings().find('.help- block').html('');
}
else{
$(oTable.table().container()).siblings().find('.help- block').html('Please select at least one checkbox');
}
});
}
}
Any help on the scenarios that I have mentioned would be appreciated.
In your code made the following changes and try:
change 1: disable sorting of checkbox column
<thead>
<tr>
<?php if($acl->can('delete_article')){ ?>
<th data-orderable="false"><input id="select_all_existent" type="checkbox" /></th>
<?php } ?>
<th>Article</th>
<th>Categories</th>
<th>Demographic</th>
<th>Intended Month</th>
<th class="text-right">Word Count</th>
</tr>
</thead>
change 2:
add the following code to script:
$('#articles').on('page.dt', function() {
$('#select_all_existent').prop("checked", 0);
$('#select_all_existent').trigger('change');
});
$('#articles').on('length.dt', function() {
$('#select_all_existent').prop("checked", 0);
$('#select_all_existent').trigger('change');
});
$('#select_all_existent').on('change',function () {
checkAllCheckbox(oTable);
});

Categories