Confirm button before running deleting routine from website - php

I have a page on my website that is dynamically created with information from an SQL database. As well as the data being displayed a delete link is also created for each record which links to a php file called deleteRecord.php that deletes that record from the database.
Is there any way I can incorporate a confirmation message so that when the Delete link is clicked it will only run the deleteRecord.php file if the response is Yes?

You could use JavaScript. Either put the code inline, into a function or use jQuery.
Inline:
Delete
In a function:
Delete
and then put this in <head>:
<script language="JavaScript" type="text/javascript">
function checkDelete(){
return confirm('Are you sure?');
}
</script>
This one has more work, but less file size if the list is long.
With jQuery:
Delete
And put this in <head>:
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script language="JavaScript" type="text/javascript">
$(document).ready(function(){
$("a.delete").click(function(e){
if(!confirm('Are you sure?')){
e.preventDefault();
return false;
}
return true;
});
});
</script>

You have 2 options
1) Use javascript to confirm deletion (use onsubmit event handler), however if the client has JS disabled, you're in trouble.
2) Use PHP to echo out a confirmation message, along with the contents of the form (hidden if you like) as well as a submit button called "confirmation", in PHP check if $_POST["confirmation"] is set.

Call this function onclick of button
/*pass whatever you want instead of id */
function doConfirm(id) {
var ok = confirm("Are you sure to Delete?");
if (ok) {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
window.location = "create_dealer.php";
}
}
xmlhttp.open("GET", "delete_dealer.php?id=" + id);
// file name where delete code is written
xmlhttp.send();
}
}

You can do it with an confirm() message using Javascript.

Try this one :
<script type="text/javascript">
var baseUrl='http://example.com';
function ConfirmDelete()
{
if (confirm("Delete Account?"))
location.href=baseUrl+'/deleteRecord.php';
}
</script>
echo '<a type="button" onclick="ConfirmDelete()">DELETE ACCOUNT</a>';

<?php
$con = mysqli_connect("localhost","root","root","EmpDB") or die(mysqli_error($con));
if(isset($_POST[add]))
{
$sno = mysqli_real_escape_string($con,$_POST[sno]);
$name = mysqli_real_escape_string($con,$_POST[sname]);
$course = mysqli_real_escape_string($con,$_POST[course]);
$query = "insert into students(sno,name,course) values($sno,'$name','$course')";
//echo $query;
$result = mysqli_query($con,$query);
printf ("New Record has id %d.\n", mysqli_insert_id($con));
mysqli_close($con);
}
?>
<html>
<head>
<title>mysql_insert_id Example</title>
</head>
<body>
<form action="" method="POST">
Enter S.NO: <input type="text" name="sno"/><br/>
Enter Student Name: <input type="text" name="sname"/><br/>
Enter Course: <input type="text" name="course"/><br/>
<input type="submit" name="add" value="Add Student"/>
</form>
</body>
</html>

Another method using both onlcick & form submit button with php record id value (record to be delete).
Use php code to get the record ID to be deleted. This is working for me.
<form action="deleteRecord.php" method="POST">
<button onclick="return confirm('Are you sure! want to delete?')" type="submit" name="id" value="<?=$record['id'];?>" >Delete</button>
</form>
deleteRecord.php example file
<?php
$con=mysqli_connect("localhost","root","","dbname") or die(mysqli_error($con));
if(isset($_POST['id']))
{
$id = mysqli_real_escape_string($conn, $_POST['id']);
$query = "DELETE FROM table_name WHERE id='$id' ";
$query_run = mysqli_query($conn, $query);
}
mysqli_close($con);
if($query_run)
{
echo "Deleted Successfully";
exit(0);
}
else
{
echo "Not Deleted";
exit(0);
}
?>

Related

HTML form data not being posted to use in SQL query

