how can I prevent preventDefault from removing the submit button from $_POST? - php

I have a form with two submit buttons:
<form method="POST">
<input type="submit" name="Update" value="Update"/>
<input type="submit" name="Submit" value="Delete"/>
</form>
I need to manipulate some things on the form before it is submitted so I used this jQuery:
$('form').submit(function (e) {
e.originalEvent && e.preventDefault();
//manipulate stuff
this.submit();
});
The problem is, I need to know which button was clicked at the back end but
$_POST['Submit'] and $_POST['Delete']
are both undefined. It seems the inputs are removed from the post array by the jQuery.
What would be a good way to solve that issue?

I would go about it with two event handlers for each button and a hidden input to tell the php which action is requested. As an addition I would advice you to checkout Ajax.
Code is as follows:
$('#update').click(function (e) {
e.originalEvent && e.preventDefault();
//manipulate stuff
$("form").append("<input type = 'hidden' name = 'action' value = 'update' />");
this.submit();
});
$('#delete').click(function (e) {
e.originalEvent && e.preventDefault();
//manipulate stuff
$("form").append("<input type = 'hidden' name = 'action' value = 'delete' />");
this.submit();
});
And on the back-end side you'll get what was submitted in $_POST['action'] that is either going to be "update" or "delete"

I would suggest you add an action as input type hidden and two buttons that may or may not be a part of the form. Add event listeners to the buttons to know when those are clicked and change input action field accordignly, then submit the form.
First, give your form a name or id, rather id.
<input type="hidden" name="action" value=""/>
<input type="submit" name="Update" value="Update"/>
<input type="submit" name="Submit" value="Delete"/>
$('input[type="submit"][name="Update"]').click(function() {
$('input[type="hidden"][name="action"]').val('Update');
$("#something").submit();
});
$('input[type="submit"][name="Submit"]').click(function() {
$('input[type="hidden"][name="action"]').val('Delete');
$("#something").submit();
});

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.

button click validation ajax

I am using a button to submit a form with ajax..all works fine..But I need to check if the button is clicked in server side page..How to do it??Any help appreciated..Thanks..
<form>
some values
</form>
<input type="button" name="delete" id="delete" value="Delete"/><br/>
<input type="button" name="edit" id="edit" value="Edit"/><br/>
Script
$("#edit").click(function(event) {
event.preventDefault();
$("#form1").submit()
});
$("#form1").validate({
debug: false,
rules: {
plid:"required",
},
messages: {
plid: "Please select a pack name id..",
},
submitHandler: function(form) {
$.ajax
({
type: "POST",
url: "aanew.php",
data: $('#form1').serialize(),
cache: false,
success: function(response) {
$('#result1').html(response);
}
});
}
});
I want to carry any attribute to check if my button is set... Thanks again..
The form value passes successfully, but I need to check the button status in another page..
First of all your buttons in page should be in form tag like this
<form>
some values
<input type="button" name="delete" id="delete" value="Delete"/><br/>
<input type="button" name="edit" id="edit" value="Edit"/><br/>
</form>
then Simply just use isset function
if (isset($_POST['delete']))
or
if (isset($_POST['edit']))
whatever you click
Put this field on the form, and the other inputs too like others have already pointed
<input type="hidden" name="check_click" value="1">
then in server side
if ((isset($_POST['check_click'])) && ($_POST['check_click'] == 1))
{
//The form was clicked
}
UPDATE:
if you want for each button
if ((isset($_POST['check_click'])) && ($_POST['check_click'] == 1))
{
//The form was clicked
if (isset($_POST['delete']))
{
//delete has some value
}
if (isset($_POST['edit']))
{
//edit has some value
}
}
You can insert into the form tag two submit buttons with different values. And on server side check - which one has come. This approach is also make adding Ajax functionality easier - because you can now add the same callback on this two buttons/

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;
});
});

Prevent Default for Ajax created form

