Combining two or more submit buttons into one - javascript

I have submit buttons for different section of the webpage. The submit button is used to update the forms and database with the text value in the form fields. Currently, each submit button updates the forms (tied to their respective PKEY id, "consideration_no") only in their own sections. I want to update all the sections forms with one button click.
As you can see from the code below, there are 2 submit buttons. I have tried to link two together through IDs but it did not work for me.
// Include config file
require_once "config.php";
// Define variables and initialize with empty values
$question = $answer = "";
$question_err = $answer_err = "";
if(isset($_POST["dg_no"]) && !empty($_POST["dg_no"])){
//counter for array
$counter = 0;
// Get hidden input value
$dg_no = $_POST['dg_no'];
$consideration_no = $_REQUEST['consideration_no'];
$answer = $_POST['answer'];
// Check input errors before inserting in database
if(empty($answer_err)){
// Validate address address
$input_answer = trim($_POST["answer"]);
if(empty($input_answer)){
$answer_err = "Please enter an answer.";
} else{
$answer = $input_answer;
$answer1[$counter] = $input_answer;
}
// Prepare an Submit statement
$sql = 'Update "PDPC".consideration SET answer=:answer WHERE consideration_no = :consideration_no';
if($stmt = $pdo->prepare($sql)){
$stmt->bindParam(":answer", $param_answer);
$stmt->bindParam(":consideration_no", $param_consideration_no);
//$stmt->bindParam(":dg_no", $param_dg_no);
//Set Parameter in while loop, hence new set of parameter for every new form is created and executed.
//Could change the counter loop to a dynamic loop with foreach array.
while ($counter<15){
$param_answer = $answer[$counter];
$param_consideration_no = $consideration_no[$counter];
$stmt->execute();
//$param_dg_no = $dg_no;
// Attempt to execute the prepared statement
//debugggggg
/* $message = $consideration_no[$counter];
$message1 = $answer[$counter];
$message2 = 'lol';
echo "<script type='text/javascript'>alert('$message, $message1, $message2 ');</script>"; */
$counter++;
//apparently redirecting can be placed in the loop, and fields will still get changed.
//header("location: home1.php?dm_no=".$_GET["dm_no"]);
header("location: home1.php?dm_no=".$_GET["dm_no"]);
}
}
if($stmt->execute()){
//Records Submitd successfully. Redirect to landing page
header("location: home1.php?dm_no=".$_GET["dm_no"]);
exit();
} else{
echo "Something went wrong. Please try again later.";
}
// Close statement
unset($stmt);
}
// Close connection
unset($pdo);
} else{
/* --- DISPLAY/READ TABLE, SEE SECTIONS AND ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- */
// Check existence of dg_no parameter before processing further
if(isset($_GET["dg_no"]) && !empty(trim($_GET["dg_no"]))){
// Get URL parameter
$dg_no = trim($_GET["dg_no"]);
// Prepare a select statement
$sql = 'SELECT * FROM "PDPC".consideration WHERE (dg_fkey = :dg_no AND code_no = 1) ORDER BY consideration_no';
if($stmt = $pdo->prepare($sql)){
// Bind variables to the prepared statement as parameters
$stmt->bindParam(":dg_no", $param_no);
// Set parameters
//$param_no = $dg_no;
$param_no = trim($_GET["dg_no"]);
// Attempt to execute the prepared statement
if($stmt->execute()){
if($stmt->rowCount() > 0){
SubSection($subsection1_1); //Consent Collection Subsection
while($row = $stmt->fetch()){
// Retrieve individual field value
$consideration_no = $row["consideration_no"];
$question = $row["question"];
$answer = $row["answer"];
$dg_no = $_GET['dg_no'];
//...time to show the questions and answers with the while loop...
?>
<form action="<?php echo htmlspecialchars(basename($_SERVER['REQUEST_URI'])); ?>" method="post">
<div class="form-group <?php echo (!empty($answer_err)) ? 'has-error' : ''; ?>">
<label><?php echo $question; ?></label>
<input type="text" name="answer[]" class="form-control" value="<?php echo $answer; ?>">
<span class="help-block"><?php echo $answer_err;?></span>
<input type="hidden" name="consideration_no[]" value="<?php echo $consideration_no; ?>"/>
<input type="hidden" name="dg_no" value="<?php echo $dg_no; ?>"/>
</div>
<?php
}
//...after the loop, show the Submit and Cancel button, coz we only need 1 set each section.
?>
<input type="Submit" name = "$consideration_no[]" class="btn btn-primary" value="Submit">
Cancel
</form>
</div>
<?php
}
}
else{
echo "Oops! Something went wrong. Please try again later.";
}
}
Section($section2); //Collection section
// Prepare a select statement
$sql = 'SELECT * FROM "PDPC".consideration WHERE (dg_fkey = :dg_no AND code_no = 2) ORDER BY consideration_no';
if($stmt = $pdo->prepare($sql)){
// Bind variables to the prepared statement as parameters
$stmt->bindParam(":dg_no", $param_no);
// Set parameters
//$param_no = $dg_no;
$param_no = trim($_GET["dg_no"]);
// Attempt to execute the prepared statement
if($stmt->execute()){
if($stmt->rowCount() > 0){
SubSection($subsection2); //Consent Collection Subsection
while($row = $stmt->fetch()){
// Retrieve individual field value
$consideration_no = $row["consideration_no"];
$question = $row["question"];
$answer = $row["answer"];
$dg_no = $_GET['dg_no'];
//...time to show the questions and answers with the while loop...
?>
<form action="<?php echo htmlspecialchars(basename($_SERVER['REQUEST_URI'])); ?>" method="post">
<div class="form-group <?php echo (!empty($answer_err)) ? 'has-error' : ''; ?>">
<label><?php echo $question; ?></label>
<input type="text" name="answer[]" class="form-control" value="<?php echo $answer; ?>">
<span class="help-block"><?php echo $answer_err;?></span>
<input type="hidden" name="consideration_no[]" value="<?php echo $consideration_no; ?>"/>
<input type="hidden" name="dg_no" value="<?php echo $dg_no; ?>"/>
</div>
<?php
}
//...after the loop, show the Submit and Cancel button, coz we only need 1 set each section.
?>
<input type="Submit" name = "$consideration_no[]" class="btn btn-primary" value="Submit">
Cancel
</form>
</div>
<?php
}
}
else{
echo "Oops! Something went wrong. Please try again later.";
}
}
// Close statement
unset($stmt);
// Close connection
unset($pdo);
}
else{
// URL doesn't contain dg_no parameter. Redirect to error page
header("location: error.php");
exit();
}
}
I want it to update all the fields, in different sections, with one submit button

