How add confirmation box in php before deleting? - php

I create one simple list in PHP where user can add Name, age, emails, etc. I added a delete option too, but I want to add a confirmation message when the user clicks on delete option.
I tried searching Google but I found only jQuery and JavaScript solutions. Is there any way to do this with PHP only?
List.php
<?php
include('config.php');
$query1=mysql_query("select id, name, age from addd");
echo "<table><tr><td>Name</td><td>Age</td><td></td><td></td>";
while($query2=mysql_fetch_array($query1))
{
echo "<tr><td>".$query2['name']."</td>";
echo "<td>".$query2['age']."</td>";
echo "<td><a href='edit.php?id=".$query2['id']."'>Edit</a></td>";
echo "<td><a href='delete.php?id=".$query2['id']."'>x</a></td><tr>";
}
</table>
?>
Delete.php
<?php
include('config.php');
if(isset($_GET['id']))
{
$id=$_GET['id'];
$query1=mysql_query("delete from addd where id='$id'");
if($query1)
{
header('location:list.php');
}
}
?>

If you want to do this only in PHP, you will need to add "steps" in your script, like:
step1 (show form) -> step2 (ask validation) -> step3 (validate)
To do so, you can use sessions to keep form content, and GET parameter to track the step.
Otherwise the simplest solution is to use javascript:
echo "<td><a onClick=\"javascript: return confirm('Please confirm deletion');\" href='delete.php?id=".$query2['id']."'>x</a></td><tr>"; //use double quotes for js inside php!

This is u need
while($query2=mysql_fetch_array($query1))
{
echo "<tr><td>".$query2['name']."</td>";
echo "<td>".$query2['age']."</td>";
echo "<td><a href='edit.php?id=".$query2['id']."'>Edit</a></td>";
echo "<td><a onclick='javascript:confirmationDelete($(this));return false;' href='delete.php?id=".$query2['id']."'>x</a></td><tr>";
}
and create javascript function
function confirmationDelete(anchor)
{
var conf = confirm('Are you sure want to delete this record?');
if(conf)
window.location=anchor.attr("href");
}
believe me it's work :)

Here is a variation of above that gives you the Confirmation box and passes a variable from PHP to Javascript and back to PHP.
I used this to select a radio button to delete a file from a list of files.
See OnClick runs function with php $fileName past to Javascript, confirmation asked with file name, and if yes, transfers to href with variables for $_GET
PHP/HTML Code:
<?php
echo "
<tr>
<td>
<input type='radio' name='input_sched_button'
onclick='confirmation(".'"'.$fileName.'"'.")' />
</td>
<td class='fixed-td-450'><a href='./$namehref'>$fileName</a></td>
<td class='fixed-td-40'>$extn</td>
<td class='col3'>$size</td>
<td class='fixed-td-80'>$modtime</td>
</tr>
";
?>
Javascript
<script>
function confirmation(delName){
var del=confirm("Are you sure you want to delete this record?\n"+delName);
if (del==true){
window.location.href="Some_Program.php?delete=y&file="+delName;
}
return del;
}
</script>

onclick="return confirm('Are You Sure ?')"
delete

Add an onClick event to trigger the dialog box and javascript:return confirm('are you sure you want to delete this?');
echo "<td>x</td><tr>";

<script>
function deleletconfig(){
var del=confirm("Are you sure you want to delete this record?");
if (del==true){
alert ("record deleted")
}
return del;
}
</script>
//add onclick event
onclick="return deleletconfig()"

work for me but, change this:
onclick='javascript:confirmationDelete($(this));return false;'
with:
onclick='confirmationDelete(this);return false;'

I don't know, if this makes any sence, but I have come up with a solution on my own. It does not work, but I would like to share the idea in here, as it basically is supposed to do the same thing. My solution was to just have php echo the javascript, and then having the code, that is supposed to be executed echoed in javascript, so it would be execuded as normal php on site.
this is the site where I got the idea of running the php inside the JS
echo "
<script>
if (window.confirm('möchten Sie die Datei wirklich unwiderruflich löschen?')){
window.alert('<?php
unlink($allFiles);
rmdir($fileDir));
?>');
}
else{
window.alert('Vorgang abgebrochen');
}
</script>
";
How I mentioned, it does not work, so I solved it just by not having confirmation.
Would be curious why this solution does not work.

Related

Approved method to navigate between pages on same website

