Javascript confirm with PHP function afterward - php

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

Related

isset validation in PHP failing when form submitted through jquery

My if(isset) validation is returning false after I have submitted the form through jQuery ,however works fine when done without jquery. Reason I am using jQuery is because I need to submit multiple forms:
Button
<input class="btn btn-primary" type ="submit" id="myButton"
name="create_record" value="Submit 1">
jQuery:
<script>
$(document).ready(function () {
$("#myButton").click(function (event) {
event.preventDefault();
$("#form1").submit();
// $("#form2").submit();
});
});
</script>
PHP
<?php
if(isset($_POST['create_record'])){
$ecode = $_POST['ecode'];
$ename = $_POST['ename'];
$date = $_POST['date'];
$jobRole = $_POST['jobRole'];
}else{
echo "did not receive anything";
}
?>
Always getting "did not receive anything" . Can someone please help.
The submit button value only gets sent if the form is submitted in the traditional way by a button click. Since you are submitting the form via javascript, you'll need to explicitly include the submit button's value or validate your post data in some other way. If you need the value of the specific button that was clicked, something like this should work:
$("#myButton").click(function (event) {
event.preventDefault();
var el = '<input type="hidden" name="' + $(this).prop('name') + '" value="' + $(this).val() + '">';
$("#form1").append(el).submit();
});
As for your objective of submitting multiple forms at once, I believe it's impossible without using ajax as discussed here. If you need guidance on how to do that, better to open a new question.
Your code, isset($_POST['create_record']) maybe false or it didn't receive any values. If your query is only in one PHP file together with your jQuery, you need to check first your algorithm or use var_dump() for testing. Second, If it didn't work, make an alternative solution for it. Do the proper HTML code when using form or make another PHP file for receiving post purpose only.
<form action="directory_to_another_file" method="POST">
<!-- SOME INPUTS HERE -->
<input type="submit" value="Submit 1" name="create_record">
</form>
Try to test all of your codes.
You have to set form method as "POST" type and if you want to receive the form data in same page then empty the "action" key otherwise give the target link.
<?php
if(isset($_POST['create_record'])){
print_r($_POST);
}
?>
<form action="" method="POST" id="form1">
<input type="text" name="create_record" value="Submit 1"/>
</form>
Submit
<script>
$(function(){
$("#myButton").click(function (event) {
event.preventDefault();
$("#form1").submit();
});
})
</script>
Let me know if it's work for you.

Looping through multiple forms