your code was bit difficult to read, but from what i understood you are trying to combine two or more form submissions into one. It's quiet simple
<form method="POST" action="save.php">
<input type=text name=name[] />
<input type=text name=name[] />
</form>
by using the [] to identify the input element you can have multiple values with the same name where you can access them from the PHP script as an array.
For example the above example will produce an array as follows
<?php
print_r($_POST['name']); //("name" => Array....
is this clear enough for you? if not drop a comment, i will explain more. As a side note i do recommend you look into using template engine, and also a framework in your coding project.

Here's what I see when i separate the html into a new file. I tried to remove the excess forms but when I open the last collapsible section, it instantly executes a submit action and brings me back to the home page.
<button class="collapsible"><?php echo $section ?></button>
<div class="content">
<button class="collapsible"><?php echo $subsection ?></button>
<form action="<?php echo htmlspecialchars(basename($_SERVER['REQUEST_URI'])); ?>" method="post">
<?php
//while loop start
?>
<form action="<?php echo htmlspecialchars(basename($_SERVER['REQUEST_URI'])); ?>" method="post">
<div class="form-group <?php echo (!empty($answer_err)) ? 'has-error' : ''; ?>">
<label><?php echo $question; ?></label>
<input type="text" name="answer[]" class="form-control" value="<?php echo $answer; ?>">
<span class="help-block"><?php echo $answer_err;?></span>
<input type="hidden" name="consideration_no[]" value="<?php echo $consideration_no; ?>"/>
<input type="hidden" name="dg_no" value="<?php echo $dg_no; ?>"/>
</div>
<?php
//while loop ends
?>
<input type="Submit" name = "$consideration_no[]" class="btn btn-primary" value="Submit">
Cancel
</form>
</div>
<?php
//while loop start
?>
<form action="<?php echo htmlspecialchars(basename($_SERVER['REQUEST_URI'])); ?>" method="post">
<div class="form-group <?php echo (!empty($answer_err)) ? 'has-error' : ''; ?>">
<label><?php echo $question; ?></label>
<input type="text" name="answer[]" class="form-control" value="<?php echo $answer; ?>">
<span class="help-block"><?php echo $answer_err;?></span>
<input type="hidden" name="consideration_no[]" value="<?php echo $consideration_no; ?>"/>
<input type="hidden" name="dg_no" value="<?php echo $dg_no; ?>"/>
</div>
<?php
//while loop ends
?>
<input type="Submit" name = "$consideration_no[]" class="btn btn-primary" value="Submit">
Cancel
</form>
</div>
<?php

