I have an HTML table generated by PHP querying from MySQL table.
<table>
<tr>
<th>Sl</th>
<th>ID</th>
<th>Article Name</th>
<th>Publish Status</th>
</tr>
<?php
$i = 1;
foreach ($obj->showAllFromTable('pattern') as $pattern) {
extract($pattern);
?>
<tr>
<td><?php echo $i++; ?></td>
<td><?php echo $id; ?></td>
<td><?php echo $pattern_name; ?></td>
<td id="publish_<?php echo $id; ?>" class="status_pattern">
<?php echo $publish; ?>
</td>
</tr>
<?php
}
?>
</table>
I want to change the status of any article by clicking on the 'publish' cell of the corresponding article row. I am trying to use ajax method of jquery for this purpose as shown in the following:
<script type="text/javascript">
$(document).ready(function(){
$('.status_pattern').click(function(){
var thisid = $(this).attr('id');
$.ajax({
url: "status_change_pattern.php",
data: {
id: thisid
},
success: function (response) {
alert(response);
}
});
});
});
</script>
In the "success" block, instead of "alert", I want to create a functionality to change the text of the specific cell which I clicked. The "status_change_pattern.php" has just a text "Hey Hey".
Can anyone help? Please.
Thanks.
You have to use closure to preserve the id.
<script type="text/javascript">
$(document).ready(function(){
$('.status_pattern').click(function(){
var thisid = $(this).attr('id');
$.ajax({
url: "status_change_pattern.php",
data: {
id: thisid
},
success: function (id) {
return function (response) {
$("#" + id).html(response);
}
}(thisid)
});
});
});
</script>
You need to write,
success: function (response) {
$(thisid).html(response);
}
Here in response, you need to get new status.
The solution provided by SajithNair works. Thanks to SajithNair. But it can also be done without using closure. As shown below:
$('.status_pattern').click(function() {
var thisid = $(this).attr('id');
$.ajax({
url : "status_change_pattern.php",
data : {
id : thisid
},
success : function(response) {
$('#' + thisid).html(response);
}
});
});
Thanks
Related
I'm not looking to add to / append an existing table. My table is empty until results are returned via AJAX. I'm trying to sort my tables data via the javascript plugin, tablesorter.js.
I have sorted my table so It's split between header and body. I can't seem to get the table rows to change though
My Code for the AJAX is;
<script>
$(document).ready(function()
{
$("#results").tablesorter();
}
);
</script>
<script>
$(document).ready(function(){
$.datepicker.setDefaults({
dateFormat: 'yy-mm-dd'
});
$(function(){
$("#to_date").datepicker();
});
var to_date = $('#to_date').val();
$( "#genre" ).val();
{
var value = $(this).val();
$( "#price" ).val();
{
var value = $(this).val();
$('#filter').click(function(){
var to_date = $('#to_date').val();
var request = $("#genre").val();
var request1 = $("#price").val();
var data = 'to_date'+'request'+'request1';
if(to_date != '' )
{
$.ajax({
url:"filter.php",
method:"POST",
data: { to_date:to_date, request:request,request1:request1 },
success:function(data)
{
$('#results').html(data);
$('#results').trigger("update");
}
});
}
else
{
alert("Please Select Date");
}
});
};
};
});
</script>
and my code for the html / PHP is;
<table id="results" class="tablesorter">
<thead>
<tr>
<th>Event</th>
<th>Venue</th>
<th>Genre</th>
<th>Date</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<?php
while($row = mysqli_fetch_array($result))
{
?>
<tr>
<td><?php echo $row["event_name"]; ?></td>
<td><?php echo $row["venue_name"]; ?></td>
<td><?php echo $row["genre"]; ?></td>
<td><?php echo $row["event_date"]; ?></td>
</tr>
<?php
}
?>
</tbody>
</table>
you never actually called to the plugin:
$("results").tablesorter()
Everytime you get your data updated you should make a all to the tablesorters update trigger so it gets its references updated.
success:function(data)
{
$('#results').html(data);
$('#results').trigger("update");
}
that should do the trick
<?php
while ($row = mysqli_fetch_array($query,MYSQLI_BOTH))
{
$id= $_POST['tran_no'];;
?>
<tbody>
<tr id=<?php echo $row['trans_no']?>>
<td><?php echo $row['trans_no']?></td>
<td><?php echo $row['obj_code']?></td>
<td><?php echo $row['div_no']?></td>
<td><?php echo $row['check_no']?></td>
<td><?php echo $row['payee']?></td>
<td><?php echo $row['payment']?></td>
<td><?php echo $row['add']?></td>
<td><?php echo $row['amount']?></td>
<td><?php echo $row['amountw']?></td>
<td>
<img src="image/remove.png">
</td>
</tr>
<?php
}
?>
</tbody>
</table>
</div>
<script src="jquery.js"></script>
<script type="text/javascript">
$(function() {
$(".delete").click(function(){
var element = $(this);
var del_id = element.attr("trans_no");
var info = 'trans_no=' + del_id;
if(confirm("Are you sure you want to delete this?"))
{
$.ajax({
type: "POST",
url: "delete.php",
data: info,
success: function(){
}
});
$(this).parents(".show").animate({ backgroundColor: "#003" }, "slow")
.animate({ opacity: "hide" }, "slow");
}
return false;
});
});
</script>
My problem is the ajax code doesnt seem to delete the row i dont know if the ajax code is executed or not. help would be much need, and please give me an insight as to what is the problem with my code or if i have to add something. heres the delete.php
<?php
$con = mysqli_connect("localhost","root"," ","dole") or die("Could not connect database");
if($_POST['trans_no'])
{
$id=$_POST['trans_no'];
$delete = "DELETE FROM table_no WHERE trans_no = '$id'";
$res=mysqli_query($con,$delete);
}
?>
OPTION 1:
You are assigning id from database to id attribute and in AJAX, reading trans_no.
trans_no attribute is not set for the delete link.
That is why you are not getting it.
Change your HTML to
<img src="image/remove.png">
To make it HTML5 Compliant:
<img src="image/remove.png">
And change JS:
var del_id = element.attr("data-id");
OPTION 2
Just change the line:
var del_id = element.attr("trans_no");
To
var del_id = element.attr("id");
And use your existing code.
It will work.
Try the below code,
$(".delete").click(function(){
var element = $(this);
var del_id = this.id;// use this.id as your database id related to element id
var info = {trans_no : del_id};
if(confirm("Are you sure you want to delete this?")){
$.ajax({
type: "POST",
url: "delete.php",
data: info,
success: function(data){
if(data=='success'){
// hide only in case of successful deltion
element.parents(".show").animate({ backgroundColor: "#003" }, "slow")
.animate({ opacity: "hide" }, "slow");
} else {
alert('Error while deleting');
}
}
});
}
return false;
});
And in PHP return success or error like,
<?php
$con = mysqli_connect("localhost","root"," ","dole") or die("Could not connect database");
$status='error';
if(isset($_POST['trans_no']) && $_POST['trans_no']){
$id=$_POST['trans_no'];
$delete = "DELETE FROM table_no WHERE trans_no = '$id'";
$res=mysqli_query($con,$delete);
if($res){// only success in case of deleted.
$status='success';
}
}
echo $status;
?>
Try this:
$(function() {
$(".delete").click(function(){
var element = $(this);
var transNoVar = element.attr('id');
if(confirm("Are you sure you want to delete this?"))
{
$.ajax({
type: "POST",
url: "delete.php",
data: {
trans_no: transNoVar
},
success: function(data){
// delete.php return 1 on success 0 otherwise, check it here
if(data=='1') {
// on success hide the tr
// add class="show" to the tr
$(this).parents(".show").animate({ backgroundColor: "#003" }, "slow")
.animate({ opacity: "hide" }, "slow");
} else {
alert('Error deleting your record');
}
}
});
}
return false;
});
});
There is a div element :
...
<div id="liste_secteurs"></div>
...
<script type="text/javascript">
$(document).ready(function() {
rechercheSecteursEtProduits(0); // setting the div's content
$('#btnSupprimer').click(function() { // btnSupprimer = button generated from an ajax called inside previous function "rechercheSecteursEtProduits"
if ($(':checkbox[id^="prod_"]:checked').length > 0) {
var msg = "Do you want to remove these records ?";
if (confirm(msg)) {
$(':checkbox[id^="prod_"]:checked').each(function(){
var type = "",id="";
if($(this).val() == "") { // delete secteur
type = "secteur";
var tabIdx = $(this).attr("id").substr(5);
id = $("#secteur_"+tabIdx).val();
} else { // delete produit
type = "produit";
id = $(this).val();
}
$.ajax({
data: "type="+type+"&id="+id,
type: "POST",
url: "<?php echo HTTP_AJAX ?>service/SupprimerSecteursProduitsUserAjax.php", // deleting database row
async: false
});
});
rechercheSecteursEtProduits(0); // this causes the bug : the "delete" button does not work anymore after this code is called !
}
}
});
});
function rechercheSecteursEtProduits(pn){
var user = "<?php echo $_SESSION[CODE_USER]; ?>";
var html = $.ajax({
data: "id_user="+user,
type: "POST",
url: "<?php echo HTTP_AJAX ?>service/ListerProduitsUserParSecteursAjax.php?pn=" + pn,
async: false
}).responseText;
$('#liste_secteurs').html(html); // this is the div element
}
</script>
Code of ListerProduitsUserParSecteursAjax.php :
<?php
... // getting database data
?>
<p>Total : <?php echo $nr; ?></p>
<div><img src="<?php echo HTTP_ICON.'plus.png'; ?>" /></div>
<?php echo $paginationDisplay; ?>
<table id="table" class="data display " >
<thead style="background-color:#CCC">
<tr>
<th><?php echo _getText("service.produit.form.secteur_activite");?></th>
<th><?php echo _getText("service.produit.form.titre");?></th>
<th></th>
<th><?php if($data["secteur"]["cnt"] > 0){ ?><input type="checkbox" id="check_all"><?php }?></th>
</tr>
</thead>
<tbody style="background-color:#FFF">
<?php
if($data["secteur"]["cnt"] > 0){
for($i=0;$i<$data["secteur"]["cnt"];$i++){?>
<tr class="odd gradeX">
<td><?php echo $data["secteur"][$i]["secta_lib_fr"] ?></td>
<td><?php echo $data["secteur"][$i]["produit_lib"] ?></td>
<td align="center" style="vertical-align:middle"><img src="<?php echo HTTP_ICON.'edit.png'; ?>" alt="<?php echo _getText('main.btn.modifier'); ?>" style="height:10px;width:10px;" /></td>
<td align="center" style="vertical-align:middle"><input type="checkbox" id="prod_<?php echo $i; ?>" value="<?php echo $data['secteur'][$i]['id_user_produit']; ?>"><input type="hidden" id="secteur_<?php echo $i; ?>" value="<?php echo $data['secteur'][$i]['id_user_secteur']; ?>"></td>
</tr>
<?php } ?>
<?php
}
else{
?>
<tr class="odd gradeX">
<td colspan="4" align="center"><b><?php echo _getText('main.liste.no_data'); ?></b></td>
</tr>
<?php }?>
</tbody>
</table>
<?php if($data["secteur"]["cnt"] > 0){ ?>
<div align="right"><input name="btnSupprimer" id="btnSupprimer" type="button" value="<?php echo _getText("main.btn.delete"); ?>" class="btn btn-blue"/></div>
<?php } ?>
<?php echo $paginationDisplay; ?>
When the page loads for the first time then the delete button works fine : the selected rows are deleted , and the list reappears accordingly to new database data. But later when I want to delete other rows then the alert does not show when I check some checkboxes and clicking the delete button !
So what is wrong in my approach ?
From what I am reading you are having problems with the row that are added from the database.
What could be the problem is when you execute this peace of code:
$('#btnSupprimer').click(function() { // btnSupprimer = button generated from an ajax called inside previous function "rechercheSecteursEtProduits"
When you call the $.click() function you add a event to all the existing DOM object that have a id of 'btnSupprimer', however this doesn't update if you add a new DOM object. So what you should do is call this function every time you add a new row. you would get something like this:
function rechercheSecteursEtProduits(pn){
var user = "<?php echo $_SESSION[CODE_USER]; ?>";
var html = $.ajax({
data: "id_user="+user,
type: "POST",
url: "<?php echo HTTP_AJAX ?>service/ListerProduitsUserParSecteursAjax.php?pn=" + pn,
async: false
}).responseText;
$('#liste_secteurs').html(html);
$('#btnSupprimer').click(addClickHandler()); // this is the div element
}
function addClickHandler(){
if ($(':checkbox[id^="prod_"]:checked').length > 0) {
var msg = "Do you want to remove these records ?";
if (confirm(msg)) {
$(':checkbox[id^="prod_"]:checked').each(function(){
var type = "",id="";
if($(this).val() == "") { // delete secteur
type = "secteur";
var tabIdx = $(this).attr("id").substr(5);
id = $("#secteur_"+tabIdx).val();
} else { // delete produit
type = "produit";
id = $(this).val();
}
$.ajax({
data: "type="+type+"&id="+id,
type: "POST",
url: "<?php echo HTTP_AJAX ?>service/SupprimerSecteursProduitsUserAjax.php", // deleting database row
async: false
});
});
rechercheSecteursEtProduits(0); // this causes the bug : the "delete" button does not work anymore after this code is called !
}
}
}
I hope it helps
Try using on instead of click as below
$('#btnSupprimer').on("click","#liste_secteurs",function() { // btnSupprimer = button generated from an ajax called inside previous function "rechercheSecteursEtProduits"
if ($(':checkbox[id^="prod_"]:checked').length > 0) {
var msg = "Do you want to remove these records ?";
if (confirm(msg)) {
$(':checkbox[id^="prod_"]:checked').each(function(){
var type = "",id="";
if($(this).val() == "") { // delete secteur
type = "secteur";
var tabIdx = $(this).attr("id").substr(5);
id = $("#secteur_"+tabIdx).val();
} else { // delete produit
type = "produit";
id = $(this).val();
}
$.ajax({
data: "type="+type+"&id="+id,
type: "POST",
url: "<?php echo HTTP_AJAX ?>service/SupprimerSecteursProduitsUserAjax.php", // deleting database row
async: false
});
});
rechercheSecteursEtProduits(0); // this causes the bug : the "delete" button does not work anymore after this code is called !
}
}
});
Use the dynamic jquery selector instead of the regular 'click' event
$('#liste_secteurs').on('click', '#btnSupprimer', function() {});
// $("container").on("event", "button", function() {});
As from Caveman's answer I made some updates :
function rechercheSecteursEtProduits(pn) {
var user = "<?php echo $_SESSION[CODE_USER]; ?>";
var html = $.ajax({
data: "id_usermer="+user,
type: "POST",
url: "<?php echo HTTP_AJAX ?>service/ListerProduitsUserParSecteursAjax.php?pn=" + pn,
async: false
}).responseText;
$('#liste_secteurs').html(html);
$('#btnSupprimer').on('click',function(){
if ($(':checkbox[id^="prod_"]:checked').length > 0) {
if (confirm("Do you want to remove these records ?")) {
$(':checkbox[id^="prod_"]:checked').each(function(){
var type = "",id="";
if($(this).val() == "") { // delete secteur
type = "secteur";
var tabIdx = $(this).attr("id").substr(5);
id = $("#secteur_"+tabIdx).val();
} else { // delete produit
type = "produit";
id = $(this).val();
}
$.ajax({
data: "type="+type+"&id="+id,
type: "POST",
url: "<?php echo HTTP_AJAX ?>service/SupprimerSecteursProduitsUserAjax.php", // deleting database row
async: false
});
});
rechercheSecteursEtProduits(0);
}
}
});
}
And it works !
My function jQuery include on my head html
$(function() {
$(".deletePage").click(function() {
var pageId = $(this).attr("id");
$.ajax({
type: "post",
url: "delete_page.php",
cache: false,
data:'id=' + pageId,
success: function(response){
try{
if(response=='true'){
parent.slideUp('slow', function() {$(this).remove();});
}
}catch(e) {
alert('Exception while request..');
}
},
error: function(){
alert('Error while request..');
}
});
}
}
And my html with listPage
<table class="table table-hover">
<thead>
<tr>
<td><strong>title page</strong></td>
<td><strong>URL</strong></td>
<td><strong>Edit</strong></td>
<td><strong>Delete</strong></td>
</tr>
</thead>
<tbody>
<?php
while($row_Q = mysql_fetch_array($sql_Q)){
?>
<tr>
<td><?php echo $row_Q["title"]; ?></td>
<td><?php echo $row_Q["permalink"]; ?></td>
<td>
</td>
<td>
<button type="button" class="btn btn-danger">
<a class="deletePage" href="#">Delete</a>
</button>
</td>
</tr>
<?php
}
?>
</tbody>
</table>
Why not working jQuery and not delete selected page?Any help me please?I want that click on the button "DELETE" the row its delete without going other page
thank you
You have an error. You're trying to get the page ID, but it doesn't exist in your HTML code.
Add the ID to your <a> and you're set.
I fix the problem :)
You said to me that add the Id to me and yes this is a one problem but I have more problems.
This is my new function in jQuery
$(function() {
$(".deletePage").click(function() {
var pageId = $(this).attr("id");
var parent = $(this).parent();
if(confirm("Delete me?")){
$.ajax({
type: "post",
url: "delete_page.php",
cache: false,
data: 'id=' + pageId,
dataType: "text",
success: function(response){
location.reload();
try{
if(response=='true'){
parent.slideUp('slow', function() {$(this).remove();});
}
}catch(e) {
alert('Exception while request..');
}
},
error: function(){
alert('Error while request..');
}
});
}
return false;
});
});
I'm trying to delete users from the database using AJAX and Code Igniter. When I click the delete link, the user gets deleted but the page gets redirected and success message is displayed. AJAX does not seem to work in my code.
Here's HTML:
<table class="table table-hover">
<thead>
<tr>
<th>#</th>
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
<th>Username</th>
<th>Password</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<?php foreach($users as $u){?>
<tr>
<td><?php echo $u['id']; ?></td>
<td><?php echo $u['firstname']; ?></td>
<td><?php echo $u['lastname']; ?></td>
<td><?php echo $u['email']; ?></td>
<td><?php echo $u['username']; ?></td>
<td><?php echo $u['password']; ?></td>
<td>
<a href="#" >Edit</a> |
<?php $id=$u['id'];?>
Delete
</td>
<?php }?>
</tr>
</tbody>
</table>
and here's AJAX:
$(document).ready(function(){
$(".delete").click(function(){
alert("Delete?");
var href = $(this).attr("href");
var btn = this;
$.ajax({
type: "GET",
url: href,
success: function(response) {
if (response == "Success")
{
$(btn).closest('tr').fadeOut("slow");
}
else
{
alert("Error");
}
}
});
})
});
and lastly the controller function to delete the user in Codeigniter
public function delete($id)//for deleting the user
{
$this->load->model('Users_m');
$delete=$this->Users_m->delete_user($id);
if($delete)
{
echo "Success";
}
else
{
echo "Error";
}
}
Where am I making the mistake?
Just to expand on the correct answers already given here.
Basically, your JS code should look like:
$(document).ready(function(){
$(".delete").click(function(event){
alert("Delete?");
var href = $(this).attr("href")
var btn = this;
$.ajax({
type: "GET",
url: href,
success: function(response) {
if (response == "Success")
{
$(btn).closest('tr').fadeOut("slow");
}
else
{
alert("Error");
}
}
});
event.preventDefault();
})
});
The event.preventDefault() part is important here. As it prevents the browser from taking the default action it takes if you click on an element.
In the case of a link, that would be redirecting you to the url that is defined in the href parameter. Which is what you see happening.
Your manually defined event is always triggered first, so the ajax request is indeed started, but right after that your event handler, the browser starts handling the default action, breaks off the ajax request, and navigates to the clicked link.
Make sure you are setting the correct object to the 'btn' var:
var btn = $(this);
See if this is the issue!
by the way you are missing a semicolon in:
var href = $(this).attr("href")
the default action of the event should not be triggered.
For this use event.preventDefault()
$(".delete").click(function(e){
e.preventDefault();
...
You are not preventing the default behavior of the anchor so it will redirect you and make the ajax request
$(document).ready(function(){
$(".delete").click(function(e){
alert("Delete?");
e.preventDefault();
var href = $(this).attr("href");
var btn = this;
$.ajax({
type: "GET",
url: href,
success: function(response) {
if (response == "Success")
{
$(btn).closest('tr').fadeOut("slow");
}
else
{
alert("Error");
}
}
});
})
});
I hope this can help :)
First you change the href attribute another attribute like name or value because first time it loads and another time it stores the value in href and after that write this for refreshing page
window.reload('true');
this will surely help you