submitting form with two buttons - php

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?

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.

WordPress - A submission confirmation on modal pop up

I am trying to get a popup submit button working but I haven't quite found the solution I'm looking for.
I am using the jquery modal plugin to show the client the content of their changes before they submit them. However, when I try submitting, nothing happens. The submit button exists on the pop up, whereas the .modify button is the button that opens it. I am having no issues with the pop up itself.
My console test is printing so I know there's nothing wrong with my event listener. Maybe it has something to do with event.preventDefault()?
Thanks in advance.
Here is my code
Back end
jQuery(".modify").click(function() {
event.preventDefault();
var submit = confirm('Are you sure?');
<?php
$post_ids = array();
while($author_entry_posts->have_posts()) : $author_entry_posts->the_post();
array_push($post_ids, get_the_ID());
endwhile;
?>
if (submit == true) {
var data = {
'action': 'modalcall',
'postid': <?php echo json_encode($post_ids)?>,
'userid': <?php echo get_current_user_id() ?>
};
jQuery.post(ajaxurl, data, function(response) {
jQuery(response).appendTo('body').modal();
//Script which handles the submit button on the modal pop-up
jQuery(".modal_submit").click(function() {
console.log("test");
jQuery().submit();
});
});
} else {
return false;
}
});
Front end
<input type="submit" name="submit" value="Submit" class="button modal_submit">
In your handler for click on modal submit you are not defining which form needs to be submitted.
jQuery(".modal_submit").click(function() {
console.log("test");
jQuery().submit(); // you are not defining which form to submit.
});
Instead the <input type="submit" name="submit" value="Submit" class="button modal_submit"> needs to be inside a form which needs to be submitted by calling jquery submit on it.
jQuery(".modal_submit").click(function() {
console.log("test");
$(this).closest('form').submit(); // asking to submit the form which contains this button
});

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

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

Run PHP code after button click but without refreshing page

I have a form in HTML to apply a Discount Coupon to a current shopping cart.
I would like the user to just click on APPLY (after entering the coupon code) and then without refreshing the page, to have some PHP code run so it computes the corresponding discount.
Here is my form:
<form action="">
<input type="text" name="couponCode">
<input type="submit" value="Apply">
</form>
PHP to be run:
if (isset($_REQUEST['couponCode']) && $_REQUEST['couponCode']!='')
{
$couponCode = $_REQUEST['couponCode'];
if ($couponCode == "TEST1")
{
$discount=0.2;
}
}
How would this be done using javascript?
You need to use either the onsubmit event of the form or the onclick event of the button.
In the event handler, you assemble a URL and "get" it. For example:
<script type="text/JavaScript">
function submitCouponCode()
{
var textbox = document.getElementById("couponCode");
var url =
"https://www.example.com/script.php?couponCode=" + encodeURIComponent(textbox.value);
// get the URL
http = new XMLHttpRequest();
http.open("GET", url, true);
http.send(null);
// prevent form from submitting
return false;
}
</script>
<form action="" onsubmit="return submitCouponCode();">
<input type="text" id="couponCode">
<input type="submit" value="Apply">
</form>
Use jQuery AJAX. When it's complete, refresh your page as needed.
You can use Jquery to do an AJAX post you your PHP script, and then use JS to change the contents of the calling page.
http://api.jquery.com/jQuery.post/
It's simple with jQuery. You just have to use the right tag. If you use an "a" tag the page will refresh.
<button id="MyButton">Click Me!</button>
<script>
$("#MyButton").click( function(){
$.post("somefile.php");
});
</script>

How to identify the change of value in a particular text field after submit button click

I want to update marks of a particular student in particular subject out of eight subjects.
My question is how to identify that a particular text box value has been changed after clicking submit button, then the updation task is forwarded to the update.php. Please give me your valuable answer. Thanks in advance.
Since your button click event is occured on client side, you can identify it by client side scripting.
<script lang='javascript'>
$(document).ready(function(){
$('#button_id').click(function(){
/* Do whatever you want to do right here*/
});
});
</script>
For identifying the change on text box after clicking submit button, first change the input type from submit to button as as soon as you click submit, it redirects the page.
<input type='button' onClick='your_function()' id='btn_submit' name='btn_submit' />
<input type='text' id='text_box' name='text_box' onchange='$('#flag_value_changes').val('1')' />
<input type='hidden' id='flag_value_changes' name='flag_value_changes' />
<script lang='javascript'>
function your_function()
{
flag_value_changes = $('#flag_value_changes').val();
if(flag_value_changes == 1)
alert('Value has been changed');
else
alert('Value has not been changed');
}
</script>
the scripting language can help you in this situation.use javascript for the event of the submit button click.
do whatever you needed in that event..happy coding :)
As stated by hsuk. You can do it on the client side using javascript.
I've provided an example using textarea and no inline javascript.
HTML
<div>
<textarea id= "math">Math</textarea>
<textarea id= "english">English</textarea>
<textarea id= "french">French</textarea>
<textarea id= "spanish">Spanish</textarea>
<input type="submit" value="submit"/>
</div>
And the following javascript(Using Jquery)
$(document).ready(function(){
var initialValues = [];
var i = 0;
//Gets values on load
$("div textarea").each(function(){
initialValues[i] = this.id+" had "+$(this).val();
i++;
});
//Checks values on click
$("input").click(function(){
i = 0;
$("div textarea").each(function(){
value = initialValues[i].split(" ");
if($(this).val() != value[2]){
alert(value[0] + " was Changed.");
}
i++;
});
});
});
DEMO

Categories