Php echo button onclick get id - php

I hava a dynamic list, loading from database in my php page.This list also have a delete button. When i click this button i need to get id of this button and delete from database that line with php code.
$dbh = new PDO("sqlite:database.sdb");
$sql ="SELECT * FROM clip";
foreach ($dbh->query($sql) as $row)
{
print 'Id: '. $row['id'] .'<br />';
echo '<input type="submit" id="'.$row['id'].'" value="delete" name="del">';
}
also this is my final code for button click;
$dbh->exec("delete clip where id='in here should be button id'");
How can i connect with this two code. Thanks already.

Given the level of your question I am assuming you are unfamiliar with jQuery and AJAX, but you should research both.
For a simple solution not using these you could do as follows:
Change the output to be <input type="button" id="'.$row['id'].'" value="Delete" onclick="do_delete(this.id)">;
Then you need a php script on the server side to handle the delete function, e.g. yourhandler.php
<?
//connect to DB here
if ($_POST['id']) {
$sql = "delete from clip where id=:delete_id";
$stmt = $dbh->prepare($sql);
$stmt->execute([':delete_id'=>$_POST['id']]);
}
?>
Then on the client side you need a form which submits when the button is clicked. Here is an example form code:
<form action="yourhandler.php" method="post" id="myform">
<!--Your PHP script which creates buttons-->
<input type="hidden" value="" name="id" id="delete_id">
</form>
<script>
function do_delete(which) {
var x = document.getElementById('delete_id');
x.value=which;
document.getElementById('myform').submit();
}
</script>

You can use this working jquery template for your task. It binds to all inputs that has a name="del".
<script src="http://code.jquery.com/jquery-latest.min.js"
type="text/javascript"></script>
<script>
$(document).ready(function() {
$('input[name="del"]').on('click', function() {
alert('button id is '+$(this).attr('id'));
var button_id = $(this).attr('id');
$.ajax({
method: 'post',
url: "delete.php",
data: {'did':button_id},
dataType: "html",
success: function(result) {
alert(result);
}
});
});
});
</script>
In your PHP delete file, you can retrieve the delete id via $_POST['did'].

Related

How to update data directly in row?

