Javascript confirm delete and edit in same form - php

I have two submit buttons on the same form for edit and delete and I want to make delete confirmation alert. I've tried but this only work yes however I select "no/cancel" in delete confirmation. What should I do ?
This is the form
<form name="form" method="POST" action="update.php">
//form code
<input name="update_button" type="submit" value="Update" />
<input type="submit" name="delete_button" onClick="javascript:confirmDelete();" value="Delete"/>
This is the javascript
<script type="text/javascript">
function confirmDelete()
{
var status = confirm("Are you sure you want to delete ?");
if(status)
{
parent.location.replace("parent.location='<?php echo "update.php";?>'");
}else
{
parent.location.replace("parent.location='<?php echo "form.php?ticket=".$c['no'] ?>'");
}
}
</script>
And this is the update.php
if(isset($_POST['update_button']))
{
//update proses
}
else if(isset($_POST['delete_button']))
{
//delete proses
}
I want delete confirmation show "Are you sure you want to delete ?" if I select "yes", it would delete from database and if I choose "Cancel", it will stay at current page (form.php).
Thanks before,

You don't need to add javascript: in onclick or any event handling attribute. Just use onclick="return confirmDelete();"
and your javascript will be like this:
<script type="text/javascript">
function confirmDelete() {
var status = confirm( "Are you sure you want to delete ?" );
return status;
}
</script>
alternately you can use onclick="return confirm( 'Are you sure you want to delete ?' );"

Html:
<form name="form" method="POST" action="">
<input name="update_button" type="submit" value="Update" />
<input type="button" name="delete_button" id="delete_button" value="Delete"/>
Javascript:
$("#delete_button").on('click',function(){
if(confirmDelete()){
parent.location.replace("parent.location='<?php echo "update.php";?>'");
}
else{
parent.location.replace("parent.location='<?php echo "form.php?ticket=".$c['no'] ?>'");
}
});
function confirmDelete(){
var status = confirm("Are you sure you want to delete ?");
if(status)
{
return true;
}
return false;
}

Related

how to show error in jquery after clicking submit button

