As I have come to learn the hard way that serialize() does not handle the values of submit buttons, I’ve now come to a point where I need some help in order to solve my issue.
What I want to accomplish is the following:
Submit a form when one of many buttons are pressed, using the value of the pressed button to determine the action.
I’m using PHP to process the data once the form is submitted
For example, when the button labeled Save is pressed, the form is submitted but since the save button was pressed, only session variables are set with values from the form elements using PHP.
When the button labeled Submit is pressed, the form is submitted once again, but since the submit button was pressed, the form is actually processed and the data can be added to a database.
But without knowing the value of the button, I can’t do something like this:
if (isset($_POST['send'])) {
if ($_POST['send'] == 'save') {
// Set session variables
} elseif ($_POST['send'] == 'send') {
// Insert all data into database
}
}
I’m now trying to figure out a way to overcome this obstacle.
This is what I have right now that works like it should in terms of functionality (it saves data to session variable), but only for not submit button elements such as text boxes.
<?php session_start(); ?>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script>
$(function () {
$('#test').on('submit', function (e) {
$.ajax({
type: 'post',
url: 'actions.php',
data: $('#test').serialize(),
success: function () {
location.reload();
}
});
e.preventDefault();
});
});
</script>
</head>
<body>
<div style="margin-top: 1200px;"></div>
<?php
if (isset($_SESSION['email'])) {
echo $_SESSION['email'];
unset($_SESSION['email']);
}
?>
<form action="" method="post" id="test">
<input type="text" name="email" />
<button type="submit" name="send_form" value="send">Add To Databse</button>
<button type="submit" name="send_form" value="save">Save</button>
</form>>
</body>
</html>
actions.php
if ($_POST['email'] != "") {
$_SESSION['email'] = $_POST['email'];
}
Using the existing code, the form is submitted causing the session variable to be set and is then displayed to the user without a visual page reload (meaning the page remains where it was during submission).
One method I’ve been playing around with is to create hidden form fields with different values that appears depending on what button to press, and use that field to determine the action of the submission. However, I’m not really sure how to proceed. At this point, any ideas are welcome.