Related

Form insertion into database not working asynchronously

I'm trying to get a text area's value inserted asynchrnously into my database, however it keeps redirecting to the PHP processing page, and echoing a result there. How would I get it to echo the result of the PHP script on the current HTML page?
JS:
$("#sub").click(function() {
$.post( $("#text").attr("action"), $("#text :input").serializeArray(),
function(info) { $("#result").html(info);});
});
$("#text").submit( function(){
return false;
})
PHP:
$sql = "UPDATE text
SET text_content = ? WHERE (id = 40) AND (number = $Number);";
$stmt = mysqli_stmt_init($connection);
if (!mysqli_stmt_prepare($stmt, $sql))
{
header("Location: ../create_text.php?error&prepare1111");
exit();
}
else
{
$stmt->bind_param("s", $content);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
$connection->close();
echo "successfully saved";
}
HTML:
<form type="text" method="post" onSubmit="return validateText(); toHTML();" action="processing.php" id="text">
<textarea name="content" rows="45" id="auto-expand" class="text-box" type="text"><?php echo stripslashes($content) ?></textarea>
<input type="hidden" name="id" id="id" value="<?php echo $id ?>">
<input type="hidden" name="number" id="number" value="<?php echo $number ?>">
<input type="hidden" name="updated" value="<?php echo $updated ?>">
<button type="submit" id="sub" name="submit">Save</button>
<button type="button" onClick="validateText(); toHTML();">Check</button>
<span id="result"></span>
</form>
Any help would be so great! :)
Try preventDefault:
$("#text").submit( function(e){
e.preventDefault();
})

'Click' action conflict with `submit` action