I have a problem with my code. I have a php script where i, in a while, i write a table in html with html name and html value attr with the data of database, like the printscreen above
My table was assembled with input inside the TDs, to be able to "edit" directly in the table, without MODAL or redirection
</thead>
<tbody id="corpoTabela">
<?php
$i = 1;
while ($row = mysqli_fetch_array($result)) :;
?>
<tr>
<form name="presencaForm" id="presencaForm" method="POST">
<input type="hidden" id="idcrmmedico" name="idcrmmedico" value="<?php echo $row['id']; ?>"></input>
See that the opening of the form tag is inside the while, that is, for each row of the table, for each TR, I have a form (all with the same name)
The end of the form tag still inside php while. The Button, who receives the ID referring to the record in the DB, has the same name of the form
<td><button id="d" name="presencaForm" value="<?php echo $row['id'] ?>" class="btn btn-sm btn-info">Atualizar</a></td>
<td>
<button type="submit" id="" name="deletamedico" class="btn btn-sm btn-danger">Excluir</button>
</td>
</form>
</tr>
<?php
endwhile;
}
?>
</tbody>
This is my ajax script, which updates the data in the database without refreshing the page and returning me a success message.
<script>
$(document).ready(function() {
$('#presencaForm').on('submit', function(event) {
event.preventDefault();
$("#alert").css('display', 'none');
console.log("Botão Clicado!");
$.ajax({
url: "DAO/medico/update.php",
method: "POST",
data: $(this).serialize(),
dataType: "json",
success: function(data) {
if (data[0] == true) {
$("#success").html('Médico ' + data[1] + ' atualizado com sucesso');
$("#success").show();
setTimeout(function() {
$("#success").hide();
}, 5000);
}
}
})
});
});
</script>
The problem is that if i try to refresh the second line, the page just refreshes.
I used the code below to check, and I saw that all buttons return only the first record in the LOG.
Is there any way to update the data as I want, right in the table?
$(document).ready(function() {
$("button[name='presencaForm']").on("click", function(event) {
event.preventDefault();
for (var i = 1; i < document.getElementById("dataTable").rows.length; i++) {
console.log($('#idcrmmedico').val());
}
var val = document.getElementById('d').value;
var x = document.getElementById("dataTable").rows.length;
});
id is unique,if you want to control a group of form,you can use class.
For example:
<form class="presencaForm" method="POST">
Then in your javascript:
$('.presencaForm').on('submit', function(event) {

php Ajax and jquery form loading then submission not working

I have 4 files testmain.php test1.php test2.php test3.php, in the testmain.php I have a div with class "content_load" where I am loading 3 files on click one by one, they are loading fine but test1.php is a form file when it's finish loading I am submitting it with ajax but it's getting redirect, I am trying since yesterday but not able to solve this, if I do not load files with ajax and just submit the test1.php that works fine, but when I combine the code of loading files using load() and submit with $.ajax() then code for loading files works fine but get redirect any solve this issue for me please so I can go ahead with my learning.
testmain.php
<div id="menu_top">
<a class="menu_top" href="test1.php">TEST 1</a> /
<a class="menu_top" href="test2.php">TEST 2</a> /
<a class="menu_top" href="test3.php">TEST 3</a> /
</div>
<div class="content_load"></div>
test1.php
<form class="ajax" action="test1.php" method="post" enctype="multipart/form-data">
<input type="text" name="txt1" /> <br>
<input type="text" name="txt2" /> <br>
<select name="sel">
<?php
include '../mysql_connect.php';
$db = new DBConfig();
$conn = $db->getDbPDO();
$sql = "SELECT * FROM tbl_campus ORDER BY camp_id ASC";
//$sql = "SELECT camp_id FROM tbl_campus ORDER BY camp_id ASC";
$query = $conn->query($sql);
$result = $query->fetchAll(PDO::FETCH_ASSOC);
$arrlength = count($result);
for ($x = 0; $x < $arrlength; $x++){
?>
<option value="<?php echo $result[$x]['camp_id']; ?>"><?php echo $result[$x]['camp_name']; ?>
<?php } ?>
</select>
<br><br>
<input type="submit" value="Click" name="submit" />
</form>
test2.php & test 3.php
<h3>THIS IS TEST 2</h3> <h3>THIS IS TEST 2</h3>
jquery file
$(document).ready(function() {
$('.content_load').load($('.menu_top:first').attr('href'));
$('.menu_top').click(function(){
var page = $(this).attr('href');
$('.content_load').load(page); return false; });
$('form.ajax').on('submit', function(e){
e.preventDefault();
var that = $(this);
url = that.attr('action'), type = that.attr('method'), data = {};
that.find('[name]').each(function(index, value){
var that=$(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
$.ajax({
url: url,
type: type,
data: data,
success: function(response){
console.log(response);
}
});
clearAll();
return false;
});
});
function clearAll(){
$("form :input").each(function(){
$(this).val("");
});
}
You cannot use direct event handler to the element that is not loaded yet.Just try to change this line:
$('form.ajax').on('submit', function(e){
to:
$('.content_load').on('submit','form.ajax', function(e){
otherwise javascript doesn't bind that event to the form and regular submit occurs.
Great explanation of the difference here: Direct vs. Delegated - jQuery .on()
May I misunderstood the problem, but if you submit the site would execute the form action.
If you dont want this, you need to add "return false" on submit, or make a "button" and no "input" for submitting.

Jquery not considering new div that is added by Jquery + php + jquery

I have a php page where I add and delete items from database using Jquery + PHP + AJAX.
Now I am able to delete and add when that page loads for the first time.
Now if I first add an element; which in turn adds record to the DB and then updates the div that contains all the listing of divs.
Example:
<div id="all_items">
<div id= "item_1">
<a id="delete_link">...</a>
</div>
<div id= "item_2">
<a id="delete_link">...</a>
</div>
.... Upto Item n
</div>
Now I replace the div with id all_items.
Now I have jQuery at the bottom of the page which calls ajax on a tag of delete_link.
Situtation is:
When page is loaded I can delete any item from the list.
But if I page load i add new item first. (which will update all_items div) after that if I try to click on delete link. Jquery on click selector event is not fired and which in turn doesn't do delete ajax operation.
I couldn't figure out why this is happening.
Looking for some help here.
EDITED:
Sorry for not writing code earliar.
Following is the jQuery I am talking about.
<script type="text/javascript" >
var jQ = jQuery.noConflict();
jQ(function() {
jQ("#submit_store").click(function() {
var store_name = jQ("#store_name").val();
var dataString = 'store_name='+ store_name;
dataString += '&mode=insert';
if(store_name =='')
{
alert("Please Enter store Name");
}
else {
jQ.ajax({
type: "POST",
url: "<?php echo $mycom_url; ?>/store_insert.php",
data: dataString,
cache: false,
success: function(html){
jQ("#dvstoreslists").html(html);
document.getElementById('store_name').value='';
document.getElementById('store_name').focus();
}
});
}
return false;
});
jQ(".store_delete").click(function() {
var store_id = jQ(this).attr('id');
var id = store_id.split("_");
var dataString = 'store_id='+ id[2];
dataString += '&mode=delete';
var to_delete = "#store_list_" + id[2]
jQ.ajax({
type: "POST",
url: "<?php echo $mycom_url; ?>/store_insert.php",
data: dataString,
cache: false,
success: function(html){
jQ(to_delete).hide("slow");
}
});
return false;
});
});
</script>
So If on page load, I delete then delete on click jquery event is fired. But after adding new store and replacing div of stores with new div. then jQuery on click event is not fired.
My HTML is as below.
<div class="sbBox stores">
<form id="add_storefrm" name="add_storefrm" method="post" action="" >
<div class="dvAddStore">
<div class="dvName" id="store_list">
<input type="text" id="store_name" name="store_name">
<input type="hidden" value="addstore" id="mode" name="mode">
</div>
<div class="btnAddStore">
<input type="submit" name="submit_store" value="Add Store" id="submit_store">
</div>
</div>
<div id="dvstoreslists">
<?php
$query = "SELECT * FROM #__shoppingstore order by store_id desc;";
$db->setQuery($query);
$rows = $db->loadObjectList();
foreach($rows as $row)
{
echo "<div class=dvlist id=store_list_".$row->store_id ."><div class=dvStoreListLeft>";
echo "<div class='slname'><h3>" . $row->store_name . "</h3></div>";
?>
<div class="slDelBtn">
<p id = "p_store_<?php echo $row->store_id ; ?>">
<a id="store_delete_<?php echo $row->store_id ; ?>" class="store_delete" alt="Delete" onclick="DeleteStore(<?php echo $row->store_id ; ?>);" >
</a>
</p>
</div>
</div>
</div>
<?php } ?>
</div>
</form>
</div>
Sorry folks for not posting the code earliar.
the ID should always be unique so use class instead
in your case : <a id="delete_link">...</a> to <a class="delete_link">...</a>
When you replace the contents of #all_items any event handlers that were bound to any descendants will no longer exist. You can use event delegation, using the on method, to solve this:
$("#all_items").on("click", ".delete_link", function() {
//Do stuff
});
Notice that I'm using a class selector (.delete_link) instead of an ID selector for the links. It's invalid to have duplicate IDs in the same document.
Also note that the above will only work if you are using jQuery 1.7 or above. For older versions, use delegate instead:
$("#all_items").on(".delete_link", "click", function() {
//Do stuff
});
This works because DOM events bubble up the tree from their target. So a click on a link which is a descendant of #all_items will bubble up through all of its ancestors and can be captured when it reached #all_items.
use live() instead of .bind()
It seems you are trying to delete dynamically added delete_link so i think you should use
$('id or class').on(click,function(){});

How to Pass Multiple CheckBox values through AJAX and process them?|

Good evening guys,
I'm trying to pass multiple checkbox values through AJAX and process them with a external .php script. Goal: delete multiple rows using checkboxes without refreshing the page.
Please assist me with passing the selected checkboxes into the datastring and putting them in the mysql command in the external .php file. This is the code so far:
The checkboxes:
<form name="frmMain" id="myForm" method="post" OnSubmit="return onDelete();">
<input class="checkbox_button_del" type="submit" id="buttondel" value="Delete" /> // submit to ajax
<input type="checkbox" class="cb-element" name="chkDel[]" id="chkDel<?=$i;?>" value="' .($id). '">
<input type="hidden" name="hdnCount" value="<?=$i;?>">
</form>
The AJAX:
$(function () {
$(".checkbox_button_del").click(function () {
var id = $(this).attr("id");
var dataString = 'id=' + id; //pass checkbox ids somehow
var parent = $(this).parents('tr:first');
$.ajax({
type: "POST",
url: "core/actions/delete_multiple.php",
data: dataString,
cache: false,
success: function () {
parent.fadeOut('300', function () {
$(this).remove();
});
$("#display").load("display.php")
}
});
return false;
});
});
The delete script:
// receive checkbox ids from ajax and delete rows
for($i=0;$i<count($_POST["chkDel"]);$i++)
{
if($_POST["chkDel"][$i] != "")
{
$strSQL = "DELETE FROM players ";
$strSQL .="WHERE id = '".$_POST["chkDel"][$i]."' ";
$objQuery = mysql_query($strSQL);
}
}
You can do this by putting all the checkboxes in a form. And then add the following line in your function:
datastring = $('#myform').serialize();
jQuery has this functionality built-in.
See: http://api.jquery.com/serialize/

jQuery: form returned on "success" needs re-binding

a quick question. I am using the jQuery.forms.js plug-in.
I have a form that posts to a php page and returns data with jSon.
The data that is returned is code for a new form (it replaces the form that was used to post the information). The new form is not bound to any jQuery functions, as it was not around when the page loaded.
So, how can I get ajax form to recognize the new form, so that if i need to use the form a second time, it is also utilizing the jQuery function?
// jQuery for submitting info to php doc and, on success, replacing the form
$(document).ready(function() {
jQuery('form[id*=postOnline]').ajaxForm({
dataType: 'json',
success: function(data) {
$('#onlineStatus' + data.rid).html(data.formed).slideDown('slow');
bindNote();
}
});
});
<!-- /////////////////////// POST ONLINE /////////////////////// -->
<div id='onlineStatus<?php echo $b_id ?>' class='postOnline'>
<form name="postOnline" id="postOnline<?php echo $b_id ?>" action="postOnline.php" method="post">
<input type="hidden" value="<?php echo $b_id ?>" name="b" />
<input type="hidden" value="1" name="p" />
<input type="submit" class="button" value="Post Online" />
</form>
</div>
<!-- /////////////////////// POST ONLINE /////////////////////// -->
// ... code for entering data into database and then...
$result = mysql_query( $sql );
if($result) {
if($show == '1'){$val = 'remove from online'; $num='0';}
if($show == '0'){$val = 'show online'; $num='1';}
$return = "
<form name='postOnline' id='postOnline$id' action='postOnline.php' method='post'>
<input type='hidden' value='$b_id' name='b' />
<input type='hidden' value='$num' name='p' />
<input type='submit' class='button' value='$val' />
</form>
";
print json_encode(array("rid" => $id, "formed" => $return));
}
?>
The easiest solution to this is not using jQuery's form plugin and doing it manually, which is really not very difficult:
$(document).ready(function() {
jQuery('form[id*=postOnline]').live('submit', function() {
var formdata = $(this).serialize();
$.ajax({
type: $(this).attr('method'),
url: $(this).attr('action'),
dataType: 'json',
data: formdata,
success: function(data) {
$('#onlineStatus' + data.rid).html(data.formed).slideDown('slow');
bindNote();
}
});
return false;
});
});
Now since you are using jQuery's new (1.3) live functionality, any forms you add that match the form[id*=postOnline] selector will still be wired with this event.
Alternatively, you can open up the jquery forms code and find wherever it does its binding and try to modify it so that it uses it live. Even another alternative would be to encompass the wiring in a function, and call it at the end of your success function, like so:
function bindForm() {
jQuery('form[id*=postOnline]').ajaxForm({
dataType: 'json',
success: function(data) {
$('#onlineStatus' + data.rid).html(data.formed).slideDown('slow');
bindNote();
bindForm();
}
});
}
$(document).ready(function() {
bindForm();
});
I don't think it is very neat, but it should work.
You need to rebind the event handlers after the ajax call. I heard about a new feature in the newer version of jquery called live events, that would make this unnecessary though.
If for whatever reason you're stuck with a pre-1.3 version of jQuery, use the "livequery" plugin.

Categories