Load more button works just once - php

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

Related

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 apply the datatable filters to my php code?

I am getting some data and displaying on the table which i have created in my php code however i want to apply the data table filters but i cannot seem to find a solution. I know in html i can assign an id to the table and then call it from a js script using the following code var table = $('#myTable').DataTable({"dom":"ftip"}); however this doesn't seem to work in my code. Perhaps because i am wrapping the html code in php?
Thanks
<script>
$(document).ready(function(){
var table = $('#myTable').DataTable({"dom":"ftip"});
});
</script>
<?php
$conn = mysqli_connect('localhost', 'root', '""', 'calendar');
extract($_POST);
if(isset($_POST['readrecords'])){
$data = '<table class="table table-bordered table-striped" id="myTable">
<tr class="bg-dark text-white">
<th>No.</th>
<th>Title</th>
<th>Driver</th>
<th>Date</th>
</tr>';
$displayquery = "SELECT id,title, driver, start FROM `events` ";
$result = mysqli_query($conn,$displayquery);
if(mysqli_num_rows($result) > 0){
$number = 1;
while ($row = mysqli_fetch_array($result)) {
$data .= '<tr>
<td>'.$number.'</td>
<td>'.$row['title'].'</td>
<td>'.$row['driver'].'</td>
<td>'.$row['start'].'</td>
<td>
<button onclick="GetUserDetails('.$row['id'].')" class="btn btn-success">Edit</button>
</td>
<td>
<button onclick="DeleteUser('.$row['id'].')" class="btn btn-danger">Delete</button>
</td>
</tr>';
$number++;
}
}
$data .= '</table>';
echo $data;
}
?>
function readRecords(){
var readrecords = "readrecords";
$.ajax({
url:"backend.php",
type:"POST",
data:{readrecords:readrecords},
success:function(data,status){
$('#records_content').html(data);
},
});
}

Error retrieving indexes using $_POST from skeleton table in Ajax. Undefined index

So, I'm trying to make a live interactive table that can do active CRUD, but for some reason, the values I'm trying to insert for the add feature are not correctly being read to $_POST.
Here is the table:
<?php
include "../db.php";
$connection = DB::CreateConnection();
$output = '';
$sql = "SELECT * FROM users ORDER BY userid ASC";
$result = mysqli_query($connection, $sql);
$output .= '
<div class="table-responsive">
<table class="table table-bordered">
<tr>
<th width="10%">Id</th>
<th width="40%">First Name</th>
<th width="40%">Last Name</th>
<th width="10%">Delete</th>
</tr>';
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_array($result))
{
$output .= '
<tr>
<td>'.
$row["userid"].'</td>
<td class="userfirstname" data-id1="'.$row["userid"].'" contenteditable>'.$row["userfirstname"].'</td>
<td class="userlastname" data-id2="'.$row["userid"].'" contenteditable>'.$row["userlastname"].'</td>
<td><button type="button" name="delete_btn" data-id3="'.$row["userid"].'" class="btn btn-xs btn-danger btn_delete">x</button></td>
</tr>';
}
$output .= '
<tr>
<td></td>
<td id="userfirstname" contenteditable></td>
<td id="userlastname" contenteditable></td>
<td><button type="button" name="btn_add" id="btn_add" class="btn btn-xs btn-success">+</button></td>
</tr>';
}
else
{
$output .= '<tr>
<td colspan="4">Data not Found</td>
</tr>';
}
$output .= '</table>
</div>';
echo $output;
?>
Here it the live data edit file:
<!-- This should be where matt's code goes to edit via popup or live -->
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<div class="container">
<br />
<br />
<br />
<div class="table-responsive">
<h3 align-"center">Live Table</h3>
<br />
<div id="live_data"></div>
</div>
</div>
</body>
<script type="text/javascript">
function fetch_data()
{
$.ajax({
url:"UViewTABLE.php",
method:"POST",
success:function(data){
$('#live_data').html(data);
}
});
}
fetch_data();
$(document).on('click', '#btn_add', function(){
var userfirstname = $('#userfirstname').text();
var userlastname = $('#userlastname').text();
if(userfirstname == '')
{
alert("Enter First Name");
return false;
}
if(userlastname == '')
{
alert("Enter Last Name");
return false;
}
$.ajax({
url:"UViewTABLEinsert.php",
method:"POST",
data:{userfirstname:userfirstname, userlastname:userlastname},
dataType:"text",
success:function(data)
{
alert(data);
fetch_data();
}
})
});
</script>
Here is the insert file:
<?php
include "../db.php";
$connection = DB::CreateConnection();
$sql = "INSERT INTO users (userfirstname, userlastname) VALUES('".$_POST["userfirstname"]."', '".$_POST["userlastname"]."')";
if(mysqli_query($connection, $sql))
{
echo 'Data Inserted';
}
?>
The error I get is:
Notice: Undefined index: userfirstname in
/var/www/html/UOM/UViewTABLEinsert.php on line 4
Notice: Undefined index: userlastname in
/var/www/html/UOM/UViewTABLEinsert.php on line 4
And, I know that means in my edit file, I'm not defining those indexes properly, but I can't see anything wrong with it. I have researched this problem for 3 days, if someone is kind enough to help, please do, evidently I don't know what I'm doing wrong.
Just remove the dataType from ajax options because you are explicitly setting the data type to text, the data is not submitting in key value pair, and after insertion, send response in JSON, may work. For more about $.ajax's dataType option, refer this. If you want to set dataTyp explicitly, then keep the response in same type as set in ajax request.