So, I have the following setup with a Submit button that saves any changes.
<div class="mysite-body">
<?php do_action('mysite_pre_form_message'); ?>
<form action="" method="post" data-action="<?php echo $template; ?>">
<input type="hidden" name="user_id-<?php echo $i; ?>" id="user_id-<?php echo $i; ?>" value="<?php echo $user_id; ?>" />
<?php
if (!isset($user_id)) $user_id = 0;
$hook_args = array_merge($args, array('user_id' => $user_id, 'unique_id' => $i));
do_action('mysite_before_fields', $hook_args);
?>
<?php foreach( mysite_fields_group_by_template( $template, $args["{$template}_group"] ) as $key => $array ) { ?>
<?php if ($array) echo mysite_edit_field( $key, $array, $i, $args, $user_id ) ?>
<?php } ?>
<?php
if (!isset($user_id)) $user_id = 0;
$hook_args = array_merge($args, array('user_id' => $user_id, 'unique_id' => $i));
do_action('mysite_after_fields', $hook_args);
?>
<?php
if (!isset($user_id)) $user_id = 0;
$hook_args = array_merge($args, array('user_id' => $user_id, 'unique_id' => $i));
do_action('mysite_before_form_submit', $hook_args);
?>
<?php if ( mysite_can_delete_user($user_id) || $mysite->request_verification($user_id) || isset( $args["{$template}_button_primary"] ) || isset( $args["{$template}_button_secondary"] ) ) { ?>
<div class="mysite-field mysite-submit mysite-column" id="A">
<?php if (isset($args["{$template}_button_primary"]) ) { ?>
<input type="submit" value="<?php echo $args["{$template}_button_primary"]; ?>" class="mysite-button" />
<?php } ?>
<?php if (isset( $args["{$template}_button_mysite"] )) { ?>
<input type="button" value="<?php echo $args["{$template}_button_secondary"]; ?>" class="mysite-button secondary" data-template="<?php echo $args["{$template}_button_action"]; ?>" />
<?php } ?>
<?php if ( $mysite->request_verification($user_id) ) { ?>
<input type="button" value="<?php _e('Request Verification','mysite'); ?>" class="popup-request_verify mysite-button secondary" data-up_username="<?php echo $mysite->id_to_member($user_id); ?>" />
<?php } ?>
<?php if ( mysite_can_delete_user($user_id) ) { ?>
<input type="button" value="<?php _e('Delete Profile','mysite'); ?>" class="mysite-button red" data-template="delete" data-up_username="<?php echo $mysite->id_to_member($user_id); ?>" />
<?php } ?>
<img src="<?php echo $mysite->skin_url(); ?>loading.gif" alt="" class="mysite-loading" />
<div class="mysite-clear"></div>
</div>
<?php } ?>
</form>
</div>
<?php } ?>
Then following javascript:
<script>// <![CDATA[
jQuery("#A").click(function(){
jQuery("#B").trigger('click');
return false; });
// ]]></script>
And id="B" is on a header as a simple anchor button:
<div class="startskip"><a id="B" href="http://mysite/start/item">Skip</a></div>
What I want to achieve is that when a submit button is clicked, then the skip button is also triggered and the user will be redirected to the next page.
Of course, I am going to put setTimeoutso there is enough time to save instead of instant redirect.
However, the submit button becomes not-responsive when I add the javascript.
So, it seems that there is a javascript conflict between the click function and submit function. (Without the javascript, the submit button works).
By looking the code, could you guys figure out what the problem is and how to solve it?
Thanks!
I read an article on this previously which explains why it doesn't work - but have lost the link, I'll see if I can find it an update this post tomorrow. But the summary would be to say that the jQuery trigger click method triggers the event handler for the element, it does not trigger the browsers default behaviour i.e. following a link.
You have two choices, if you must use jQuery, then you can use this:
window.location = $('#B').attr('href');
Another option is to use pure JS:
document.getElementById("a_link").click();
In this case, I would go for the second option since I think it is more clear and readable - but that's subjective!
The return false inside the click handler cancels the original click and that is why the form doesn't get submitted.
I don't think it's possible to run any script after the form submission though. You could try submitting the form with ajax and on success do the redirect.

how can I submit the value of an unchecked checkbox

