I am using AJAX to send data to server and update the current page with no reloading. I have this script:
$.ajax
({
url: 'insert.php',
type: 'POST',
data: {data1: emp, data2: pos, data3: sal},
dataType: "json",
success:function(data)
{
var emp_n = data.emp_name;
var btn = '<button type="Button" id="del" name="del" class="btn btn-danger">Delete</button></a>';
$("#before_tr").before("<tr><td>"+data.emp_name+"</td><td>"+data.position+"</td><td>"+data.salary+"</td><td>"+btn+"</td></tr>");
},
As you see, I have a delete button that should be added too to the same row. But this button won't be active until I refresh the page. What I want is to append action like this PHP Based code for a delete button of each 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>
<td><button type="Button" id="del" name="del" class="btn btn-danger">Delete</button>
</tr>
<?php } ?>
What I've tried is the following:
$.ajax
({
url: 'insert_with_ajax.php', //Sending variable emp, pos, and sal, into this url
type: 'POST', //I will get variable and use them inside my PHP code using $_POST['emp']
data: {data1: emp, data2: pos, data3: sal},//Now we can use $_POST[data1];
dataType: "json", //JSON or HTML
success:function(arr)
{
//if(data=="success")
//{
//alert("Data added");
var emp_n = arr.emp_name;
var btn = 'Delete</button>';
$("#before_tr").before("<tr><td>"+arr.emp_name+"</td><td>"+arr.position+"</td><td>"+arr.salary+"</td><td>"+btn+"</td></tr>");
$("#emp_name").val("");
$("#position").val("");
$("#salary").val("");
//}
},
Where I added this line <a href="delete_id.php?id="'+emp_n+' to the following:
var btn = 'Delete</button>';
When I click on delete button of the last one added using AJAX the page go to delete_id but the link is like this:
delete_id.php?id=
id is equal to empty.
So, What I am working on is like when we add a status on Facebook and you delete it directly with no need for reloading the page. I am trying and I hope that someone could help.
Check your code once again:
'<a href="delete_id.php?id="'+emp_n+'>'
^ - see? you have a closing " here.
This means that no values will be added to your href attribute as it's already closed.
Proper code is:
'<a href="delete_id.php?id='+emp_n+'">'
^ -see? closing " moved after emp_n
Related
I have a list with information from a database, next to each record there is a button to edit the record data. The problem is when I try to send the id of the registry I want to edit, I have always received the same output, the simple word: Array.
This is the table:
<th><?php echo $row_usuario["id_employee"]; ?></th>
<td><?php echo $row_usuario["nome"]; ?></td>
<td><?php echo $row_usuario["email"]; ?></td>
<td>
<a href="#Edit" id="custId" data-toggle="modal" data-id=" '.$row_usuario['id_employee'].'">
<i class="material-icons" style="color:#2A6F46">edit</i>
</a>
</td>
The ajax:
$(document).ready(function(){
$('#Edit').on('show.bs.modal', function (e) {
var rowid = $(e.relatedTarget).data('id');
$.ajax({
type : 'post',
url : 'list_emp.php',
data : 'rowid='+ rowid,
success : function(data){
$('.fetched-data').html(data);//Show fetched data from database
}
});
});
});
Query part:
//database connection include before this
if($_POST['rowid']) {
$id = $_POST['rowid'];
//here is the problem, i'm not receiving the real id, just the word "Array" and i can't run the query because this
}
Modal:
<div class="fetched-data">Here i want to show the form with the info to be edit</div>
Can someone help me find the error?
next to each record there is a button to edit the record data
so i think you need class instead of id on your edit button
so change your html to this:
<th><?php echo $row_usuario["id_employee"]; ?></th>
<td><?php echo $row_usuario["nome"]; ?></td>
<td><?php echo $row_usuario["email"]; ?></td>
<td>
<a href="#Edit" class="fancyEditButton" data-toggle="modal" data-id=" '.$row_usuario['id_employee'].'">
<i class="material-icons" style="color:#2A6F46">edit</i>
</a>
</td>
and on your ajax:
$(document).ready(function(){
$('.fancyEditButton').on('click', function (e) {
e.preventDefault();
var rowid = $(this).data('id');
$.ajax({
type : 'post',
url : 'list_emp.php',
data : 'rowid='+ rowid,
success : function(data){
$('.fetched-data').html(data);//Show fetched data from database
}
});
});
});
try this instead
$.ajax({
type : 'post',
url : 'list_emp.php',
data : {rowid: rowid}
success : function(data){
$('.fetched-data').html(data);//Show fetched data from database
}
});
Like here shown post ajax data to PHP and return data
well, here my code
From my index.php:
<a href="#" id="save" class="save" onclick='UpdateStatus("<?PHP echo $fgmembersite->UserFullName();?>","<?php echo $_GET['id'] ;?>")'> save</a>
User can save one information when he clicks on this link.
Then, my fuction UpdateStatuts
function UpdateStatus(member1,id1) { //
/* VALUES */
var member = member1;
var id = id1;
var statut = '1';
/* DATASTRING */
var dataString = 'member='+ member+'&id='+ id+'&statut='+ statut;
console.log ("SOMETHING HAPPENS");
$.ajax({
type: "POST",
url: "../../lib/tratement.php",
data: dataString,
success: function(){
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
console.log (dataString);
console.log ("AJAX DONE");
}
});
return false;
};
It works perfectly. But after users clicks on the first link, i want to display unsave instead save without reload the whole page.
In an another way, i want this
<a href="#" id="save" class="save" onclick='**RemoveStatus**("<?PHP echo $fgmembersite->UserFullName();?>","<?php echo $_GET['id'] ;?>")'> **Unsave**</a>
instead <a href="#" id="save" class="save" onclick='UpdateStatus("<?PHP echo $fgmembersite->UserFullName();?>","<?php echo $_GET['id'] ;?>")'> save</a>
Is it possible ?
Some strange problem occurred. I am trying to delete a record from a table by using AJAX but whenever I click the delete button it is sending the ID of the last row in the table each time instead of that specific ID which I want to delete to my delete-process.php page. Now I checked that the PHP page and codes are just working fine. When I did console.log(dataString) I got to see that no matter which Delete button I click I get the ID of the last field only.
Code
<table class="table table-hover table-striped">
<thead>
<th>ID</th>
<th>Name</th>
<th>Email</th>
<th>Phone</th>
<th>Date</th>
<th>Action</th>
</thead>
<tbody>
<?php while($si = $stmt->fetch()){ extract($si); ?>
<tr>
<td><?php echo $ct_id; ?></td>
<td><?php echo $ct_name; ?></td>
<td><?php echo $ct_email; ?></td>
<td><?php echo $ct_phone; ?></td>
<td><?php echo date('jS M, Y (h:i a)', strtotime($ct_date)); ?></td>
<td>
<form method="post" action="">
View
<input type="text" value="<?php echo $ct_id; ?>" class="ctid">
<input type="submit" value="Delete" class="btn btn-danger btn-fill delete">
</form>
</td>
</tr>
<?php } ?>
</tbody>
AJAX
$(document).ready(function() {
$(".delete").click(function() {
var dataString = {
id: $(".ctid").val()
};
console.log(dataString);
var $submit = $(this).parent().find('.delete');
$.confirm({
title: 'Confirm!',
content: 'Are you sure you want to delete this message?',
buttons: {
confirm: function () {
$.ajax({
type: "POST",
//dataType : "json",
url: "delete-process.php",
data: dataString,
cache: true,
beforeSend: function(){
$submit.val("Please wait...");
},
success: function(html){
$('.message').html(html);
if($('.message').find('#responseBox').hasClass('alert-success')){
$.alert(html);
setTimeout(function(){
window.location.replace("support.php<?php if(!empty($_GET['ids'])){ ?>?ids=<?php echo $_GET['ids']; } ?>");
},2000);
}
}
});
},
cancel: function(){}
}
});
return false;
});
});
I did not include PHP code because the error is detected in console.log(dataString) as every button clicked is sending the same ID. Please help.
$(".ctid") will return an array containing all of the elements with that class.
You are only interested in the sibling to the clicked button so you should use $(this).prev().
$(this) will reference the clicked button.
.prev() selects the immediately proceeding sibling.
$(".delete").click(function() {
var dataString = {
id: $(this).prev().val()
};
...
});
As you are creating the table rows using loop so the class ctid is repeated. so when you are accessing this like this id: $(".ctid").val(). It will return all the elements having class ctid. So change your script like this
var dataString = {
id: $(this).siblings('.ctid').val()
};
Of course it is selecting the same ctid since you don't distinguish between forms. You can distinguish like this:
var dataString = {
id: $(this).closest('form').find('.ctid').val()
};
"closest" navigates to the form and then find the ctid that is contained in the form.
When you do this:
$(".ctid").val()
Which matching element are you expecting? The code doesn't specify, and ".ctid" matches multiple elements. But since it can only return a single value, it's simply returning the last matching one. Essentially, you need to specify which matching element you want.
One way to do this is by navigating the DOM from the clicked button to the nearest matching element. Perhaps by navigating up to a single common parent element and then finding the target element therein. Something like this:
$(this).closest("form").find(".ctid").val()
Starting from the clicked element which raised the event (this), it navigates up to the containing <form> and then searches for the matching ".ctid" within that form. Then gets the value from only that element.
You can inspect to check each button value is getting unique or not
You can achieve that without using ajax use below code
Delete
Basically what I have is a lot of <a> tags which are queried from a database. They are displayed and when a user clicks on one of the tags then it fires an ajax function. Right now one button does the work of all the buttons.
The tags look like this:
<a value='<?php echo $setit ?>' class='button' setdata='<?php echo
$setit ?>'><?php echo $setit ?></a>
And the ajax function looks like this:
$(document).ready(function(){
$(".button").click(function(event){
var data1=$(this).data('setdata');
$.ajax({
url: "set_freq.php",
type: "POST",
data: {"set_freq":data1},
success: function(data){
data = JSON.stringify(data);
console.log(data);
}
});
});
});
I'm thinking that I need to make the button id-s unique so the function can only get the correct button value. Am I on the right track? How can it be done?
There is no need to make the ids of your buttons unique. You could simply use
$('.button').click(function(e) {/*ajax*/});
to query all buttons. Note that you have to query using a . (for class names) instead of a # (for ids). Inside of the function $(this) will always refer to the link that was clicked.
On the other hand your id's should be unique. If you do not mind that they change on every refresh, you might use uniqueid:
<a id="<?= uniqueid(); ?>" ... >
Else your database should have an unique index that you might use. But i think there is no reason to set an id at all since your JavaScript is fine without.
$("#button") targets an element with id="button" but you certainly want to target element with class="button" as seen in your HTML... So you should replace the # with a dot, just like in CSS. $(".button")
Also, you do not need to use ID for this, even if you have multiple buttons, the eventHandler receives this as the target element, so you'll always have access to the "current" data.
Also I think you have wrong format for data property.
The right is here:
<a value='<?= $setit ?>' class='button' data-set='<?= $setit ?>'><?= $setit ?></a>
Just change your a tag as follows.
<a class='button' data-setdata='<?php echo $setit ?>'><?php echo $setit ?></a>
Replace your tag :
<a value='<?php echo $setit ?>' class='button' setdata='<?php echo
$setit ?>'><?php echo $setit ?></a>
To:
<a class='button' id='setit'><?php echo $setit ?></a>
and replace your ajax function :
$(document).ready(function(){
$(".button").click(function(event){
var data1=$(this).data('setdata');
$.ajax({
url: "set_freq.php",
type: "POST",
data: {"set_freq":data1},
success: function(data){
data = JSON.stringify(data);
console.log(data);
}
});
});
});
To :
$(document).ready(function(){
$(".button").click(function(event){
var data1 = document.getElementById("setit").innerHTML
$.ajax({
url: "set_freq.php",
type: "POST",
data: {"set_freq":data1},
success: function(data){
data = JSON.stringify(data);
console.log(data);
}
});
});
});
why the code below doesn't do its job ?
I just need POST via javascript id content on click btn.
this code works properly in many other situations but not here that i'm using twitter bootstrap modal.
thanks.
<button id="<?php echo $id; ?>" class="btn btn-warning" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
<span class="glyphicon glyphicon-trash"></span> delete id
</button>
<script type="text/javascript">
//delete id
$(document).on('click','.btn-warning',function(){
var element = $(this);
var del_id = element.attr("id");
var info = 'id=' + del_id;
if(confirm("are you sure ?")){
$.ajax({
type: "POST",
url: "page.php",
data: info,
success: function(){ window.location.href = "/logout.php"; }
});
}
return false;
});
</script>
PHP
if($_POST['id']){
$id=$_POST['id'];
$id = mysql_real_escape_string($id);
...
info = {'id' : del_id };
Try to send data as array.
First, I think you should be using isset(variable) in the PHP:
if (isset($_POST['ID'])
{
...
Second, it doesn't work because you need to set the data and a key -> value array.
data: {id: "ID_NUMBER"}
Look over the examples on Jquery's site: https://api.jquery.com/jQuery.ajax/
I would also suggest using a unique ID property or a new/unique class proverty, and then using that to add the onClick event.