I am trying to add a new row to the existing table using Ajax, PHP and Jquery.
Ajax call is successful (tested it by placing alerts). But it displays the new row only if I refresh the entire page. I want the row to be added to the table with out refreshing the entire page, but just with a table refresh on the fly.
example : As I press Add button on the table, it should add a new row to the table on the fly.
hotTopics_focusAreas_data.php file :
<?php
$SQL = "select * from hottopics order by id desc limit 1";
while($row = mysql_fetch_array($SQL,MYSQL_ASSOC)) {
echo
"<tr>
<td id=title:".$row['id']." contenteditable='true'>".$row['title']."</td>
<td id=status:".$row['id']." contenteditable='true'>".$row['status']."</td>
<td><button type='button' class='btn btn-danger'>Delete</button></td>
</tr>";
}
?>
Javascript file :
$("document").ready(function() {
hotAddClicked();
});
function hotAddClicked(){
$("#hotadd_clicked").click(function(e) {
endpoint = 'hotTopics_focusAreas_data.php?role=add';
$.ajax({
url : endpoint,
type : "GET",
async : true,
success : function(data) {
$("#hottopics_table").append(data);
}
});
});
}
Table definition:
<table class="table" id="hottopics_table">
<thead>
<tr>
<th>Title</th>
<th>Status</th>
<th></th>
</tr>
</thead>
<tbody>
<?php
$SQL = "select * from hottopics;";
$result_update = mysql_query($SQL) or die("Couldn't execute query.".mysql_error());
while($row = mysql_fetch_array($result_update,MYSQL_ASSOC)) {
echo
"<tr>
<td id=title:".$row['id']." contenteditable='true'>".$row['title']."</td>
<td id=status:".$row['id']." contenteditable='true'>".$row['status']."</td>
<td><button type='button' class='btn btn-danger'>Delete</button></td>
</tr>";
}
?>
</tbody>
</table>
$(document).ready(function() {
$("#hotadd_clicked").click(function(e) {
endpoint = 'hotTopics_focusAreas_data.php?role=add';
$.ajax({
url : endpoint,
type : "GET",
async : true,
success : function(data) {
$("#hottopics_table tbody").append(data);
}
});
});
});
Check this jQuery script and check if it works properly.
Related
I am trying to display database records to my console in json format but i can't see why my request in json format is not being displayed on my console. There is no error also to guide me where i made a mistake. can someone help me. I use the MVC framework for writing my code. I want to retrieve horse names based on race number from the race table in the database.
here is my home.php
<div class="box-body">
Start creating your amazing application!
<table class="table table-bordered table-striped dt-responsive tables" width="100%">
<thead>
<tr>
<th style="width:10px">#</th>
<th>id</th>
<th>Race Number</th>
<th>Horse Name</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<?php
$users = ControllerUsers::ShowallUsersCtr();
foreach ($users as $key => $value) {
echo '
<tr>
<td>'.($key+1).'</td>
<td>'.$value["id"].'</td>
<td>'.$value["racenumber"].'</td>
<td>'.$value["horsename"].'</td>';
echo '<td>
<div class="btn-group">
<button class= "btn btn-primary btnAddRace" RaceNumber="'.$value["racenumber"].'" data-toggle="modal" data-target="#editUser">Add Horse - Race 1</button>
</div>
</td>
</tr>';
}
?>
</tbody>
</table>
</div>
here is my javascript file code named users.js
$(document).on("click", ".btnAddRace", function(){
var RaceNumber = $(this).attr("RaceNumber"); // capture the race number from database to the console
console.log("RaceNumber",RaceNumber);
var data = new FormData();
data.append("RaceNumber",RaceNumber);
$.ajax({
url: "ajax/users.ajax.php",
method: "POST",
data: data,
cache: false,
contentType: false,
processData: false,
dataType: "json",
success: function(answer){
console.log("answer", answer); // bring from the database whatever we asked for
}
});
});
And here is my Ajax file users.ajax.php
<?php
require_once "../controllers/users.controller.php";
require_once "../models/users.model.php";
class AjaxUsers{
public $RaceNumber;
public function ajaxEditUser(){
$item = "racenumber";
$value = $this->RaceNumber; // value what is selected from the table
$answer = ControllerUsers::ctrShowUsers($item, $value); // ask for the controller to show me the race table
echo json_encode($answer);
}
}
if (isset($_POST["RaceNumber"])) { // if the variable race number comes with information, we can execute all of this
$edit = new AjaxUsers();
$edit -> RaceNumber = $_POST["RaceNumber"];
$edit -> ajaxEditUser();
}
here is my user controller and model methods
static public function ctrShowUsers($item, $value){
$table = "race";
$answer = UsersModel::MdlShowUsers($table, $item, $value);
return $answer;
}
static public function MdlShowUsers($table, $item, $value){
$stmt = Connection::connect()->prepare("SELECT * FROM $table WHERE $item = :$item");
$stmt -> bindParam(":".$item, $value, PDO::PARAM_INT);
$stmt -> execute();
return $stmt -> fetch();
$stmt -> close();
$stmt = null;
}
Database Picture is here
enter image description here
I want to refresh the jquery datatable every 3 seconds. I already done this but I have pagination issues. When I execute the code the pagination is gone so all the data is display without pagination.
Here is my code:
<div id="timexx">
<table id="example1" class="table table-bordered table-striped" style="margin-right:-10px">
<thead>
<tr>
<th>id #</th>
<th>Name</th>
</tr>
</thead>
<?php
include('../dist/includes/dbcon.php');
$query=mysqli_query($con,"SELECT * FROM accounts_tic WHERE statuss = 'New' OR statuss = 'On-Process' order by id DESC")or die(mysqli_error());
while($row=mysqli_fetch_array($query)){
$id=$row['id'];
$name=$row['name'];
?>
<tr>
<td>
<?php echo $id;?>
</td>
<td>
<?php echo $name;?>
</td>
</tr>
<?php }?>
</table>
</div>
And this is my javascript code:
$(document).ready(function() {
setInterval(function() {
$('#timexx').load(location.href + " #timexx>*", "")
}, 3000);
});
I would recommend using an ajax data source along with ajax.reload(). In fact, the docs page I linked there has an example of just what you are after.
For your markup you can simply create the table and header:
<table id="example1" class="table table-bordered table-striped" style="margin-right:-10px">
<thead>
<tr>
<th>id #</th>
<th>Name</th>
</tr>
</thead>
</table>
Then initialize datatables with ajax data source, declare your columns and start the loop:
$(document).ready( function () {
var table = $('#example1').DataTable({
"ajax" : 'http://example.com/table_data.php',
"columns" : [
{ "data" : "id" },
{ "data" : "name" )
]
});
setInterval(function () {
// the second argument here will prevent the pagination
// from reseting when the table is reloaded
table.ajax.reload( null, false );
}, 3000);
});
Now you need a web page at the endpoint declared for your ajax data source http://example.com/table_data.php that spits out the table data as a json. There are a few ways this can be structured, but my preference is to use the data property as the docs state:
the data parameter format shown here can be used with a simplified DataTables initialisation as data is the default property that DataTables looks for in the source data object.
With this objective, your php script might look something like this:
include('../dist/includes/dbcon.php');
$query = mysqli_query($con, "SELECT * FROM accounts_tic WHERE statuss = 'New' OR statuss = 'On-Process' order by id DESC") or die(mysqli_error($con));
$results = [];
while ($row=mysqli_fetch_array($query)) {
$results['data'][] = [
'id' => $row['id'],
'name' => $row['name']
];
}
echo json_encode($results);
Side note, mysqli_error() expects a single argument which should be your connection resource.
Screenshot
<?php
if(isset($_GET['View']) && $_GET['View']=="HistoryEntry"){
echo '
<h2>History Of Entries</h2>
<table id="table" class="table table-hover">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Date In</th>
<th scope="col">Date Out</th>
<th scope="col">Rfid</th>
<th scope="col">Plate #</th>
</tr>
</thead>
<tbody>';
global $connection;
$query = "SELECT * FROM history_entries";
$result = mysqli_query($connection, $query);
while($row = mysqli_fetch_assoc($result)){
echo '<tr>
<th scope="row">'.$row['Entry_ID'].'</th>
<td>'.$row['Date_in'].'</td>
<td>'.$row['Date_out'].'</td>
<td>'.$row['Acc_rfid'].'</td>
<td>'.$row['Plate_num'].'</td>
</tr>';
}
echo ' </tbody>
</table>
<center>
<button>Delete</button>
</center>
<div class="line"></div>';
}
?>
?>
$("#table tr").click(function() {
$('.selected').removeClass('selected');
$(this).addClass("selected");
});
$("#Sample").click(function() {
var value = $(".selected th:first").html();
value = value || "No row Selected";
});
As you can see this my codes, i already know how to select the row and get the ID but cant pass the ID "value" to php in order to do the delete function in database. can i use here $.POST function here? or is it better to use GET function here but i think it wouldn't be secure.
This is how you can do it without get param :
1/ Your FRONT :
HTML (just an example)
<table>
<tr id="row_id">
<td>Data 1</td>
<td>Data 2</td>
...
</tr>
...
</table>
<button id="delete_row" type="button">Delete</button>
JS / jQuery
var current_row_id = "";
// You select the row
$("#table tr").click(function() {
$('.selected').removeClass('selected');
$(this).addClass("selected");
current_row_id = $(this).attr("id"); // Here you get the current row_id
});
// You delete the row
$("#delete_row").on("click", function() {
$.ajax({
type: "POST",
url: "delete.php",
data: {"id" : current_row_id }, // You send the current_row_id to your php file "delete.php" in post method
dataType: 'json', // you will get a JSON format as response
success: function(response){
// you do something if it works
},
error: function(x,e,t){
// if it doesn't works, check the error you get
console.log(x.responseText);
console.log(e);
console.log(t);
}
});
});
2/ Your BACK
PHP "delete.php" file
<?php
$id = $_POST['id']; // You get the 'current_row_id' value
// Now you do your DELETE request with this id :
$sql = "DELETE ... WHERE id = :id";
etc...
$result = array(); // You can prepare your response and send information about what you did
$result['row_deleted'] = $id;
$result['message'] = "The row with id = " . $id . " was deleted with success";
$result['type'] = "success";
//etc....
echo json_encode($result); // You send back a response in JSON format
3/ Back to the FRONT
Your ajax call, the success part :
success: function(response){
// You can display a success message for example using your response :
alert(response.message); // You will get 'The row with id = {the row id} was deleted with success' here for example
},
Is it what you are looking for?
here is a simple Ajax request
var data = {
rowId: 1
};
$.ajax({
type: "POST",// GET|POST
url: 'delete.php', // Where you want to send data like url or file
data: data, // this is what you want to send to server, in this case i send data with id = 1 to server
dataType: 'json' // here we say what data type we want "json"
success: function(response) {
alert(response);
}, // this is the callback were u will get response from your server
});
delete.php here is how u can handle this ajax
$rowId = htmlspecialchars($_POST['rowId']);
if ($rowId) {
global $connection;
$query = "DELETE FROM history_entries WHERE Entry_ID = " . $rowId;
$result = mysqli_query($connection, $query);
$response = array(
'success' => true
);
echo json_encode($response);
exit;
} else {
echo json_encode(array('success' => false));
exit;
}
Hope this will help you to understand how to use Ajax
This is my index.php view were my table is placed
<table class="striped">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Address</th>
<th>Created at</th>
</tr>
</thead>
<tbody id="showdata">
<!--<tr>
<td>1</td>
<td>Alvin</td>
<td>Eclair</td>
<td>$0.87</td>
<td>
Edit
Delete
</td>
</tr>-->
</tbody>
</table>
This my ajax script placed on index.php
function showAllEmployee() {
$.ajax({
type: 'ajax',
url: '<?php echo base_url(); ?>index.php/Employee/showAllEmployee',
async: false,
dataType: 'json',
success: function(data) {
//console.log(data);
var html = '';
var i;
for (i=0; i<data.length; i++) {
html += '<tr>'+
'<td>'+data[i].emp_id+'</td>'+
'<td>'+data[i].name+'</td>'+
'<td>'+data[i].address+'</td>'+
'<td>'+data[i].created_at+'</td>'+
'<td>'+
'Edit'+
'Delete'+
'</td>'+
'</tr>';
}
$('#showdata').html(html);
},
error: function() {
alert('Could not get data from database');
}
});
}
This is what i have on my employee controller
public function showAllEmployee()
{
$result = $this->em->showAllEmployee();
echo json_encode($result);
}
This is my model
public function showAllEmployee()
{
$this->db->order_by('created_at', 'desc');
$query = $this->db->get('tbl_employees');
if($query->num_rows() > 0) {
return $query->result();
} else {
return false;
}
}
Whenever i refresh the page the data wont display instead i run into an error could not get the data from the database which is the condition i set on my ajax script what could be wrong pls help
set header as JSON type in the controller
change your controller to
public function showAllEmployee(){
$result = $this->em->showAllEmployee();
$this->output
->set_content_type('application/json')
->set_output(json_encode($result));
}
I need to update a row of a table. So when I click on a cell, I want it to be transformed into text box, so I used this:
<td contenteditable></td>
And then, when the content of a <td> is changed, I need to send it through AJAX to update it in the server without clicking on a button, so it will use the .change(function()).
I tried to get the content changed into a variable:
$("TD").change(function()
{
//Here I want to set the row ID:
var rowid = '<?php echo $row['id'] ?>';
var name = $("#emp_name").val();
var position = $("#position").val();
var salary = $("#salary").val();
$.ajax
({
url: 'update.php',
type: 'POST',
data: {dataId: rowid, data1: name, data2: position, data3: salary},//Now we can use $_POST[data1];
dataType: "text",
success:function(data)
{
if(data=="success")
{
//alert("Data added");
$("#before_tr").before("<tr><td>"+emp+"</td><td>"+pos+"</td><td>"+sal+"</td></tr>");
$("#emp_name").val("");
$("#position").val("");
$("#salary").val("");
}
},
error:function(data)
{
if(data!="success")
{
alert("data not added");
}
}
});
});
The problem is how to know which row is changed to send it via AJAX ? I am not getting any errors even when data not updated.
Here is the update.php code:
try
{
$rowid = $_POST['dataId'];
$emp_name = $_POST['data1'];
$pos = $_POST['data2'];
$sal = $_POST['data3'];
$upd = "UPDATE emp SET name = :emp_name, position = :pos, sal = :sal WHERE id = :rowid";
$updStmt = $conn->prepare($upd);
$updStmt->bindValue(":rowid", $rowid);
$updStmt->bindValue(":emp_name", $emp_name);
$updStmt->bindValue(":pos", $pos);
$updStmt->bindValue(":sal", $sal);
$updStmt->execute();
echo "success";
}
catch(PDOException $ex)
{
echo $ex->getMessage();
}
HTML:
<tbody>
<?php
$sql = "SELECT * FROM employee";
$stmt=$conn->prepare($sql);
$stmt->execute();
$res=$stmt->fetchAll();
foreach($res as $row){
?>
<tr id=""<?php echo $row['id'] ?>"">
<td contenteditable><?php echo $row['emp_name'] ?></td>
<td contenteditable><?php echo $row['position'] ?></td>
<td contenteditable><?php echo $row['salary'] ?></td>
</tr>
<?php } ?>
When loading your data with PHP you need to keep the row id in your html:
<tr id="<?php echo $yourList["id"]; ?>">
<td contenteditable></td>
</tr>
Then in your javascript you can catch it using the parent() jquery function
$("TD").change(function()
{
//Here I want to set the row ID:
var rowid =$(this).parent().attr("id");
......
UPDATE
Check this example, I have added listeners to detect contenteditable td changes, I think you shall add it too , refer to this contenteditable change events for defining proper change events on contenteditable fields.
Explanation:
The contenteditable does not trigger change events, this work around is used to detect the focus event of the td using jquery on method and event delegation. The original content is saved in the td jquery data object $this.data('before', $this.html()); . Then when the user leaves the field or triggers any of the events 'blur keyup paste input', the current content is compared to the content in the data object, if it differs, the change event of the td is triggered.
$(document).ready(function(){
$('table').on('focus', '[contenteditable]', function() {
var $this = $(this);
$this.data('before', $this.html());
return $this;
}).on('blur keyup paste input', '[contenteditable]', function() {
var $this = $(this);
if ($this.data('before') !== $this.html()) {
$this.data('before', $this.html());
$this.trigger('change');
}
return $this;
});
$("TD").change(function()
{
//Here I want to set the row ID:
var rowid = $(this).parent().attr("id");
$("#res").html(rowid);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table border="1" width="500px">
<tr id="1222">
<td contenteditable></td>
</tr>
<tr id="55555">
<td contenteditable></td>
</tr>
</table>
Row Id : <span id="res"></span>
<tr row_id="<?php echo $row['id'] ?>"> ></tr>
In Your Ajax
var rowid = $(this).attr('row_id');