AJAX live insert delete search, shows items 2 times

When i insert an item it is shown on the list 2 times, but on mysql table it is registered just one time. It started when i started using sessions. Thank you in advance.
index.php
<html>
<head>
<title>Live Table Data Edit</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
</head>
<body>
<div class="container">
<br />
<br />
<br />
<div class="table-responsive">
<h3 align="center">Lista articulos prestados</h3><br />
<div id="live_data"></div>
</div>
</div>
</body>
</html>
<script>
$(document).ready(function(){
function fetch_data()
{
$.ajax({
url:"select.php",
method:"POST",
success:function(data){
$('#live_data').html(data);
}
});
}
fetch_data();
$(document).on('click', '#btn_add', function(){
var Articulo = $('#Articulo').text();
var fecha = $('#fecha').text();
var emailpresta = $('#emailpresta').text();
var emailrecibe = $('#emailrecibe').text();
if(Articulo == '')
{
alert("Ingresa Articulo");
return false;
}
if(fecha == '')
{
alert("Ingresa Fecha");
return false;
}
if(emailpresta == '')
{
alert("Ingresa tu email");
return false;
}
if(emailrecibe == '')
{
alert("Ingresa email tercero");
return false;
}
$.ajax({
url:"insert.php",
method:"POST",
data:{Articulo:Articulo, fecha:fecha, emailpresta:emailpresta, emailrecibe:emailrecibe },
dataType:"text",
success:function(data)
{
alert(data);
fetch_data();
}
})
});
$(document).on('click', '.btn_delete', function(){
var id=$(this).data("id3");
if(confirm("Are you sure you want to delete this?"))
{
$.ajax({
url:"delete.php",
method:"POST",
data:{id:id},
dataType:"text",
success:function(data){
alert(data);
fetch_data();
}
});
}
});
});
</script>
select.php
<?php
session_start();
$check_usuario = $_SESSION['email'];
$connect = mysqli_connect("######", "######", "", "############");
$output = '';
$sql = "SELECT * FROM articulos INNER JOIN usuarios WHERE emailpresta='".$check_usuario."'";
$result = mysqli_query($connect, $sql);
$output .= '
<div class="table-responsive">
<table class="table table-bordered">
<tr>
<th width="10%">Id</th>
<th width="40%">Articulo</th>
<th width="40%">Fecha(Formato: AAAA-MM-DD)</th>
<th width="40%">Email-presta</th>
<th width="40%">Email-recibe</th>
<th width="10%">Borrar</th>
</tr>';
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_array($result))
{
$output .= '
<tr>
<td>'.$row["id"].'</td>
<td class="Articulo" data-id1="'.$row["id"].'" contenteditable>'.$row["Articulo"].'</td>
<td class="fecha" data-id2="'.$row["id"].'" contenteditable>'.$row["fecha"].'</td>
<td class="emailpresta" data-id2="'.$row["id"].'" contenteditable>'.$row["emailpresta"].'</td>
<td class="emailrecibe" data-id2="'.$row["id"].'" contenteditable>'.$row["emailrecibe"].'</td>
<td><button type="button" name="delete_btn" data- id3="'.$row["id"].'" class="btn btn-xs btn-danger btn_delete">x</button></td>
</tr>
';
}
$output .= '
<tr>
<td></td>
<td id="Articulo" contenteditable></td>
<td id="fecha" contenteditable></td>
<td id="emailpresta" contenteditable></td>
<td id="emailrecibe" contenteditable></td>
<td><button type="button" name="btn_add" id="btn_add" class="btn btn-xs btn-success">+</button></td>
</tr>
';
}
else
{
$output .= '<tr>
<td></td>
<td id="Articulo" contenteditable></td>
<td id="fecha" contenteditable></td>
<td id="emailpresta" contenteditable></td>
<td id="emailrecibe" contenteditable></td>
<td><button type="button" name="btn_add" id="btn_add" class="btn btn-xs btn-success">+</button></td>
</tr>';
}
$output .= '</table>
</div>';
echo $output;
?>
insert.php
<?php
session_start();
$connect = mysqli_connect("############", "############", "", "############");
$sql = "INSERT INTO articulos(Articulo, fecha, emailpresta, emailrecibe) VALUES('".$_POST["Articulo"]."', '".$_POST["fecha"]."'
, '".$_POST["emailpresta"]."', '".$_POST["emailrecibe"]."')";
if(mysqli_query($connect, $sql))
{
echo 'Data Inserted';
}
?>
delete.php
<?php
session_start();
$connect = mysqli_connect("############", "############", "", "############");
$sql = "DELETE FROM articulos WHERE id = '".$_POST["id"]."'";
if(mysqli_query($connect, $sql))
{
echo 'Data Deleted';
}
?>
The problem is likely with you MySQL query. What shows up on screen when you execute the following:
//session_start(); <-- do not start session
$email = '......'; <-- use an email from the DB with data available
$sql = "SELECT * FROM articulos INNER JOIN usuarios
WHERE emailpresta='$email'";
$connect = mysqli_connect(...);
$result = mysqli_query($connect,$sql);
$data = mysqli_fetch_all($result));
print_r($data);
Do you see duplicate rows? If so, you'll need to work on your SQL query. Specifically, you don't tell the database how to join the articulos and usarios tables. Instead of
SELECT * from articulos INNER JOIN usarios WHERE emailpresta='$email'
You probably need something like:
SELECT * from articulos INNER JOIN usarios ON articulos.userID=usarios.ID
WHERE usarios.emailpresta='$email'
Instead of articulos.userID and usarios.ID, use the fields in the two tables that match up. You can learn a bit about INNER JOIN here
Side note
I noticed that you plug $_SESSION['email'] directly into your DB query. If this is a value that you received from the user, you run a huge risk of SQL injection attack, a way for anyone to execute any query (including extracting, modifying or deleting your DB records) using specially crafted inputs. Look into using parameterized queries instead. Even if the contents of $_SESSION['email'] are safe, running raw queries is a risky habit anywhere you take input from the user.