My problem is that after clicking on submit button the page will go to php file any way my html code is like this
<form action="register.php" method="post">
<input type="text" name="name" id="name"><div id="adiv"></div>
<input type="submit" value="submit" id="button">
</form>
and my jquery code goes like this
$('#name').focusout(function(){
if($('#name').val().length==0){
$('#adiv').html("please enter name")
}
});
$('#button').click(function(){
if($('#name').val().length==0){
$('#adiv').html("please enter your name")
}
});
but after clicking submit button it redirects to php file and doesn't show any error and store blank data in the database.
Because your input type is submit you can either change the type to button or add event.preventDefault() to avoid automatic passing of form
use event.preventDefault()
$('#button').click(function(e) {
e.preventDefault();//this will stop form auto submit thus showing your error
if ($('#name').val().length == 0) {
$('#adiv').html("please enter your name")
}
});
Or
<input type="submit" value="submit" id="button">
change to
<input type="button" value="submit" id="button">//also prevent form auto submit thus will show the error
Well you need to stop the code to execute after error has been detected. For example you can simple use return false or return:
$('#name').focusout(function() {
if ($('#name').val().length == 0) {
$('#adiv').html("please enter name")
}
});
$('#button').click(function() {
if ($('#name').val().length == 0) {
$('#adiv').html("please enter your name")
return false;//add this
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="register.php" method="post">
<input type="text" name="name" id="name">
<div id="adiv"></div>
<input type="submit" value="submit" id="button">
</form>
I strongly recommend never to assign validation to a submit button click.
Instead assign the submit event handler of the form.
I also added trim and removed the content of the error from the code.
$(function() {
$('#name').focusout(function() {
var empty = $.trim($('#name').val()).length == 0;
$('#adiv').toggle(empty);
});
$('#form1').on("submit",function(e) {
$('#name').focusout();
if ($('#adiv').is(":visible")) {
e.preventDefault()
}
});
});
#adiv { display:none }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form action="register.php" method="post" id="form1">
<input type="text" name="name" id="name">
<div id="adiv">please enter name</div><br/>
<input type="submit" value="submit" id="button">
</form>
Please check this
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post">
<input type="text" name="name" id="name">
<div id="adiv"></div>
<input type="button" value="submit" id="button">
</form>
<script>
$(document).ready(function(){
$('#button').on('click',function(){
if($('#name').val() == ''){
$('#adiv').text("Please enter name!!");
}else{
$('#adiv').text($('#name').val());
}
})
})
</script>
try this..:D
function validateFunction(){
if(document.getElementByID('name').value.length==0){
document.getElementByID('adiv').innerHTML = "please enter your name";
return false;
}
return true;
}
<input type="submit" value="submit" id="button" onclick="return validateFunction();" />
$('your-form').on('submit', function(e) {
e.preventDefault();
//your code bere
});
preventDefault stop the normal submit behaviour of your browser so that you can trigger any event you want

How to call a PHP function on the click of a button

I have created a page called functioncalling.php that contains two buttons, Submit and Insert.
I want to test which function is executed when a button gets clicked. I want the output to appear on the same page. So, I created two functions, one for each button.
<form action="functioncalling.php">
<input type="text" name="txt" />
<input type="submit" name="insert" value="insert" onclick="insert()" />
<input type="submit" name="select" value="select" onclick="select()" />
</form>
<?php
function select(){
echo "The select function is called.";
}
function insert(){
echo "The insert function is called.";
}
?>
The problem here is that I don't get any output after any of the buttons are clicked.
Where exactly am I going wrong?
Yes, you need Ajax here. Please refer to the code below for more details.
Change your markup like this
<input type="submit" class="button" name="insert" value="insert" />
<input type="submit" class="button" name="select" value="select" />
jQuery:
$(document).ready(function(){
$('.button').click(function(){
var clickBtnValue = $(this).val();
var ajaxurl = 'ajax.php',
data = {'action': clickBtnValue};
$.post(ajaxurl, data, function (response) {
// Response div goes here.
alert("action performed successfully");
});
});
});
In ajax.php
<?php
if (isset($_POST['action'])) {
switch ($_POST['action']) {
case 'insert':
insert();
break;
case 'select':
select();
break;
}
}
function select() {
echo "The select function is called.";
exit;
}
function insert() {
echo "The insert function is called.";
exit;
}
?>
Button clicks are client side whereas PHP is executed server side, but you can achieve this by using Ajax:
$('.button').click(function() {
$.ajax({
type: "POST",
url: "some.php",
data: { name: "John" }
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
});
In your PHP file:
<?php
function abc($name){
// Your code here
}
?>
You should make the button call the same page and in a PHP section check if the button was pressed:
HTML:
<form action="theSamePage.php" method="post">
<input type="submit" name="someAction" value="GO" />
</form>
PHP:
<?php
if($_SERVER['REQUEST_METHOD'] == "POST" and isset($_POST['someAction']))
{
func();
}
function func()
{
// do stuff
}
?>
You cannot call PHP functions like clicking on a button from HTML. Because HTML is on the client side while PHP runs server side.
Either you need to use some Ajax or do it like as in the code snippet below.
<?php
if ($_GET) {
if (isset($_GET['insert'])) {
insert();
} elseif (isset($_GET['select'])) {
select();
}
}
function select()
{
echo "The select function is called.";
}
function insert()
{
echo "The insert function is called.";
}
?>
You have to post your form data and then check for appropriate button that is clicked.
To show $message in your input:
<?php
if(isset($_POST['insert'])){
$message= "The insert function is called.";
}
if(isset($_POST['select'])){
$message="The select function is called.";
}
?>
<form method="post">
<input type="text" name="txt" value="<?php if(isset($message)){ echo $message;}?>" >
<input type="submit" name="insert" value="insert">
<input type="submit" name="select" value="select" >
</form>
To use functioncalling.php as an external file you have to include it somehow in your HTML document.
Try this:
if($_POST['select'] and $_SERVER['REQUEST_METHOD'] == "POST"){
select();
}
if($_POST['insert'] and $_SERVER['REQUEST_METHOD'] == "POST"){
insert();
}
You can write like this in JavaScript or jQuery Ajax and call the file
$('#btn').click(function(){
$.ajax({
url:'test.php?call=true',
type:'GET',
success:function(data){
body.append(data);
}
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<form method='get' >
<input type="button" id="btn" value="click">
</form>
<?php
if(isset($_GET['call'])){
function anyfunction(){
echo "added";
// Your funtion code
}
}
?>
The onclick attribute in HTML calls JavaScript functions, not PHP functions.
I was stuck in this and I solved it with a hidden field:
<form method="post" action="test.php">
<input type="hidden" name="ID" value"">
</form>
In value you can add whatever you want to add.
In test.php you can retrieve the value through $_Post[ID].
Use a recursive call where the form action calls itself. Then add PHP code in the same form to catch it. In foo.php your form will call foo.php on post
<html>
<body>
<form action="foo.php" method="post">
Once the form has been submitted it will call itself (foo.php) and you can catch it via the PHP predefined variable $_SERVER as shown in the code below
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
echo "caught post";
}
?>
</form>
</body>
</html>
Here is an example which you could use:
<html>
<body>
<form action="btnclick.php" method="get">
<input type="submit" name="on" value="on">
<input type="submit" name="off" value="off">
</form>
</body>
</html>
<?php
if(isset($_GET['on'])) {
onFunc();
}
if(isset($_GET['off'])) {
offFunc();
}
function onFunc(){
echo "Button on Clicked";
}
function offFunc(){
echo "Button off clicked";
}
?>
Calling a PHP function using the HTML button: Create an HTML form document which contains the HTML button. When the button is clicked the method POST is called. The POST method describes how to send data to the server. After clicking the button, the array_key_exists() function called.
<?php
if(array_key_exists('button1', $_POST)) {
button1();
}
else if(array_key_exists('button2', $_POST)) {
button2();
}
function button1() {
echo "This is Button1 that is selected";
}
function button2() {
echo "This is Button2 that is selected";
}
?>
<form method="post">
<input type="submit" name="button1" class="button" value="Button1" />
<input type="submit" name="button2" class="button" value="Button2" />
</form>
source: geeksforgeeks.org
You can simply do this. In php, you can determine button click by use of
if(isset($_Post['button_tag_name']){
echo "Button Clicked";
}
Therefore you should modify you code as follows:
<?php
if(isset($_Post['select']){
echo "select button clicked and select method should be executed";
}
if(isset($_Post['insert']){
echo "insert button clicked and insert method should be executed";
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<body>
<form action="functioncalling.php">
<input type="text" name="txt" />
<input type="submit" name="insert" value="insert" onclick="insert()" />
<input type="submit" name="select" value="select" onclick="select()" />
</form>
<script>
//This will be processed on the client side
function insert(){
window.alert("You click insert button");
}
function select(){
window.alert("You click insert button");
}
</script>
</body>
</html>

Ajax with multiple submit buttons

How can I change the code below so instead of a text input type with a submit button I want multiple submit buttons each with their own unique value? Everything I try just ends up with submit's value being undefined. Any help would be great!
Code source: Submit Search query & get Search result without refresh
<script type="text/javascript">
$(function() {
$("#lets_search").bind('submit',function() {
var value = $('#str').val();
$.post('db_query.php',{value:value}, function(data){
$("#search_results").html(data);
});
return false;
});
});
</script>
<form id="lets_search" action="" >
Search:<input type="text" name="str" id="str">
<input type="submit" value="send" name="send" id="send">
</form>
You can add multiple submit buttons and attach to all of them onclick event listener. When button was clicked - get the value and send with a POST request.
<script>
$(function(){
$('input[type=submit]').click(function(){
$.post('db_query.php', {value:$(this).val()}, function(data){
$("#search_results").html(data);
});
return false;
});
});
</script>
<form id="lets_search" action="">
<input type="submit" name="button1" value="hi"/>
<input type="submit" name="button2" value="bye"/>
</form>
If you want to use multiple submit buttons, you can catch the click event and determine which button was clicked. then run different Ajax submit. this also works when enter is hit.
//submit buttons
<form id="lets_search" action="" >
Search:<input type="text" name="str" id="str" />
<input type="submit" value="v1"/>
<input type="submit" value="v2"/>
//...more submit buttons
</form>
//submit func
$(function() {
$("#lets_search input[type=submit]").click(function() {
switch ($(this).val){
case 'v1':...;
case 'v2':...
}
});
});
Here is my version - which now looks very much like Bingjies because it was written while I was testing out his version
DEMO
<form id="lets_search" action="" >
Search:<input type="text" name="q" id="q">
<input type="submit" value="Google" name="send" id="google">
<input type="submit" value="Bing" name="send" id="bing">
</form>
$(function() {
$("#lets_search input[type=submit]").click(function() {
switch ($(this).val()) {
case "Bing" :
$("#lets_search").attr("action","http://www.bing.com/search");
break;
case "Google":
$("#lets_search").attr("action","https://www.google.com/search");
break;
}
});
});
Here, I would prefer to Vamsi's solution n Why not Sanjeev mk?
Give some extra thought on prefering the solution.
case: If there are mulitple submit buttons
If the user is in the text field and hits enter, the system will assume the first submit button was hit.
So, here, it would be good to go for not having mulitple submit
buttons for end user point of view
You can have multiple submit buttons in the form, no problem. They may have the same name, type etc, but just assign them different values. Like Submit Button 1 can have value="hi" and Button 2 can have value="bye".
Then when the action function is called for the button, all you have to do when entering the function is do a check with: $(this).val
HTML:
<input type="submit" name="button1" value="hi"/>
<input type="submit" name="button2" value="bye"/>
jQuery:
$(function() {
$("#lets_search").bind('submit',function() {
var value = $(this).val();
if(value == "hi")
do_something;
else
do_something_else;
});
});

Javascript confirm with PHP function afterward

I would like a way to have a confirm box pop up when a user clicks "delete" to remove a record.
Something like:
<script language="JavaScript" type="text/javascript" >
function confirmDelete() {
if(confirm("Would you like to delete the selected products?")) {
<?php
$allCheckBoxId = $_POST['checkbox'];
array_map ('mysql_real_escape_string', $allCheckBoxId);
$ids = implode(",", $allCheckBoxId);
$sql = "DELETE FROM products WHERE `id` IN ($ids)";
mysql_query($sql);
?>
}
}
</script>
With an onclick:
echo "<input type='submit' name='submit' value='Delete' onclick='confirmDelete()' />";
But I know it's not possible to be using Javascript & PHP together like this. Is there another way to do this? Maybe PHP has its own kind of confirm? Please give any ideas!
Thank you.
It is pretty easy to make use of AJAX for this case. Simply place your PHP in the scriptDelete.php file and make sure you pass the proper arguments and their values in the data property. For this example I just pass an id of 5.
<script type="text/javascript">
function confirmDelete() {
if (confirm('Are you sure you want to delete this?')) {
//Make ajax call
$.ajax({
url: "scriptDelete.php",
type: "POST",
data: {id : 5},
dataType: "html",
success: function() {
alert("It was succesfully deleted!");
}
});
}
}
</script>
<input type='submit' name='submit' value='Delete' onclick='return confirmDelete()' />
Another way would be to post the form back to its own page like:
<form method="post" action="yourpage.php">
<input type="submit" name="submit" value="delete" onclick="return confirm('Are you sure you want to delete this?')" />
</form>
So you simply post the form back to yourpage.php and on top of this page you do something like:
<?php
//Means the form was submitted
if ($_POST['submit']) {
$id = $_POST['idToDelete'];
$query = "DELETE FROM products WHERE id = " . mysql_real_escape_string($id);
mysql_query($query) or die(mysql_error());
}
?>
You should move the event to the form, and use onsubmit="confirmDelete()". If you return false within the ConfirmDelete function, the form submit is cancelled. If you return true, the form will get submitted like normal, and you can process it like a regular form on the server side.
<script type="text/javascript">
function confirmDelete() {
return window.confirm("Are you sure you want to delete this record?");
}
</script>
<form action="myDelete.php" onsubmit="confirmDelete()">
....inputs
<input type="submit" name="submit" value="Delete">
</form>
Then have regular processing code on the server side
The easiest way is to do a javascript function before you submit. If you click on false, the return will be false and it will not be submitted:
<form action="something.php" onSubmit="return confirm('Are you sure?');" method="post">
// Fields
// Fields
<input type="submit" name="Submit" class="button" value="Submit">
</form>
Easy way to confirm, instead of creating whole new function.
Do this
<input type="submit" name="Delete" onClick='return confirm("Sure you want Delete this Page?")' />
this will exactly respond the same way.
Ajax. Place your php in a separate file, and use ajax to send it the id you want to use in your query. I recommend jQuery .post

Confirm before a form submit

I have searched for an answer but couldn't find one!
I have a simple form,
<form action="adminprocess.php" method="POST">
<input type="submit" name="completeYes" value="Complete Transaction" />
</form>
How would I adjust this to confirm before processing the form?
I tried onclick, but couldn't get it working.
Any ideas?
UPDATE - What I now have.
<script type="text/javascript">
var el = document.getElementById('myCoolForm');
el.addEventListener('submit', function(){
return confirm('Are you sure you want to submit this form?');
}, false);
</script>
<form action="adminprocess.php" method="POST" id="myCoolForm">
<input type="submit" name="completeYes" value="Complete Transaction" />
</form>
HTML:
<form action="adminprocess.php" method="POST" id="myCoolForm">
<input type="submit" name="completeYes" value="Complete Transaction" />
</form>
JavaScript:
var el = document.getElementById('myCoolForm');
el.addEventListener('submit', function(){
return confirm('Are you sure you want to submit this form?');
}, false);
Edit: you can always use inline JS code like this:
<form action="adminprocess.php" method="POST" onsubmit="return confirm('Are you sure you want to submit this form?');">
<input type="submit" name="completeYes" value="Complete Transaction" />
</form>
<input type="submit" onclick="return confirm('Are you sure you want to do that?');">
The correct event is onSubmit() and it should be attached to the form. Although I think it's possible to use onClick, but onSubmit is the correct one.
If you're already using jQuery.. you can use an event handler to trigger before submission
$(document).ready(function() {
$("#formID").submit(function(){
// handle submission
});
});
Reference:
http://api.jquery.com/submit/
var submit = document.querySelector("input[type=submit]");
/* set onclick on submit input */
submit.setAttribute("onclick", "return test()");
//submit.addEventListener("click", test);
function test() {
if (confirm('Are you sure you want to submit this form?')) {
return true;
} else {
return false;
}
}
<form action="admin.php" method="POST">
<input type="submit" value="Submit" />
</form>
In my case, I didn't have a form ID and couldn't add inline in the form tag. I ended up with the following jQuery code
var form = $("form").first();
form.on('submit', function() {
return confirm('Are you sure you want to submit this form?');
});
if you have more then one submit buttons that do different actions you can do it this way.
<input TYPE=SUBMIT NAME="submitDelete" VALUE="Delete Script" onclick='return window.confirm("Are you sure you want to delete this?");'>

Categories