I have researched many places to find an answer to this question, but they never quite answer my real question: What is the best/approved way to move to a new page within the same website? I have read that it is bad to use window.location because search engines will think you are hiding something. But, when I don't want to open a new window (window.open), then I don't know how else to do it. I use href anchors in links and form actions, where appropriate. But when I have menus or buttons with onclick, then I need something else.
Here's an snippet of my code:
my javascript: (with one option commented)
function gotoCat() {
var catcdF = document.catSelect.catcd.value;
<?php
echo "window.location.href='http://www.mysite.org".$pgmdir."services/busMenu.php?catF='+catcdF; ";
/*
echo "window.open('http://www.mysite.org".$pgmdir."services/busMenu.php?catF='+catcdF,'','resizable=1,scrollbars=1,toolbar=1,top=50,left=300,width=950,height=800,location=0'); ";
*/
?>
}
My dynamic SELECT list in a form (within PHP):
echo " <select name='catcd' id='catcd' size='8' onclick=gotoCat() > \n";
// display list of categories
if ($numcats == 0) { // print message text only
echo "<option value='0' >".$catMsg."</option> \n";
}
else {
for ($i=1; $i<=$numcats; $i++) {
$catcd_db = $catAry[$i][1];
$catName_db = $catAry[$i][2];
echo "<option value='".$catcd_db."'> ".$catName_db." </option> \n";
}
}
echo "</select>";
So, as you can see, I just want a method to allow the user a choice and then automatically go to the correct web page once selected. This is not always in a select list. Often it's when they want to exit or get an error:
if (mysqli_connect_errno()) {
echo "<br/> <p style='text-align:center;'> <button type='button'
class='buttonStyle' style='padding: 4px 20px;' value='Exit' ";
echo "onClick=\"window.location.href='http://www.mysite.org/services/catSelbus.php?rc=1&func=Rev'\" > ";
echo "Exit </button></p> ";
}
I cannot use "go back" because they need to go to a prior page, not the form they came from.
So, unless my navigation methods are really off-the-mark, I guess I need to know the acceptable method for using javascript onClick to move to the next page in the same website. Is window.location okay, or should I use something else?
Any opinions or suggestions are welcome!
To navigate to another page using Javascript, use:
window.location.href = "url";
That's how it's done and there's nothing wrong about it.
For the sake of argument, you could create a hidden link and simulate a click on it, but as I said, there's really no need.
You can use php header('location') instead:
<form action="submit.php">
<input type="hidden" value="test" name="hidden1" />
<input type="submit" Value="Exit" ... />
submit.php
<?php
if (isset($_POST['hidden1'])
{
header('Location: http://www.mysite.org/services/catSelbus.php?rc=1&func=Rev');
exit;
}
?>
More info about header('Location ...');:
http://php.net/manual/en/function.header.php
Instead of a hidden, you use your select's value and get it via the $_POST variable.

Using a hyperlink to submit a form instead of a button through an intermedite function is not working

I want to submit a form through an 'edit(param1,param2)' function which in turn is being called in either of the two ways..
echo '<input type="button" value="DELETE" onclick="edit(\''.$key.'\',\''.$b.'\')"/>';
or
echo '<a href="list_cadmin.php" onclick="edit(\''.$key.'\',\''.$b.'\')"><span class="bluetext">DEACTIVATE</span>';
the function edit() is something like this:
function edit(a,b) {
var answer = confirm("Do You Really want to Deactivate ?")
if (answer){
alert(a)
document.getElementById('cid').value= a;
document.getElementById('key').value= b;
document.getElementById('fname').method='get';
document.getElementById('fname').action='samepage.php';
document.getElementById('fname').submit();
}
}
where $key and $b are number and string values respectively.
so, according to the above both should go to 'samepage.php?cid=BLAHBLAH&key=1234' on onClick. But only the input=button is working. Hyperlink is reloading without the GET parameters. How do i get the hyperlink to work?
You need to prevent the href from executing by returning false from the onclick:
echo '<a href="list_cadmin.php" onclick="edit(\''.$key.'\',\''.$b.'\'); return false;"><span class="bluetext">DEACTIVATE</span>';
Try to use
echo '<span class="bluetext">DEACTIVATE</span>';
<?php
echo <<<EOD
<a href="javascript:void(0);" onclick="edit('{$key}','{$b}')">
<span class="bluetext">DEACTIVATE</span></a>
EOD;

how to get an id of an element, which is returned from php code

I am trying to build a db driven web site in which the user selects from a drop down menu a
value and some Information from a database are returned. I use an ajax post cause i dont want the page to get refreshed:
$("#button").click(function(){
var datastr = ($('#act').val());
var datastr1 = ($('#loc').val());
$.ajax({
type:'POST',
url:'activities_code.php',
data: {datastr:datastr, datastr1:datastr1},
success:function(response){
$("#msg").html(response);
} });});
In the url parameter I have the following php file (this is a part of the php file):
$query = "SELECT PK,title,Information from activities where Activities='$category'";
$result = mysqli_query($dbcon, $query) or die('no available data');
echo "<table>";
$num_results = 0;
$t = 0; //title counter for the id of each title
while ($row=mysqli_fetch_array($result, MYSQLI_ASSOC)) {
// Here the columns of title and information are printed
echo "<tr><td>";
echo "<a href='test.php' id=\"t\".$t onClick=\"test()\" target=\"_new\" >".$row['title']."</a>";
echo "<br>";
echo $x = $row['PK'];
echo "</td></tr>";
echo "<tr><td>";
echo $row['Information'];
echo "</td></tr>";
// Here I sum up the number of the results
$num_results=$num_results+1;
$t = $t+1;
}
}
As you can see, I have a while loop in which I echo each time a link with an id:
"<a href='test.php' id=\"t\".$t onClick=\"test()\" target=\"_new\" >".$row['title']."</a>";
What I want to do is to use this id of each link later in my code by doing something like this:
document.getElementById("t1").value
My question is, how can I return this id's to the client side? I think I should write something in the success function but I have no idea what.
If you dont understand some part of the code or I didn't explain everything clear, please ask me.
Thanks
D.
This is what I get when I alert(response) in the success function.
<!DOCTYPE HTML>
<table id="container"><tr><td><a href='test.php' id="t0" target="_new" class='pickanchor'>Rafting in Voidomatis</a><br>1</td></tr><tr><td>
<img src="m.jpg" class="textwrap" height="120px" width="120px">
<p style="text-align:left;">Our experienced rafting instructors will show you the best way to enjoy Voidomatis, the river with the most clear waters inSouth Europe. You can also cross the Vikos Gorge by following Voidomatis river in an attractive one and a half hour long walk. Alternatively you can ask for the more demanding Aoos river rafting.</p>
<br>
<br>
<hr></td></tr><tr><td><a href='test.php' id="t1" target="_new" class='pickanchor'>Rafting in Lousios</a><br>4</td></tr><tr><td><img src="raf.jpg" class="textwrap" height="120" width="120">
<p>You will be surprised to know that Greece hides numerous, densely vegetated rivers offering amazing rafting opportunities. In the whole mainland, there is a company base awaiting you, for an amazing � off the beaten track experience!</p>
<br>
<br>
<br>
<hr></td></tr><div id="r2" align="center" id="result_2">2 results for rafting were found!
</div></table> <!-- End of PHP code-->
First, There is problem with ID of your anchor tag. here is correction
"<a href='test.php' id=\"t".$t."\" onClick=\"test()\" target=\"_new\" >".$row['title']."</a>";
Second, Give id to your table like
<table id="container">
Third, give class to your anchor tag.
"<a href='test.php' class='pickanchor' id=\"t.$t\" onClick=\"test()\" target=\"_new\" >".$row['title']."</a>";
Now write following code into your success handle after .html() statement
NEW EDIT
$("a.pickanchor").each(function(i){
alert(this.id);
});
In line you presentd you made mistake. In wrong place you have added ".
echo "<a href='test.php' id=\"t\".$t onClick=\"test()\" target=\"_new\" >".$row['title']."</a>";
It should be
echo "<a href='test.php' id=\"t".$t."\" onClick=\"test()\" target=\"_new\" >".$row['title']."</a>";
As simplest solution you could add after the while loop
echo "<script> my_max_id_num=$t </script>"
This will give you knowledge about which ids are present on page. This should give your js script access to my_max_id_num variable. It's not considered best programming practice but is simple.
Second (better) way of solving problem could be returning json instead of html and rewriting your success method. This will be more work to be done:
Rewrite while loop so it returns something like:
{ "data":[
...
{ "id":"10", "target":"_new", "title":"one_of_your_link_titles" },
{ "id":"10", "target":"_new", "title":"one_of_your_link_titles" },
...
]}
Rewrite your ajax query so it will accept json, and rewrite success method so it will create your links on basis off data returned from server.
This way you will have both, ids and your links in one query. What's more in case of changing requirements it will be easier.
The simplest solution would be to give your elements a class, that way you don't need to select based on the elements id, but you can access it easily:
eg.
test 0
test 1
$('#msg').on('click', '.className', function() {
console.log(this.id);
});
I don't have enough rep points to ask for clarification, but what do you mean by 'return this id's to the client side'? Also what would the 'value' of the element 't1' be?
Lets say you wanted to get the link location it could be something like:
var value = $('#addButton').attr('href');
and then do something with the value (not sure what you mean by 'return this id's to the client side') but perhaps you want the value then to be visible to the client?
So if you have a div somewhere on the page where you want it to show you could populate it with you value, maybe something like:
HTML
<div id="valueBox"></div>
jQuery
$("#valueBox").html(value);

Issue with Calling JS function through PHP based on IF statement

I have a web based tool. There is a login where username, loggedin and authorised are stored in session variables.
There is one particular page where I have a form that has multiple buttons, I wish to disable one button based on what the users authorisation level is. So if authorised is 0 (user) the button is disabled, else it's enabled as I've only got two authorisation levels, 0 & 1.
I've attached what I've done below, and to me it looks right, obviously it's not!
Here is the JQuery function:
$(function disable(){
$('#signBtn').attr('disabled', true);
});
Here is the PHP code:
if($_SESSION['authorised'] == '0')
{
echo "<SCRIPT LANGUAGE='javascript'>disable();</SCRIPT>";
}
Here is my HTML code:
<input type=\"submit\" name=\"save\" id = \"signBtn\" class = 'eBtnSubmit' value=\"Sign off by Chairperson\" />
If there is anyone out there that can see what my problem is I would really appreciate it...this is my last piece of the puzzle and I'm presenting this today (Software Intern).
So basically if the level is 0 call the function.
Regards,
Gary
No warranty because I don't have all the code
Change the static JavaScript Code to this
var disableSingoff = function () {
$('#signBtn').attr('disabled', true);
}
In your original code, you execute the disable() function right when the DOM is ready by wrapping it in $().
Change the PHP code to this
if($_SESSION['authorised'] == '0') {
echo "<script>$(function () { disableSignoff(); })</script>";
}
It might be easier to simply set the value in the HTML if possible
if($_SESSION['authorised'] == '0'){
echo '<button type="button" disabled="disabled">Click Me!</button>';
}else{
echo '<button type="button">Click Me!</button>';
}
This would work before the page even starts loading.
The other option would be to hook the window on load function.
window.onload = (function(){ [...] }
is the <input type=\"submit\" name=\"save\" id = \"signBtn\" class = 'eBtnSubmit' value=\"Sign off by Chairperson\" /> being echoed from a php statement? if not you can get rid of all the '\'s. they are not necessary when writing strictly html.

php javascript confirm box for delete

The below code is in PHP
echo "<input type='submit' name='delete' value='$t2[0]' class='delete_button' onclick='return confirm('Please Confirm Delete');'>"
I am trying to create a delete button, when a user clicks on delete button , it should ask confirmation. but in this case, its not working.
is there any best way to delete with confirmation in php with/ or javascript
and no ajax
Your quotes are breaking themselves here;
onclick='return confirm('Please Confirm Delete');'>
Instead use;
onclick="return confirm('Please Confirm Delete');">
Well, in javascript you can do it as:
<input type='submit' name='delete' value='$t2[0]' class='delete_button' onclick='return askme();'>
//javascript function
function askme() {
if(confirm("Are you sure you want to delete this..?")) {
//delete someting
}
}
The quotes are going wrong, use this instead:
echo "<input type='submit' name='delete' value='$t2[0]' class='delete_button' onclick='return confirm(\"Please Confirm Delete\");'>"
You are going out of your attribute by opening the single quote again inside your confirm.
You cannot "call php code into jquery". The only thing you can do is to set up a request (AJAX) to a server side PHP script which will take over the respective parameters you transferred to the script and produce an output (using echo or print) which will automatically be available in the request's callback.
With jQuery it's as easy as that
$.post('url/to/script.php', {parameter1: 'whatever', param2: 'something'}, function(response) {
// the output of the PHP script is available in the variable "response"
alert(response);
});
The PHP script can take over the parameters, take any action with it and create output
$param1 = $_POST["parameter1"];
$param2 = $_POST["param2"];
// do whatever you want with $param1 and $param2
// create some output using echo/print
echo "This will be transferred back to the calling Javascript";
You can try this, quite easy and it works.
<td> <a onClick="return confirm('DELETE: Are You sure ??');" href="member_delete?id=<?php echo $row['memID'];?>" >delete <i class="fa fa-trash-o" aria-hidden="true"></i></a></td> [DEMO][1]
I assume, its in a table list of members.

Categories