this should be simple but I have lost my way
simple form on HTML page - select Men, Women or Junior
then send that that value to a php page to perform SQL query and find all the Men, Women or Juniors using the variable "$trigen"
display the results on the HTML page using AJAX
if I set $trigen manually it works, but not when I choose the option in the form as set out in this code:--
my HTML:-
<!DOCTYPE html>
<html>
<div class="entry-content">
<form action="/getcustomer.php" method="POST">
<label for="trigen">Choose a gender:</label>
<select id="trigen" name="trigen">
<option value="Men">Men</option>
<option value="Women">Women</option>
<option value="Junior">Junior</option>
</select>
<button class="btn btn-primary text-center btn-block btn-flat" style="h2; margin: 20px; color:black; " name="trilookup" type="submit" onclick="showResults()"> Search</button>
</form>
</div>
<div id="results">Results go here if it works....</div>
<script>
function showResults(str) {
var xhttp;
if (str == "") {
document.getElementById("results").innerHTML = "";
return;
}
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("results").innerHTML = this.responseText;
}
};
xhttp.open("GET", "getcustomer.php?q="+str, true);
xhttp.send();
}
</script>
then my php code in "getcustomer.php"
<?php
//connect to the database
$conn=mysqli_connect('localhost','wetsuder_user1','user123','wetsuder_finder');
if($conn){
}
else{
echo "Sorry there is a connection error".mysqli_connect_error();
}
$trigen=$_POST['trigen'];
//this is the search
$sql = "SELECT id, Gender, Wetsuit FROM wp_wetsuitdata WHERE Gender = '$trigen'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<table><tr><th>ID</th><th>Name</th></tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>".$row["id"]."</td><td>".$row["Gender"]." ".$row["Wetsuit"]."</td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}
$conn->close();
?>
Your button is causing a form submission. Just add preventDefault() as the first line of your showResults function and it will prevent the form from submitting naturally. You're handling the form submission via ajax. Also you don't need to have an action or method on your <form tag for the same reason. Another way of preventing the form from submitting is like this: <form onsubmit="return false"
Also, change your function to find the value you want to send, since you're not actually passing that value through the function call str
function showResults() {
preventDefault(); // prevents form submission
// get the value
let str = document.getElementById('trigen').value;
// check to make sure it's there...
if (!str) return alert("Please select an option...");
var xhttp;
......
You're sending the data via GET (when you use the ?q=val on your URL, the data is being sent through GET. So, you can receive it in your PHP with this:
$trigen=$_GET['q'];

javascript function not returning value for a particular case

I have a sample script in php and validation are done using javascript. I am generating a inputbox using ajax script on click of a button. When I click submit it checks whether all the boxes are filled or not.
I am validating the boxes using for loop. When the boxes are empty it correctly alerts and I am returning false for the same case. But the problem is when all the boxes are filled it doesn't not return any thing and the function stops working even when I m returning true for this condition.
My javascript code with function is shown below
function addInput(){
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var result = xmlhttp.responseText;
var newElem = document.createElement ("div");
newElem.innerHTML = result;
newElem.id = "input";
var container = document.getElementById ("main");
container.appendChild (newElem);
}
}
xmlhttp.open("GET","insert.php",true);
xmlhttp.send();
}
var count = '<?php echo $_SESSION['z']; ?>'
function check(){
function validate()
{
for(var i=1; i<=count+10; i++)
{
if(document.getElementById("text"+i+"").value == "")
{
alert("Please Enter Start Date For Sales Promotion");
document.getElementById("text"+i+"").focus();
return 'false';
}
}
return 'abc';
}
var flag = validate();
if(flag != 'false')
{
alert("correct");
}
}
MY html code is shown below
<form method="post" action="save.php">
<div id="main">
<div id="input1">
Enter Name </br></br>
<input type="text" id="text1" />
<?php $_SESSION['z'] = 2; ?>
</div>
</div>
</br>
<input type="button" value="add another" onclick="addInput()" />
<input type="button" value="Submit" onclick="check()" />
</form>
<div id="display"></div>
my ajax code is shown below
<?php
session_start();
$q = $_SESSION['z'];
?>
Enter Name </br></br>
<input type="text" id="text<?php echo $q; ?>" />
<?php $q = $q + 1;
$_SESSION['z'] = $q;
?>
the problem is when all the fields are filled it doesn't return anything.
This may occur a lot, and according to the browser used, the click event and submit event will be call at the same time, it's not safe (for exemple, in IE if your submit button call another submit function, the form will be submitted twice...)
You should wire your check function to the onBeforeSubmit event of your form.
It is likely that you get an error when you try to retrieve an item which does not exist on the page.
if(document.getElementById("text"+i+"").value == "")
{
alert("Please Enter Start Date For Sales Promotion");
document.getElementById("text"+i+"").focus();
return 'false';
}
Here may be there are no items with ids like "text8", "text9", etc. In that case there will be null reference error when you try to get value of non exisisting element.
Try changing it like this:
var ele = document.getElementById("text"+i);
if(ele && ele.value == "")
{
alert("Please Enter Start Date For Sales Promotion");
document.getElementById("text"+i+"").focus();
return 'false';
}
This validates if ele is null or not before accessing the value of it.