I have a user edit page with a set of user permissions. Each permission is basically a checkbox. If checked the user has the permission if unchecked the user does not have the permission. So if I want to remove a permission I would uncheck the box and vice versa to add a permission.
I got everything to work using a hidden input, but the problem that I am having is that it is submitting both the hidden input and the checkbox value. For example even if I don't make a change and click the update button, I get a message that reads:
Removed access from 1 permission levels
Added access to 1 permission levels
I will show you my code below. Something to keep in mind is that each input calls a different function.
Here is the inputs:
<ul class="list-group permission-summary-rows">
<?php //List of permission levels user is apart of
foreach ($permissionData as $v1) {
if(isset($userPermission[$v1['id']])){
?>
<li class="list-group-item">
<?php echo $v1['name']; ?>
<span class="pull-right">
<input type="hidden" name="removePermission[<?php echo $v1['id'] ?>]" id="removePermission[<?php echo $v1['id'] ?>]" value="<?php echo $v1['id'] ?>" >
<input type="checkbox" checked data-toggle="switch" name="addPermission[<?php echo $v1['id'] ?>]" id="addPermission[<?php echo $v1['id'] ?>]" value="<?php echo $v1['id'] ?>" >
</span>
</li>
<?php
}
}
?>
<?php //List of permission levels user is not apart of
foreach ($permissionData as $v1) {
if(!isset($userPermission[$v1['id']])){
?>
<li class="list-group-item">
<?php echo $v1['name']; ?>
<span class="pull-right">
<input type="checkbox" data-toggle="switch" name="addPermission[<?php echo $v1['id'] ?>]" id="addPermission[<?php echo $v1['id'] ?>]" value="<?php echo $v1['id'] ?>" >
</span>
</li>
<?php
}
}
?>
Here is the PHP:
//Remove permission level
if(!empty($_POST['removePermission'])) {
$remove = $_POST['removePermission'];
if ($deletion_count = removePermission($remove, $userId)) {
$successes[] = lang("ACCOUNT_PERMISSION_REMOVED", array ($deletion_count));
} else {
$errors[] = lang("SQL_ERROR");
}
}
// Add permission level
if(!empty($_POST['addPermission'])) {
$add = $_POST['addPermission'];
if ($addition_count = addPermission($add, $userId)) {
$successes[] = lang("ACCOUNT_PERMISSION_ADDED", array ($addition_count));
} else {
$errors[] = lang("SQL_ERROR");
}
}
Even if I add the hidden input underneath the checkbox input I receive the same message. I know it has something to do with using different functions so can anyone guide me in the right direction? Should I use some JS code to find if it is checked or not?
If you want to use that trick... you must to name the same both arrays!
<input type="hidden" name="Permission[<?php echo $v1['id'] ?>]" id="removePermission[<?php echo $v1['id'] ?>]" value="0" >
<input type="checkbox" <?php echo ($v1['id']=='YES')?'checked':'' ?> data-toggle="switch" name="Permission[<?php echo $v1['id'] ?>]" id="AddPermission[<?php echo $v1['id'] ?>]" value="1" >
Take a look at "$v1['id']=='YES'" and use the correct comparison. Remember, name must be the same and a value of 0 will be disabled and 1 enabled.
Good luck.
Both the hidden input and the checkbox values are submitted because they're of different input types.
You don't need to hardcode checked explicitly. Write a php if loop to check if the user has permission and echo "checked" accordingly.
//EDIT:
This is the code I would use for this problem. Just overwrite all rules for the user in the DB. Only thing you have to know is the amount of rules (represented by the constant).
<html>
<body>
<?PHP
define("NUMBEROFINPUTS",5);
if(isset($_GET["permissions"])){
$dbperms = array();
foreach($_GET["permissions"] as $permission) {
$dbperms[$permission] = 1;
}
//$dbperms: 0->Input is not set; 1-> Input is set
for($i=0;$i<NUMBEROFINPUTS;$i++){
if(isset($dbperms[$i])) {
echo "Input ".$i." is set<br />";
}
else{
echo "Input ".$i." is not set<br />";
}
}
}
else {
echo '<form>';
for($i = 0;$i<NUMBEROFINPUTS;$i++){
echo 'Permission '.$i.': <input type="checkbox" name="permissions[]" value="'.$i.'" checked /><br />';
}
echo '<input type="submit" /></form>';
}
?>
</body>
</html>
I hope I could help.
use this in jQuery
$("input[type=checkbox]:not(:checked)").attr("value");
well for get and do some with all unchecked checkbox you can collect it into array... and send it on submit to server
var aUnchecked = new Array();
$("input[type=checkbox]:not(:checked)").each(fucntoin(){
aUnchecked.push($(this).attr("name"));
}

SESSION variable slow to update textfield in php

I have a form, contained 3 fields, which when the submit button in submitted,
it will changes the session variable values according to the fields, in this case there are 3 variables. then i echo back the variable onto the fields.
For the first time submit, it stores the value beautifully and display in the fields correctly, the problem is that, when i submit the second time, the values are still the same. after i refresh the page, then the values in the fields are changed.
this is partially the codes i'm using now.
<?php
session_start();?>
?>
<form name="form1" id="form1" action="">
<input type="text" name="acc1" value="<?php echo $_SESSION['acc_main']" />
<input type="text" name="acc2" value="<?php echo $_SESSION['acc_id']" />
<input type="text" name="acc3" value="<?php echo $_SESSION['acc_cat']" />
<input type="submit" name="submit">
</form>
<?php
if(isset($_POST['submit']) != '')
{
$_SESSION['acc_main'] = $_POST['acc1'];
$_SESSION['acc_id'] = $_POST['acc2'];
$_SESSION['acc_cat'] = $_POST['acc3'];
}
?>
After i refresh(F5), then the value changed. i want it to be, when i clicked the submit button, it will change to the new value.
PHP Code:
<?php
if(isset($_POST['submit']) != '')
{
$_SESSION['acc_main'] = $_POST['acc1'];
$_SESSION['acc_id'] = $_POST['acc2'];
$_SESSION['acc_cat'] = $_POST['acc3'];
echo '<script type="text/javascript">'
, 'jsfunctionToPrintUpdatedValues();'
, '</script>'
;
}
?>
Javascript Sample Code
function jsfunctionToPrintUpdatedValues()
{
/* retrieve the updated session variables in javascript variables */
var acc_main_js = <?php echo $_SESSION['acc_main']?>
var acc_id_js = <?php echo $_SESSION['acc_id']?>
var acc_cat_js = <?php echo $_SESSION['acc_cat']?>
document.getElementById("main").value=acc_main_js;
document.getElementById("id").value=acc_main_js;
document.getElementById("cat").value=acc_main_js;
}
in the input fields you have to write like this
`
Below
`
<input type="text" name="acc1" value="<?php if(isset($_SESSION['acc_main'])) echo $_SESSION['acc_main']" />
Use if(isset($_POST['submit']) != '') before the form. Change your code to this:
<?php
session_start();
if(isset($_POST['submit']) != '')
{
$_SESSION['acc_main'] = $_POST['acc1'];
$_SESSION['acc_id'] = $_POST['acc2'];
$_SESSION['acc_cat'] = $_POST['acc3'];
?>
<form name="form1" id="form1" action="">
<input type="text" name="acc1" value="<?php echo $_SESSION['acc_main']" />
<input type="text" name="acc2" value="<?php echo $_SESSION['acc_id']" />
<input type="text" name="acc3" value="<?php echo $_SESSION['acc_cat']" />
<input type="submit" name="submit">
</form>
<?php
}else{
?>
<form name="form1" id="form1" action="">
<input type="text" name="acc1" value="<?php echo $_SESSION['acc_main']" />
<input type="text" name="acc2" value="<?php echo $_SESSION['acc_id']" />
<input type="text" name="acc3" value="<?php echo $_SESSION['acc_cat']" />
<input type="submit" name="submit">
<?php } ?>

HTML fields are shown empty when they contain value

I have an edit user form. When a user visits this page, details regarding to him are shown in the fields. He can edit the fields if he want to, and then submit the form.
<form id="edit-form"method="post" action="<?php echo $_SERVER['PHP_SELF'] ; ?>">
<input id="txtalias" name="txtalias" type="text" value="<?php echo 1; ?>" >
<input type="text" id="txthour_max" name="txthour_max" value="<?php echo 2; ?>" >chk1
<input type="text" id="txtminute_max" name="txtminute_max" value="<?php echo 3; ?>" >chk2
<input type="text" id="txthour_def" name="txthour_def" value="<?php echo 4; ?>" >chk3
<input type="text" id="txtminute_def" name="txtminute_def" value="<?php echo 5; ?>">chk4
<button id="serv_butn" type="submit">Save settings</button>
</form>
This is the PHP part:
if((isset($_POST['txtalias']))&&(isset($_POST['txthour_max']))&&(isset($_POST['txtminute_max']))&&(isset($_POST['txthour_def']))&&(isset($_POST['txtminute_def'])))
{
$z = $_POST['txtalias'];
$y= $_POST['txthour_max'];
$w=$_POST['txtminute_max'];
$x = $_POST['txthour_def'];
$u = $_POST['txtminute_def'];
}
And if the user, doesn't want to make any changes & he clicks the submit button,
Notice: Undefined variable
is shown, even though the text fields have values stored in them.
How to solve this issue?
<input id="txtalias" name="txtalias" type="text" value="<?php echo $env; ?>" >
If this is a textbox, and when i click submit button, following notice is shown
Notice: Undefined variable: env in C:\wamp\www\project\mypage.php on line 212 Call Stack #TimeMemoryFunctionLocation 10.0010163472{main}( )..\mypage.php:0 ">
your
<input id="txtalias" name="txtalias" type="text" value="<?php echo $env; ?>">
$env has not define;
please check when you declare $env

Categories

Resources