I am extracting sql data to a another php table used for a site. For each row in the table I have a button to delete or edit that specific row. The edit button works fine but I have been having issues with the delete button. As of now the delete button only deletes the first row of the table and not the row that has been selected for deletion.
Here is a sample of the table:
while($row = mysqli_fetch_array($result)){
<tr>
<td>'.($row['some_data']).'</td>
<td>
<form action="meeting_update_milestone.php" method="POST">
<input type="hidden" name="mile_id" value="'.$row['id'].'" />
<input type="submit" value="EDIT" />
</form>
</td>
<td>
<form id="meeting_delete_item">
<input type="hidden" name="mile_id" value="'.$row['id'].'" />
<input type="button" onclick="delete_meeting_item()" value="DELETE" />
</form>
</td>
</tr>';
}
This data is being sent to an ajax call:
function delete_meeting_item(){
var x = confirm("Are you sure you want to permanetly delete this item?");
if (x){
$.ajax({
type: "POST",
url: "meeting_delete_item.php",
data: $('#meeting_delete_item').serialize(),
cache: false,
success: function(result){
alert(result);
}
})//end ajax
}
else{
return false;
}
}
As you can tell I loop through the rows creating multiple forms with the same id. I think this is creating the issue here? If so how can I fix it by keeping the same formatting. I believe the forms have to have a unique name, but I am not sure how to implement this into the ajax data string.
I can't comment on the validity of your php code, but as you say, the id values have to be unique. In this instance, I don't believe the ID really makes much difference to what you are trying to achieve.
Remove the id and the inline onclick event:
while($row = mysqli_fetch_array($result)){
<tr>
<td>'.($row['some_data']).'</td>
<td>
<form action="meeting_update_milestone.php" method="POST">
<input type="hidden" name="mile_id" value="'.$row['id'].'" />
<input type="submit" value="EDIT" />
</form>
</td>
<td>
<form>
<input type="hidden" name="mile_id" value="'.$row['id'].'" />
<input type="button" class="delete" value="DELETE" />
</form>
</td>
</tr>';
}
And bind it using jQuery. I added a class to be able to get a selector to the delete button.
$(document).ready(function(){
$('.delete').click(function(){
var x = confirm("Are you sure you want to permanetly delete this item?");
if (x){
$.ajax({
type: "POST",
url: "meeting_delete_item.php",
data: $(this).closest(form).serialize(),
cache: false,
success: function(result){
alert(result);
}
})//end ajax
}
else{
return false;
}
}
}
On click of the delete button, we get the nearest form and serialize the data for that form.
Your problem is here
$('#meeting_delete_item').serialize()
You should use something else to determine that the current line is.
HTML FORM PART FOR DELETE
<form id="meeting_delete_item">
<input type="button" onclick="delete_meeting_item('.$row['id'].')" value="DELETE" />
</form>
JS
function delete_meeting_item(deleteId){
var x = confirm("Are you sure you want to permanetly delete this item?");
if (x){
$.ajax({
type: "POST",
url: "meeting_delete_item.php",
data: {mile_id: deleteId},
cache: false,
success: function(result){
alert(result);
}
})//end ajax
}
else{
return false;
}
}
Outside of your loop, you can keep a counter: $x = 0 and use that when generating the form: <form id="meeting_delete_item"'.$x.'>. At the end of the loop, increment the counter for the next iteration ++$x. In your javascript, you will probably retrieve the id according to the button that is pressed.
Sample Forms:
<form id="myForm1">
<button>Click me!</button>
</form>
<form id="myForm2">
<button>Click me!</button>
</form>
Sample JavaScript:
$('form button').click(function(e) {
var $form = $(this).closest('form');
console.log($form.attr('id'));
return false; //stop form submission
});
Live demo (click).
Also, inline js (like onclick in your html) has never been good practice. Instead, follow the example in my sample code and bind the click function with javascript. For more on this subject, read some of these results: https://www.google.com/search?q=Why+is+inline+js+bad%3F

php change link to submit button

I have this jquery script that refreshes a div tag on my page:
$(function() {
$(".loadlink").click(function(event) {
event.preventDefault();
$("#result").load($(this).attr("href"));
});
});
A link click activates it, but I want to change it to a button. Currently I have:
<a class="loadlink" href="crimes_result.php?id=<? echo $id ?>">do job<a>
Instead I want a submit button, like: (this doesnt work-doesn't send the id)
<input type="submit" class="loadlink" value=" do job " onClick="location.href='crimes2.php?id=<? echo $id ?>';this.disabled=true;">
What am I doing wrong?
Leverage the data attribute and jQuery's data method. I think this is what you are trying to do.
html
<input type="submit" class="loadlink" data-url="crimes2.php?id=<?php echo $id ?>" />
javasript
$(function() {
$(".loadlink").click(function(event) {
event.preventDefault();
$("#result").load($(this).data('url'));
});
});
You may try
<input type="submit" class="loadlink" value=" do job " onClick="loadlink('crimes2.php?id=<? echo $id ?>'); this.disabled=true;">
And JavaScript
function loadlink(href)
{
$("#result").load(href);
}
Set the URL as a data-attribute in your button markup and read it like this in your JS:
$(function() {
$(".loadlink").click(function(event) {
event.preventDefault();
$("#result").load($(this).attr("data-href"));
this.disabled = true;
});
});
This requires your button to look more like this:
<input type="submit" class="loadlink" value=" do job " data-href="crimes2.php?id=<? echo $id ?>';">
The reason it's not working, is that the submit button does not have a href attribute.
You need to add the value you want to go to (the url) to the button and change your javascript accordingly or just change the link to make it look like a button.
use a hidden field which will store the url to load:
<input type="hidden" name="myUrl" value="crimes_result.php?id=<? echo $id ?>" />
and use the javascript:
$(function() {
$(".loadlink").click(function(event) {
event.preventDefault();
$("#result").load($('input[name=myUrl]').val());
});
});

1 form 2 actions

<form name="ipladder" id="ipladder" action="/checkuser/master-check.php" method="post">
<input name="ipladder" type="text" id="ipladder" />
<input type="submit" name="submit" id="botton" value="Check" />
<input type="submit" name="geo" id="botton"/>
</input></form>
I have one input box and 2 submit buttons. When the first button is pressed (name="submit") I want it to go to master-check.php as specified in the action= parameter. However when the geo button is pressed, I want it to go through a different action which I haven't specified because I didn't know how to do so.
What can I do so I can have 1 input box and 2 buttons each processing through different action files?
Maybe you can try altering the "action" parameter of your form in an onclick method that, after changing, submits the form. Something like:
$('#btn1').click(function(){
$('#ipladder').attr('action', 'location1.php');
$('#ipladder').submit();
});
$('#btn2').click(function(){
$('#ipladder').attr('action', 'location2.php');
$('#ipladder').submit();
});
Another option of couse, is to post to 1 page...and handle the logic (some redirect or whatever) there.
Make a single PHP script that handles which button has been pressed and then redirects to correct PHP handling script (after correcting what Juhana commented of course).
Instead of using form action, I think you can use Ajax to achieve what you want. It will be something like this:
<form name="ipladder" id="ipladder" method="post">
<input type="text" id="ipladder2" name="ipladder2" />
<input type="button" id="button1" name="submit" value="Check" onclick="action1()" />
<input type="button" id="button2" name="geo" value="Something else" onclick="action2()" />
</form>
and in the header you can define 2 Ajax functions:
<script type="text/javascript">
function action1()
{
$.ajax({
type: "POST",
url: "/checkuser/master-check.php",
data: $("ipladder2").val(),
success: //do something,
dataType: //return dataType
});
}
function action2()
{
$.ajax({
type: "POST",
url: //other URL,
data: $("ipladder2").val(),
success: //do something else,
dataType: //return dataType
});
}
</script>
Well you can achieve your goal by single php page as well.
on mastercheck.php something like this can help you.
<?php
if($_POST['submit'])
{
//you code for master-check.php
}
else if(isset($_POST['geo']))
{
//you code for other page goes here
}
?>

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