submit a form via Ajax and update a result div

I was using a self submitting form to process the data but I now need to process it separately so now I need to submit a form, return the results and place it in a div. It seems using AJAX is a good way to do this to have the data return to the original page where the form is. I have had a look at alot of examples and I don't really understand how to do it or really how its working.
Say I wanted to send this form data from index.php to my process page twitterprocess.php what do I need to do and get it to return to display the data processed.
<form method="POST" action="twitterprocess.php">
Hashtag:<input type="text" name="hashtag" /><br />
<input type="submit" value="Submit hashtag!" />
</form>
This is what I have been using to display the results.
<?php foreach($results as $result) {
$tweet_time = strtotime($result->created_at);?>
<div>
<div class="tweet"> <?php echo displayTweet($result->text),"\r\n"; ?>
<div class="user"><?php echo "<strong>Posted </strong>" . date('j/n/y H:i:s ',$tweet_time) ?><strong> By </strong><a rel="nofollow" href="http://twitter.com/<?php echo $result->from_user ?>"><?php echo $result->from_user ?></a></div>
</div>
<br />
<? } ?>
I'm new to AJAX but any guidance would be greatly appreciated
*When you use AJAX the output generated on other page is the result for this page.
*Now when you want to post data and retrieve results through the use of AJAX then in form part of your html don't use type="submit" for button, but simply go for type="button".
*action attribute should be left blank as you are going to trigger the action through your AJAX code.
*Well rest all your solution in the code snippet below:
Below is the HTML code along with AJAX
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Simple Form Handling Through AJAX</title>
<script type="text/javascript">
function loadXmlDoc(fname, lname){
var xmlhttp;
if (window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
}
else{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
document.getElementById("ajaxify").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("POST", "demo_ajax3.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("fname=" + fname + "&" + "lname=" + lname);
}
</script>
</head>
<body>
<p>
<span id="ajaxify"> </span>
</p>
<form id="frm" action="#">
<input type="text" name="fn" />
<input type="text" name="ln" />
<input type="button" name="submit" value="submit" onclick="loadXmlDoc(fn.value, ln.value)" />
</form>
</body>
</html>
Below is the PHP code that is used in above code
<?php
$fname = $_POST["fname"];
$lname = $_POST["lname"];
echo "Hello " . $fname . " " . $lname;
?>
Assign some id to your submit button, i'd use id="submit" and some id for your text field (i use id="text");
Client-side js:
$("#submit").click(function () {
var postData = new Object(); //for complex-form
postData.hashTag = $("#text").val();
$.ajax({
type: 'POST', //or 'GET' if you need
contentType: "application/json; charset=UTF-8", //i use json here
dataType: "json",
url: "some_url",
data: JSON.stringify(postData), //or smth like param1=...&param2=... etc... if you don't want json
success: function (response) {
//handle response here, do all page updates or show error message due to server-side validation
},
error: function () {
//handle http errors here
}
});
return false; //we don't want browser to do submit
});
So, if user has js enabled = your code will do ajax request, otherwise - regular post request will be made;
On a server-side you have to handle ajax and regular submit different to make it work correct in both cases. I'm not good in php so can't do any advise here
You can use jQuery, for example,
function doPost(formdata){
var url="/twitterprocess.php";
var senddata={'data':formdata};
$.post(url,senddata,function(receiveddata){
dosomethingwithreceiveddata(receiveddata);
}
your php will get senddata in JSON form. You can process and send appropriate response. That response can be handled by dosomethingwithreceiveddata.
I find the Ajax Form plugin a good tool for the job.
http://www.malsup.com/jquery/form/#tab4
A basic code example could be:
$(document).ready(function() { // On Document Ready
var options = {
target: '#output1', // ID of the DOM elment where you want to show the results
success: showResponse
};
// bind form using 'ajaxForm'
$('#myForm1').ajaxForm(options);
});
// the callback function
function showResponse(responseText, statusText, xhr, $form) {
alert('status: ' + statusText + '\n\nresponseText: \n' + responseText +
'\n\nThe output div should have already been updated with the responseText.');
}
All your PHP file have to do is echo the html (or text) back that you want to show in your DIV after the form has been submitted.
If you do not want to use jquery try this in pure javascript
function SendData(Arg) {
xmlhttp=null;
var uri = "/twitterprocess.php";
if(window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
} else if(window.ActiveXObject) {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
if(xmlhttp!=null) {
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState==4) {
if(xmlhttp.status==200) {
var xmlDoc = xmlhttp.responseXML;
var DateNode=xmlDoc.getElementsByTagName('Date')[0].firstChild.nodeValue;
var Xml2String;
if(xmlDoc.xml) {
Xml2String = xmlDoc.xml
} else {
Xml2String = new XMLSerializer().serializeToString(xmlDoc);
}
document.getElementById("CellData").value=Xml2String;
} else {
alert("statusText: " + xmlhttp.statusText + "\nHTTP status code: " + xmlhttp.status);
}
}
}
}

While Loop, jQuery and AJAX mysql query

I'm working on a message system where users submit one response to another user. The receiver then views all of his messages in a while loop. I created a delete button that will delete the whichever message the delete button is linked to. I have two problems. First, the delete button does not work, and second, when it was working (it no longer is) the while loop was linking all the delete buttons to the first message and not individually to each message the while loop produced. Also, I'm aware that mysql is deprecated. Will be making the transition over soon.
Here is the first code:
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<script type="text/javascript" >
function load(thefile, thediv) {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject ('Microsoft.XMLHTTP');
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById(thediv).innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open('GET', thefile + key, true);
xmlhttp.send();
}
</script>
<?php
while($ergo_data = mysql_fetch_assoc($ergo_query_result)) {
echo 'Message: ' . $ergo_data['ergo'] . '<br>';
echo 'From: ' . username_from_user_id($ergo_data['user_id_seeker']) . '<br>';
echo 'Time submitted: ' . $ergo_data['ergo_time_submitted'] . '<br><br><br><br>';
echo $ergo_data['primary_key'];
?>
<div class="changes">
<input type="button" value="delete" class="<?php echo $ergo_data['primary_key']; ?>"
name="<?php echo $ergo_data['user_id_seeker']; ?>"
onclick="load('ajax_ergo_list.php?key=',
'delete');">
</div>
<script type="text/javascript" >
$(document).ready(function(){
var key = $(".changes :input").attr("class");
alert(key);
});
</script>
<br>
<br>
<br>
<?php
}
?>
<div id="delete"></div>
Here is the second file containing what I want to happen when the button is pressed.
if (isset($_GET['key'])) {
$key = sanitize($_GET['key']);
}
if (!empty($key)) {
$query = "DELETE FROM `ergo` WHERE `primary_key` = '$key'";
$query_run = mysql_query($query);
echo 'Deleted!';
}
?>
Ok, first off, this is all sorts of crazy code you got going on here...
<script type="text/javascript" >
$(document).ready(function(){
var key = $(".changes :input").attr("class");
alert(key);
});
</script>
You have your script inside a while loop. That will alert as many times as the loop is. And that is really all the function does. It's not setting a global variable or anything.
In regards to jQuery, use it:
function load(thefile, thediv) {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject ('Microsoft.XMLHTTP');
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById(thediv).innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open('GET', thefile + key, true);
xmlhttp.send();
}
Condense that to this:
function load(thefile, thediv) {
$.get(thefile+key,function(responseText){
$('#'+thediv).html(responseText);
});
}
In regards to your question about the delete function:
<div class="changes">
<input type="button" value="delete" class="<?php echo $ergo_data['primary_key']; ?>"
name="<?php echo $ergo_data['user_id_seeker']; ?>"
onclick="load('ajax_ergo_list.php?key=',
'delete');">
</div>
Your onclick is the javascript that is firing. You have the first variable set to the link and the second to the action I am guessing? In your function code, the second variable is supposed to be the div where the info is displayed. The key is no where to be found. Try doing this instead:
<div class="changes">
<input type="button" value="delete" class="<?php echo $ergo_data['primary_key']; ?>"
name="<?php echo $ergo_data['user_id_seeker']; ?>"
onclick="load('ajax_ergo_list.php?key=<?php echo $ergo_data['primary_key'];?>',
'delete');">
</div>
And your load function to this:
function load(thefile, thediv) {
$.get(thefile,function(responseText){
$('#'+thediv).html(responseText);
});
}
Good luck!

Commenting System - Ajax, Php & MySql

I've succeeded to write a simple commenting system with a form of 2 fields: name and comment. When the user inters values and presses submit it simply adds the comment to the current page using Ajax (without loading the whole page).
Now, I need also to add the ability of "Deleting Comment", but I have no idea how can I implement that.
If you take a look at my code bellow you would notice that when loading the page I printed all the existing comments, and when adding new ones I simply added them to the HTML code by this sub-code:
document.getElementById("result").innerHTML +=
"<font color='red' size='5'>" + str + "</font>";;
I thought of declaring an array that holds the values of all the comments with an additional value for each one "active".
When this value is trua I print the current comment, else I dont.
I've not succeeded to implement that, besides, Is it a good solution at all?
cause this solution prints all the comments all over again each time the user presses submit.
Any suggestions?
I would appreciate your help.
This is My Code:
main.php
<html>
<head>
<title> </title>
<script language="Javascript" src="ajax.js"> </script>
</head>
<body>
<h1 align="center"><font color="#000080">Welcome, </font></h1>
<p align="center"><font color="#000080">Enter your name & comment then press
"Submit Button"</font></p>
<form name="f1" method="post">
<p align="center"><font color="#000080">
Enter your name: <input type="text" name="username" id="username">
<font color="#000080">
Enter your comment: <input type="text" name="comment" id="comment">
<input value="Submit" type="button"
onclick='JavaScript:postRequest()' name="showdate"></font></p>
</form>
</br></br>
<?php
include_once("config.php");
$query = "SELECT * FROM `comments` ORDER BY 'id'";
//Execute query
$qry_result = mysql_query($query) or die(mysql_error());
// Insert a new row in the table for each person returned
while($row = mysql_fetch_array($qry_result)){
echo ' <p align="center">';
echo "<font color='red' size='5'> name: </br>".$row['added_by'];
echo " </br>comment: </br>".$row['comment'];
echo "</font></p>";}
?>
<div id="result" align="center"> </div>
</body>
</html>
showcomments.php
name: ' .$name;
echo 'comment: ' .$content;
echo ''
?>
ajax.js
function postRequest() {
var xmlHttp;
try{
// Opera 8.0+, Firefox, Safari
xmlHttp = new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer Browsers
try{
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try
{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
var usr=window.document.f1.username.value;
var cmnt=window.document.f1.comment.value;
var url = "showcomments.php?username=" + usr +"&comment=" + cmnt;
xmlHttp.open('GET', url, true);
xmlHttp.setRequestHeader
('Content-Type', 'application/x-www-form-urlencoded');
xmlHttp.onreadystatechange =function(){
if(xmlHttp.readyState == 4){
updatepage(xmlHttp.responseText);
}
}
xmlHttp.send(url);
}
function updatepage(str){
document.getElementById("result").innerHTML +=
"<font color='red' size='5'>" + str + "</font>";;
}
(P.S: I created a table using MySql named "comments" with the following columns: Id, Added_by, comment.)
I would not only print the name and comment in you PHP file, but also a form with a hidden field containing the ID. Or, even better, a button with a onClick="deleteComment(ID)". More importantly: place every comment in a p-tag with an ID, with id=comment-id. Your main.php PHP file would be expanded with this:
while($row = mysql_fetch_array($qry_result)){
echo ' <p align="center" id="'.$row['id'].'>';
echo "<font color='red' size='5'> name: </br>".$row['added_by'];
echo " </br>comment: </br>".$row['comment'];
echo "</font></p>";}
This (ajax)-function deleteComment(ID) then sends the ID of the comment to be deleted to another PHP-script. This deletes it from the database.
Now you have two options: you either delete the p-tag on the page by it's ID (this is very easy with jQuery with the function $('IDofP').empty(); ) or you reload all the comments.

Categories