I am getting the form on click from a file called test.php which contains the following:
<form method="post" class="adminTM">
<input type="hidden" name="execID" value="<?=$_POST['exec']?>" />
<input type="hidden" name="fromTM" value="<?=$_POST['TM']?>" />
<input type="text" name="toTM" value="<?=$_POST['TM']?>" />
<input type="hidden" name="symbol" value="<?=$_POST['symbol']?>" />
<button class="submitTM">SUBMIT</button>
</form>
The javascript looks like so:
$(function(){
$('.adminTMClick').live('click', function(e){
$(this).data('TM', this.innerHTML);
$.post('test.php', $(this).data(), function(data){
$(data).dialog({
modal: true,
beforeClose: function(){
$(this).remove();
}
});
console.log($('.adminTM'));
console.log($('.submitTM'));
});
});
$('.submitTM').live('click', function(e){
//originally had .adminTM with submit which failed
e.preventdefault();
alert('i am here');
return false;
});
});
How do i make it so that the form DOES NOT do the default submit action when the submit button is clicked?
Here is a fiddle that demonstrates basically what I am doing (i had to change it a bit because of the way jsfiddle works): http://jsfiddle.net/maniator/tQVnV/show/
You should use the submit() event on the form instead of the click() on the submit, since pressing enter will still submit the form (bypassing the submit button).
This should properly prevent the form from doing the default submit:
$('.adminTM').live('submit', function(e) {
// execute custom code
console.log("submit event fired");
// prevent default submit
return false;
});
jsFiddle: http://jsfiddle.net/bjorn/tQVnV/11/

submitting form with two buttons

I have 2 buttons in HTML form. And both of them should submit the form. I would need to capture which button has been clicked so i can use it to perform different actions based on which button was clicked.
I am able to submit the form with both the buttons but how would i capture which button was clicked in the php file .
<INPUT type="button" name="submit" class="button" class="element_2" value="firstbutton">
<INPUT type="button" name="submit1" class="button" class="element_2" value="second button.. ">
i am using post method in Jquery to submit the form. How can i check which HTML button was clicked in server side php script
You could use a hidden element here, something like this:
<input type="hidden" id="submittedBy" name="submittedBy">
Your current .submit() handler using .serialize() and $.post() should work, just update the hidden field when clicking either button, for example:
$("form :submit").click(function() {
$("#submittedBy").val(this.name);
});
Then in PHP just check that $_POST["submittedBy"] == "submit" or "submit1" to see which caused it.
The alternative is to have the click handler POST and add in the value between .serializeArray() and when $.param() is called, like this:
$("form :submit").click(function() {
var data = $(this.form).serializeArray();
data.push({ name: 'submittedBy', value: this.name });
$.post("myPage.php", data, function(result) {
//do something
});
return false; //prevent normal form submission, even with the .submit() handler
});
Just do this,
HTML
<button type="submit" name="action[update]" value="1">Update</button>
<button type="submit" name="action[delete]" value="1">Delete</button>
PHP
$action = isset($_POST['action']['update']) ? 'update' : 'delete';
You CAN'T depend on JavaScript to tell you wich button was clicked, if user has JavaScript disabled, your form is broken.
You could try using the isset function
if(isset($_POST['submit'])){
echo "first button was clicked";
}
Or to detect the second one was clicked:
if(isset($_POST['submit1'])){
echo "second button.. was clicked";
}
I would capture all the events on the page using:
$(document).click(function (obj) {
if ('equipmentSetup' === obj.target.id) {
$('#form').submit();
}
....
Then add an if statement looking for the "id" of the button you want. Don't use the name or id "submit". I forgot why but I remember it caused problem for me.
You could try changing the buttons to type="button" and give them ids. With that, you can use the jquery line (not able to check my syntax below, but think i've got it right)
$('form button').click(function(){
if($(this).attr('id') = "button1"){ ...button 1 clicked}
..process form here..
});
would that do it?

Categories