unable to do inline editing with php code igniter and jquery. Not able to update table values in the database

this is my edit_table.php in which dynamic table is generated and by on click function i try to update database.
<script>
function table_edit(btn)
{
var id=btn.id;
if(btn.value=="Edit")
{
document.getElementById('college_id'+id).setAttribute("contenteditable" , "true");
document.getElementById('name'+id).setAttribute("contenteditable" , "true");
//document.getElementById('university_id'+id).removeAttribute("Readonly");
document.getElementById('university_id'+id).setAttribute("contenteditable" , "true");
document.getElementById(id).value="Save";
return false;
}
if(btn.value=="Save")
{
document.getElementById('name'+id).removeAttribute("contenteditable");
document.getElementById('college_id'+id).removeAttribute("contenteditable");
// document.getElementById('university_id'+id).setAttribute("Readonly" , "readonly");
document.getElementById('university_id'+id).removeAttribute("contenteditable");
document.getElementById(id).value="Edit";
var newuniversity_id=document.getElementById('university_id'+id).innerHTML;
var newcollege_id=document.getElementById('college_id'+id).innerHTML;
var newname=document.getElementById('name'+id).innerHTML;
alert(newname+" "+newcollege_id+" "+newuniversity_id+" "+id);
var dataString = 'name1=' + name + '&university_id=' + newuniversity_id + '&college_id=' + newcollege_id + '&id=' + id;
$.ajax({
type: "POST",
url: "update_table_data",
data: dataString,
success: function(html) {
alert("ajax calling done");
}
});
return true;
}
}
function table_update(){
//document.getElementById("edit_rows").value="Save"
alert("Working!");
}
</script>
<?php
function test()
{
echo "<script>alert('hello');</script>";
} ?>
<div id="page-content-wrapper">
<div class="container-fluid">
<i class="fa fa-bars"></i> <span>Menu</span>
<div class="content-block">
<div class="login-sign forgot_pass login forgot text-center">
<!-- <form action="<?php echo base_url(); ?>edit_table" method="post" accept-charset="utf-8"> -->
<div class="login-signup-head">Edit Table</div>
<table>
<tbody>
<thead>
<tr class="tredit">
<!-- <th width="10"></th> -->
<th> Id </th>
<th > University Id </th>
<th > Name </th>
<th > College Id </th>
<th width="100"> </th>
</tr>
</thead>
<tbody>
<?php
foreach($student_data as $row){
?>
<tr class="tredit" id="row_edit">
<td><?php echo $row['id']; ?></td>
<td id="university_id<?php echo $row['id']; ?>" ><?php echo $row['university_id']; ?></td>
<td id="name<?php echo $row['id']; ?>" ><?php echo $row['name']; ?></td>
<td id="college_id<?php echo $row['id']; ?>" > <?php echo $row['college_id']; ?></td>
<td><input type='button' class='editable' onclick=" return table_edit(this)" value='Edit' id= "<?php echo $row['id']; ?>">
<input type='button' class='tabledelete' onclick="table_update()" value='Delete' ></td>
</tr>
<?php
}
?>
</div>
</div>
</div>
<!-- </form> -->
</div>
</div>
</tbody>
</table>
and this is the route
$route['update_table_data'] = 'home/update_table';
and the following functions are for fetching the data as well as updating the data.
public function tableedit(){
if($this->session->userdata('university_id')){
$user_id = $this->session->userdata('university_id');
$data['user_id'] = $user_id;
$data['student_data'] = $this->home_model->table_data($user_id);
$this->load->view('home/new-header',$data);
$this->load->view('home/left_university_sidebar',$data);
$this->load->view('edit_table',$data);
$this->load->view('home/footer');
} else {
$data['error'] = 'Table Cannot be viewed!';
$this->load->view('home/header');
$this->load->view('edit_table');
$this->load->view('home/footer');
}
}
public function update_table() {
if($this->session->userdata('university_id')){
if($this->input->server("REQUEST_METHOD") === "POST"){
$university_id=$_POST['university_id'];
$college_id=$_POST['college_id'];
$id=$_POST['id'];
$name=$_POST['name'];
$this->home_model->update_table($university_id,$college_id,$name,$id);
}
}
}
and finally this is the model for update query.
public function update_table($university_id,$college_id,$name,$id) {
$data = array('University Id' => $university_id, 'name' => $name, 'College Id' => $college_id);
$this->db->where('id', $id);
$this->db->update('college', $data);
}
editable table
edit values
but when i save and refresh the page, no change occur in the table.
my issue is database is not updated when i update it from save button.
first of all :
Formatting your code , that must be clean and easily readable
for your ajax call you dont need use routed url , it work at background, you can use like this :
put : <script>var base_url='<?php echo base_url(); ?>'</script>
in your header menu , or upper place that you use in your theme.
then make ajax call like this:
$.ajax({
type: "POST",
url: base_url+"youController/yourAction",
data: dataString,
success: function(html) {
alert("ajax calling done");
}
});

Categories