I have some Ajax code all code working fine but the problem is the loading image showing continually.
I want to hide the image on success and also want to change background of table column.
My current code:
index.php
<?php
include_once("db_connect.php");
?>
<title>phpzag.com : Demo Inline Editing using PHP MySQL and jQuery Ajax</title>
<script type="text/javascript" src="script/jquery-3.1.1.js"></script>
<link rel="stylesheet" type="text/css" href="bootstrap-4.0.0-alpha.5-dist/css/bootstrap.min.css"/>
<script type="text/javascript" src="script/functions.js"></script>
<div class="container">
<h2>Example: Inline Editing using PHP MySQL and jQuery ajax</h2>
<?php
$sql = "SELECT id, employee_name, employee_salary, employee_age FROM table_record";
$resultset = mysqli_query($conn, $sql) or die("database error:". mysqli_error($conn));
?>
<table class="table table-condensed table-hover table-striped bootgrid-table">
<thead>
<tr>
<th>Employee Name</th>
<th>Salary</th>
<th>Age</th>
</tr>
</thead>
<tbody>
<?php
while( $rows = mysqli_fetch_assoc($resultset) ) {
?>
<tr>
<td contenteditable="true" data-old_value="<?php echo $rows["employee_name"]; ?>" onBlur="saveInlineEdit(this,'employee_name','<?php echo $rows["id"]; ?>')" onClick="highlightEdit(this);"><?php echo $rows["employee_name"]; ?></td>
<td contenteditable="true" data-old_value="<?php echo $rows["employee_salary"]; ?>" onBlur="saveInlineEdit(this,'employee_salary','<?php echo $rows["id"]; ?>')" onClick="highlightEdit(this);"><?php echo $rows["employee_salary"]; ?></td>
<td contenteditable="true" data-old_value="<?php echo $rows["employee_age"]; ?>" onBlur="saveInlineEdit(this,'employee_age','<?php echo $rows["id"]; ?>')" onClick="highlightEdit(this);"><?php echo $rows["employee_age"]; ?></td>
</tr>
<?php
}
?>
</tbody>
</table>
<div style="margin:50px 0px 0px 0px;">
<a class="btn btn-default read-more" style="background:#3399ff;color:white" href="http://www.phpzag.com/inline-editing-using-php-mysql-and-jquery-ajax" title="Inline Editing using PHP MySQL and jQuery ajax">Back to Tutorial</a>
</div>
</div>
Database connection
<?php
/* Database connection start */
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "dynamic_test";
$conn = mysqli_connect($servername, $username, $password, $dbname) or die("Connection failed: " . mysqli_connect_error());
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
?>
Mysql update query
<?php
include_once("db_connect.php");
$sql = "UPDATE table_record set " . $_POST["column"] . " = '".$_POST["value"]."' WHERE id=".$_POST["id"];
mysqli_query($conn, $sql) or die("database error:". mysqli_error($conn));
exit;
?>
Ajax query
function highlightEdit(editableObj) {
$(editableObj).css("background", "#FFF");
}
function saveInlineEdit(editableObj, column, id) {
// No change change made then return false
if ($(editableObj).attr('data-old_value') === editableObj.innerHTML)
return false;
// Send ajax to update value
$(editableObj).css("background", "#FFF url(loader.gif) no-repeat right");
$.ajax({
url: "saveInlineEdit.php",
type: "POST",
dataType: "json",
data: 'column=' + column + '&value=' + editableObj.innerHTML + '&id=' + id,
success: function(response) {
// Set updated value as old value
$(editableObj).attr('data-old_value', editableObj.innerHTML);
$(editableObj).css("background", "#dcd8d8");
},
error: function() {
console.log("errr");
}
});
}
Use beforeSend method for ajax like success and error method.
function highlightEdit(editableObj) {
$(editableObj).css("background", "#FFF");
}
function saveInlineEdit(editableObj, column, id) {
// No change change made then return false
if ($(editableObj).attr('data-old_value') === editableObj.innerHTML)
return false;
// Send ajax to update value
//$(editableObj).css("background", "#FFF url(loader.gif) no-repeat right");
$.ajax({
url: "saveInlineEdit.php",
type: "POST",
dataType: "json",
data: 'column=' + column + '&value=' + editableObj.innerHTML + '&id=' + id,
beforeSend : function(res){
$(editableObj).css("background", "#FFF url(loader.gif) no-repeat right");
},
success: function(response) {
// Set updated value as old value
$(editableObj).attr('data-old_value', editableObj.innerHTML);
$(editableObj).css("background", "#dcd8d8");
},
error: function() {
console.log("errr");
}
});
}
As #Luka Kvavilashvili said, your $(editableObj).css("background","#dcd8d8"); will only set the background-color, and not change the other styles, so you must change it to:
success: function(response) {
// Set updated value as old value
$(editableObj).attr('data-old_value', editableObj.innerHTML);
$(editableObj).css({"background-image":"none", "background":"#dcd8d8"});
}
another good solution wold be to make use of CSS, doing
td { background: #dcd8d8; }
.loading { background: #fff url(loader.gif) no-repeat right; }
and changing the js code to something like
$(editableObj).addClass('loading');
$.ajax({
...
success: function(response) {
// Set updated value as old value
$(editableObj).attr('data-old_value', editableObj.innerHTML);
$(editableObj).removeClass('loading');
}
...
Related
I am using DataTables with ajax using PHP CodeIgniter Framework. I am having a problem with switching Active buttons to Inactive buttons, vice versa.
What I want is:
When I click Active button, It should change to Inactive in realtime without refreshing the page.
Controller:
function activateStatus() {
$id = $this->uri->segment(3);
$data = array(
'status' => 1
);
$this->equip_model->updateAccount('equip', $data, array('id' =>$id));
}
function deactivateStatus() {
$id = $this->uri->segment(3);
$data = array(
'status' => 0
);
$this->equip_model->updateAccount('equip', $data, array('id' =>$id));
}
View:
<table class="table table table-hover table-bordered" id="equipmain">
<thead>
<tr>
<th>ID</th>
<th>Status</th>
</tr>
</thead>
<tbody>
<?php
foreach ($equip as $row){
?>
<tr>
<td style="display: none;"><?= $row->id ?></td>
<td align="center">
<?php
$status = $row->status;
if($status == "1") { ?>
<button id="<?php echo $row->id ?>" class="btn btn-xs green-jungle statusupdate1">✓</button>
<?php } else { ?>
<button id="<?php echo $row->id ?>" class="btn btn-xs red-flamingo statusupdate0" >✕</button>
<?php } ?>
</td>
</tr>
</tbody>
</table>
AJAX:
var oTable = $('#equipmain').DataTable( {
"searching": false,
"processing":true,
"columnWidth": 20,
"serverSide": true,
"autoWidth": true,
});
$(document).on('click', '.statusupdate0', function() {
var id = $(this).attr("id");
$.ajax({
url: "<?= base_url() ?>Admin/activateStatus/" + id,
success: function (data) {
oTable.ajax.reload();
}
});
});
$(document).on('click', '.statusupdate1', function() {
var id = $(this).attr("id");
$.ajax({
url: "<?= base_url() ?>Admin/deactivateStatus/" + id,
success: function (data) {
oTable.ajax.reload();
}
});
});
I don't know where is the error why the buttons are not working.
It may be that you are missing the semicolon (;) after your base_url() call. In the AJAX section for both buttons, try changing <?= base_url() ?> to <?= base_url(); ?> and see if that solves the issue.
Hello guys I am new to AJAX and I'm developing DB list like CRUD and one of delete feature I used with AJAX actually it deletes record but only reflect after manual refresh not simultaneously so I need your help with AJAX.
List.php
<?php
include "db.php";
$sql = "SELECT * FROM users";
$query = $conn->query($sql);
?>
<script src="https://code.jquery.com/jquery-3.2.1.js" integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE="
crossorigin="anonymous"></script>
<script>
$(document).ready(function() {
$(document).on('click','#btn_delete',function(){
var uid = $(this).data("id1");
if(confirm('Are You Sure To Delete '+uid+' ?'))
{
$.ajax({
url: 'delete.php',
type: 'POST',
data: 'uid='+uid,
dataType: 'text',
success:function(data){
//alert(data);
}
});
}
});
});
</script>
<table border="1">
<tr>
<th>ID</th>
<th>Name</th>
<th>Contact</th>
<th>Skills</th>
<th>Edit</th>
</tr>
<?php
while($row = $query->fetch_object()){
//echo $row->name."<br>";
?>
<tr>
<td><?php echo $row->uid; ?></td>
<td><?php echo $row->name; ?></td>
<td><?php echo $row->contact; ?></td>
<td><?php echo $row->skills; ?></td>
<td id="edit">
<button calss="delete_btn" type="submit" id="btn_delete" name="delete" value="DELETE" data-id1="<?php echo $row->uid; ?>">DELETE</button>
<!-- <a href="delete.php" data-id2="<?php echo $row->uid; ?>" id="delete" alt="DELETE" >Delete</a> -->
Update
</td>
</tr>
<?php } ?>
</table>
Whenever I press Delete button it actually delete record on first hand from database that mean ajax works but simultaneously table is not refresh, deleted entry remain in table till next refresh.
Delete.php
<?php
include "db.php";
$uid = $_POST['uid'];
$sql = "DELETE FROM users WHERE uid='".$uid."'";
$conn->query($sql);
$conn->close();
?>
<p id="check">Deleted</p>
I see some issues with this code and currently only partial or round about answers so I thought I would lend a hand :)
The dynamic rows you create inside your while loop have buttons that have a static ID across all delete buttons.
This could cause problems because ID's are supposed to be unique.
You misspelled class.
I removed the ID, corrected the spelling on class, and updated the JavaScript to use the button class instead of ID.
Since the button is in the table we can use it as a marker for which row to remove from the table.
This can be accomplished by calling closest: var tr = $(this).closest("tr");
Once the AJAX succeeds we can now remove that row: tr.remove();
The jQuery AJAX function has gone through some changes recently as the success callback was deprecated and then removed in 3.0 see Deprecation Notice.
This would cause your success call to not fire as it doesn't exist in 3.0 and from your question we can see that your using version 3.2.1.
I have replaced the callback with the updated call.
Here is the solution I came up with:
<script>
$(document).ready(function() {
$(document).on("click", ".btn_delete", function(){
var tr = $(this).closest("tr");
var uid = $(this).data("id1");
if (confirm("Are You Sure To Delete " + uid + "?")) {
$.ajax({
url: "delete.php",
type: "POST",
data: "uid=" + uid,
dataType: "text",
done: function(data){
tr.remove();
}
});
}
});
});
</script>
<table border="1">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Contact</th>
<th>Skills</th>
<th>Edit</th>
</tr>
</thead>
<tbody>
<?php
while($row = $query->fetch_object()){
//echo $row->name."<br>";
?>
<tr>
<td><?php echo $row->uid; ?></td>
<td><?php echo $row->name; ?></td>
<td><?php echo $row->contact; ?></td>
<td><?php echo $row->skills; ?></td>
<td id="edit">
<button class="delete_btn" type="submit" name="delete"
value="DELETE" data-id1="<?php echo $row->uid; ?>">DELETE</button>
<a href="form.php?link=<?php echo $row->uid; ?>"
value="<?php echo $row->uid; ?>" alt="UPDATE">Update</a>
</td>
</tr>
</tbody>
<?php } ?>
</table>
On another note the PHP call to your MySql in Delete.php is susceptible to injection attacks here is some documentation on that in PHP < 5.5 see Example 5.50 An example SQL Injection Attack and in PHP >= 5.5 as the function was deprecated in 5.5.
You can delete the element in the success callback function like so:
$.ajax({
url: 'delete.php',
type: 'POST',
data: 'uid='+uid,
dataType: 'text',
success:function(data){
//if using jquery
//$('tr').filter(':has(td:first:contains(' + uid + '))').remove();
$('tr').filter(function() {
return $(this).find('td:first').text() == uid;
}).remove();
//if not
var table = document.getElementsByTagName('table')[0];
var rows = table.getElementsByTagName('tr');
for (var i = 0; i < rows.length; i++) {
if (rows[i].children[0].textContent == uid) {
table.removeChild(rows[i]);
}
}
}
});
You can use this:
$.ajax({
url: 'delete.php',
type: 'POST',
data: 'uid='+uid,
dataType: 'text',
success:function(data){
window.location.href = 'YOUR PAGE';
}
})
You can make the page to reload automatically after successful ajax call. Try This:
$.ajax({
url: 'delete.php',
type: 'POST',
data: 'uid='+uid,
dataType: 'text',
success:function(data){
location.reload();
}
})
I am loading a content into a #result div. In that content, there is a button.
After the contrnt was loaded with ajax, i cant click on that button, i dont get the alert. (the page doesnt see it? :))
<script type="text/javascript">
$(document).ready(function(e)
{
$('#printButton').hide();
$('#submitButton').click(function(e)
{
var kat = $('#kategoria').val();
$.ajax({
type: 'POST',
url: 'files/get_arlista_kategoria.php',
data: { kat: kat },
dataType: "html",
cache: false,
beforeSend: function(){
$('#preloaderImage2').show();
},
success: function(data)
{
var result = $.trim(data);
$('#result').html(result);
$('#printButton').show();
},
complete: function(){
$('#preloaderImage2').hide();
}
});
});
// This click doesnt work
$('#savePrices').click(function(e)
{
alert("Its oké");
});
});
</script>
How can i work with this button and the input after the ajax loaded it? I want to update the product prices.
And here is the php file, this generates the html content:
<?php
include_once("../../files/connect.php");
include_once("../../files/functions.php");
if(!empty($_POST))
{
$kategoria = mysqli_real_escape_string($kapcs, $_POST['kat']);
$sql = "SELECT termek_id, termek_nev, termek_akcio, termek_normal_ar, termek_akcios_ar, mertekegyseg_nev FROM termek
LEFT JOIN webshop_mertekegyseg ON webshop_mertekegyseg.mertekegyseg_id = termek.termek_egyseg
WHERE
termek_id IN (SELECT kat_kapcs_termek_id FROM `termek_katgoria_kapcsolo` WHERE kat_kapcs_kategoria_id IN ($kategoria) ) ORDER BY termek_nev ASC";
$get = mysqli_query($kapcs, $sql) or die(mysqli_error($kapcs));
$num = mysqli_num_rows($get);
if($num > 0 )
{
echo '<form method="post">';
echo '<table class="form manufacturer-seo-form table table-hover">';
echo '<thead style="font-weight:bold;">
<tr>
<td style="text-align: left;">ID</td>
<td class="left">Megnevezés</td>
<td style="text-align: left;">Egység</td>
<td>Bruttó ár</td>
<td>Akciós ár</td>
<td style="text-align: center;">Akciós</td>
</tr>
</thead>';
echo '<tbody>';
while($i = mysqli_fetch_assoc($get))
{
?>
<tr id="sor<?php echo html($i['termek_id']); ?>">
<td style="text-align: left;"><?php echo html($i['termek_id']); ?></td>
<td class="left"><a title="Megnyitás" style="color:#333;" target="_blank" href="termek-szerkesztes.php?id=<?php echo html($i['termek_id']); ?>"><?php echo html($i['termek_nev']); ?></a></td>
<td style="text-align: left;"><?php echo $i["mertekegyseg_nev"] ?></td>
<td><input type="text" name="normal_ar" value="<?php echo html($i['termek_normal_ar']); ?>" /></td>
<td><input type="text" name="akcios_ar" value="<?php echo html($i['termek_akcios_ar']); ?>" /></td>
<td style="text-align: center;">
<select name="termek_akcio" class="input input-select" style="padding:5px 10px">
<?php
$ertek = intval($i['termek_akcio']);
$values = array("1" => "Igen", "0" => "Nem");
foreach($values AS $k => $v)
{
$selected = $ertek == $k ? ' selected="selected"':'';
echo '<option ' . $selected . ' value="' . $k . '">' . $v . '</option>';
}
?>
</select>
</td>
</tr>
<?php
}
echo '</tbody>';
echo '</table>';
echo '<div class="text-center"><button class="btn saveButton" type="button" id="savePrices">Módosítások mentése</button></div>';
echo '</form>';
}
else
{
echo '<span style="display:block;margin:20px 0 20px 5px;"><b>A kiválasztott kategóriában nincsenek termékek.</b></span>';
}
}
?>
You assign the click event function before the element (button) actually exists. Therefore there is no element to bind the click event to. You can bind the click event to the document instead:
$(document).on('click', '#savePrices', function(e) {
alert(...);
});
Completely untested though ...
The onclick assignment ($('#savePrices').click(...)) is run once when the web page has loaded. But your pricing buttons are not there yet.
Run it again when the AJAX .success is executed:
<script type="text/javascript">
$(document).ready(function(e)
{
$('#printButton').hide();
$('#submitButton').click(function(e)
{
var kat = $('#kategoria').val();
$.ajax({
type: 'POST',
url: 'files/get_arlista_kategoria.php',
data: { kat: kat },
dataType: "html",
cache: false,
beforeSend: function(){
$('#preloaderImage2').show();
},
success: function(data)
{
var result = $.trim(data);
$('#result').html(result);
// assign onclick
$('#savePrices').click(function(e)
{
alert("Its oké");
});
$('#printButton').show();
},
complete: function(){
$('#preloaderImage2').hide();
}
});
});
});
</script>
How Delete row in table html using ajax and php,
I need delete row in html table select row and click button delete make delete using ajax Currentally can make delete without ajax but I need delete row and stay on page without make submit on other page
code javaScript
function getDelete()
{
$.ajax({
type:"post",
//dataType:"json",
data:"id="+id,
url:"delete_address.php?id=$id", // url of php page where you are writing the query
success:function(json)
{
},
error:function(){
}
});
}
code html and php
<?php
$resualt=mssql_query("SELECT * FROM Address where user_id='$UserId' ") ;
echo "<table border='1' class='imagetable' id='imagetable'
width='400px' >\n";
echo '<thead>'.'<tr>';
echo '<th>Street</th>'.'<th>Quarter</th>'.
'<th>From</th>'.'<th>To</th>'.'<th>Notes</th>';
echo '</tr>'.'</thead>';
echo '<tbody>';
while ($row = mssql_fetch_assoc($resualt)) {
$fromDate=$row['from_date'];
$toDate=$row['to_date'];
echo " <tr onClick='myPopup($row[id])'".
( $_GET['id'] == $row['id'] ?
"style='background-color: green;'":"").">\n"."<td >
{$row['street']} </td>\n".
"<td>{$row['quarter']}</td>\n"."<td>$fdate2</td>\n".
"<td>$tdate2</td>\n"."<td>{$row['other_info']}</td>\n";
}
echo '</tbody>';
echo "</table>\n";
?>
<?php
echo"<a class='button-link' onClick='getDelete()'>delete</a>";
?>
code sql query
<?php
$idEmploye=$_GET['id'];
$userId=$_GET['user_id'];
$db_host = 'MOHAMMAD-PC\SQL2005';
$db_username = 'sa';
$db_password = '123321';
$db_name = 'db_test';
mssql_connect($db_host, $db_username, $db_password);
mssql_select_db($db_name);
mssql_query("DELETE FROM Address
WHERE id='$idEmploye' ; ") or die(mssql_error()) ;
echo '<script language="javascript">';
echo 'alert("successfully deleted ")';
echo '</script>';
echo "<script>setTimeout(\"location.href ='address.php';\",10); </script>";
?>
Any Help Very Thanks
Try this solution
HTML:
<table>
<tr>
<td>Username</td>
<td>Email</td>
<td>Action</td>
</tr>
<tr>
<td>TheHalfheart</td>
<td>TheHalfheart#gmail.com</td>
<td>
<input type="button" class="delete-btn" data-id="1" value="Delete"/>
</td>
</tr>
<tr>
<td>freetuts.net</td>
<td>freetuts.net#gmail.com</td>
<td>
<input type="button" class="delete-btn" data-id="2" value="Delete"/>
</td>
</tr>
</table>
We have two button's properties call data-id and class delete-btn
AJAX jQuery:
<script language="javascript">
$(document).ready(function(){
$('.delete-btn').click(function(){
// Confirm
if ( ! confirm('Are you sure want to delete this row?')){
return false;
}
// id need to delete
var id = $(this).attr('data-id');
// Current button
var obj = this;
// Delete by ajax request
$.ajax({
type : "post",
dataType : "text",
data : {
id : id
},
success : function(result){
result = $.trim(result);
if (result == 'OK'){
// Remove HTML row
$(obj).parent().parent().remove();
}
else{
alert('request fails');
}
}
});
});
});
</script>
In PHP:
Get the ID and delete
Reponse OK if success
Sorry i'm learning English, please fix if its bad
I wrote the code to delete MySQL table rows. But when I click on delete icon, nothing happens. Could someone please tell me what's left in my code?
<?php
include_once 'include/DatabaseConnector.php';
$query1="SELECT * FROM MyTable;";
$result1=DatabaseConnector::ExecuteQueryArray($query1);
?>
<script type="text/javascript">
function deleteRow(tableName,colName,id){
$.ajax({
type: "POST",
url: "delete.php",
data: "tableName=tableName&colName=colName&id=id",
success: function(msg){
alert( "Row has been updated: " + msg );
}
});
}
</script>
<table id="newspaper-b" border="0" cellspacing="2" cellpadding="2" width = "100%">
<thead>
<tr>
<th scope="col">Opr</th>
<th scope="col">Flt Num</th>
<th scope="col">From</th>
<th scope="col"></th>
</tr>
</thead>
<tbody>
<?php foreach ($result1 as $row):?>
<tr>
<td><?php echo $row['airlineName'];?></td>
<td><?php echo $row['flightNum'];?></td> <td><?php echo $row['from'];?></td>
<td>
<div title='Delete' onclick='deleteRow(<?php echo 'flightschedule','flightNum',$row['flightNum']; ?>)'>
<img src='images/delete.png' alt='Delete' />
</div>
</td>
</tr>
<?php endforeach;?>
</tbody>
delete.php
<?php
/* Database connection */
include_once 'include/DatabaseConnector.php';
if(isset($_POST['tableName']) && isset($_POST['colName']) && isset($_POST['id'])){
$tableName = $_POST['tableName'];
$colName = $_POST['colName'];
$id = $_POST['id'];
$sql = 'DELETE FROM '.$tableName.' WHERE '.$colName.' ="'.$id.'"';
mysql_query($sql);
} else {
echo '0';
}
?>
have you checked your PHP log to see if there is an error?
what is Ajax.Request ? if you are using the prototype library, where is it included in your HTML code?
finally, are you sure your PHP code is called? (check using for instance the Web Developper Tools in Chrome browser, "Requests" tab)
You have an error on this line
<div title='Delete' onclick='deleteRow(<?php echo 'flightschedule','flightNum',$row['flightNum']; ?>)'>
this will print
<div title='Delete' onclick='deleteRow(flightscheduleflightNumid)'>
You have to change it to
<div title='Delete' onclick='deleteRow("flightschedule","flightNum",<?php $row['flightNum']; ?>)'>
to work.
Best wishes
Update: For the above code to work also add
<script src="js/jquery.js" type="text/javascript" ></script>
or load it from the internet
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.js"></script>
to include Jquery at the header of html. I have tested its ok now.
you send not your data to the delete.php file, because in the attribute dated you seize them badly. Here is this code I have just tested him(it) and that seems to work.
data: "tableName="+tableName+"&colName="+colName+"&id="+id+"",
function deleteRow(tableName,colName,id){
$.ajax({
type: "POST",
url: "delete.php",
data: "tableName="+tableName+"&colName="+colName+"&id="+id+"",
success: function(msg){
alert( "Row has been updated: " + msg );
}
});
}