Submit PHP form does not pass php variable to javascript function - javascript

In a php application with I inherited (I am a php newbie) I have a php form with multiple includes. One of the includes has two tables set up and within each table is a form. The first form displays records retrieved from a MySQL database, so there could be 1 or more records returned. A while loop goes through the records and populates the controls with the data for each record (name, phone, email). The controls are named [fieldname<?php echo $line; ?>] - where $line starts at 1 and is incremented as the while loop goes through the records. This is working fine!
The problem comes when someone wants to edit one of the fields and submits the change. The form has an onsubmit="return validateForm(<?php echo $line; ?>);" I have checked to ensure that the $line variable does increment, but when it is sentto the javascript function "validateForm" the variable is not defined in the javasscript function. Originally I did I not pass the $line variable but the javascript function kept telling me that it could not get the value of the undefined element.
FIRST FORM CODE
<form action="admin_profiles_main_update.php" method="post" name="submit_order" enctype="multipart/form-data" onsubmit="return validateForm(<?php echo $line; ?>);">
<table border="0" cellspacing="0" cellpadding="0" class="forms">
<col width="20%"/>
<col width="80%"/>
<?php
if($user_access == 'National'){
$result = mysql_query("SELECT * FROM Profile ORDER BY profile_name");
}else{
$result = mysql_query("SELECT * FROM Profile WHERE profile_parent_region = '$user_profile' ORDER BY profile_name");
}
$line = 1;
while ($row_profile = mysql_fetch_array($result)){
$field_id = "_" . $line;
?>
<!-- LINE -->
<tr><td colspan="11"><hr class="view_line"></td></tr>
<!-- LINE -->
<tbody id="region<?php echo $field_id; ?>" >
<input class="field_long" name="profile_id<?php echo $field_id; ?>" id="profile_id<?php echo $field_id; ?>" type="hidden" value="<?php echo $row_profile[profile_id]; ?>"/>
<tr>
<td>
<label class="field_label" for="profile_parent_region<?php echo $field_id; ?>">Profile: </label>
</td>
<td align="left">
<select name="profile_parent_region<?php echo $field_id; ?>" id="profile_parent_region<?php echo $field_id; ?>" class="drop_med" >
<option></option>
<?php
if($user_access != 'National'){
$result_profile = mysql_query("Select Distinct profile_parent_region FROM profile where profile_parent_region = '$user_profile' ");
}else {
$result_profile = mysql_query("Select Distinct profile_parent_region FROM profile ORDER BY profile_parent_region ASC");
}
while($row = mysql_fetch_array($result_profile)){
echo '<option value ="'.$row['profile_parent_region'].'"';
if($row['profile_parent_region'] == $user_profile){
echo ' selected="selected"';
}
echo ' > ' . $row['profile_parent_region'] . '</option>';
}
?>
</select>
<span class="must_fill">* </span>
<label class="form_des" for="profile_parent_region<?php echo $field_id; ?>"></label>
</td>
</tr>
<tr>
<td>
<label class="field_label" for="profile_name<?php echo $field_id; ?>">Region: </label>
</td>
<td align="left">
<select name="profile_name<?php echo $field_id; ?>" id="profile_name<?php echo $field_id; ?>" class="drop_med" >
<option></option>
<?php
$parent_region = $row_profile['profile_name'];
if($user_access != 'National'){
$result_region = mysql_query("Select Distinct region FROM regions where parent_region = '$user_profile' ");
}else {
$result_region = mysql_query("Select Distinct region FROM regions ORDER BY region ASC");
}
while($row = mysql_fetch_array($result_region)){
echo '<option value ="'.$row['region'].'"';
if ($row['region'] == $parent_region){
echo ' selected="selected"';
}
echo ' >' . $row['region'] . '</option>';
}
?>
</select>
<span class="must_fill">* </span>
<label class="form_des" for="profile_name<?php echo $field_id; ?>"></label>
</td>
</tr>
<tr>
<td><label class="field_label" for="profile_manager<?php echo $field_id; ?>" >Region's Manager's Name: </label></td>
<td>
<input class="field_long" name="profile_manager<?php echo $field_id; ?>" id="profile_manager<?php echo $field_id; ?>" type="input" value="<?php echo $row_profile[profile_manager]; ?>"/>
<span class="must_fill">*</span>
<label class="form_des" for="profile_manager<?php echo $field_id; ?>"></label>
</td>
</tr>
<tr>
<td><label class="field_label" for="profile_phone<?php echo $field_id; ?>" >Region's Contact Number: </label></td>
<td>
<input class="field_long" name="profile_phone<?php echo $field_id; ?>" id="profile_phone<?php echo $field_id; ?>" type="input" value="<?php echo $row_profile[profile_phone]; ?>"/>
<span class="must_fill">*</span>
<label class="form_des" for="profile_phone<?php echo $field_id; ?>"></label>
</td>
</tr>
<tr>
<td><label class="field_label" for="profile_email<?php echo $field_id; ?>" >Region's Contact E-mail: </label></td>
<td>
<input class="field_long" name="profile_email<?php echo $field_id; ?>" id="profile_email<?php echo $field_id; ?>" type="input" value="<?php echo $row_profile[profile_email]; ?>"/>
<span class="must_fill">*</span>
<label class="form_des" for="profile_email">This email address will also be used to advise of files added to a submitted order.</label>
</td>
</tr>
<tr align="center">
<td colspan="2" class="loginrow">
<br />
<input name="Login <?php echo $field_id; ?>" id="Login<?php echo $field_id; ?>" value="Update Profile" type="submit" class="submit_button"/>
<br />
<br />
</td>
</tr>
</tbody>
<?php
$line++;
}
?>
</table>
</form>`
JAVASCRIPT FUNCTION - location in "parent" php form
function validateForm(lineNum) {
if (lineNum == null) {
var x = document.forms["submit_order"]["file_name"].value;
if (x == null || x == '') {
alert("Missing File Name.");
return false;
}
var x = document.forms["submit_order"]["file_for"].value;
if (x == null || x == '') {
alert("Missing File Type.");
return false;
}
var x = document.forms["submit_order"]["OrderForm"].value;
if (x == null || x == '') {
alert("Missing File to Upload.");
return false;
}
}

Your code
<form action="admin_profiles_main_update.php" method="post" name="submit_order" enctype="multipart/form-data" onsubmit="return validateForm(<?php echo $line; ?>);">
is outside the loop of linenumbers - so what should $line be, but null?
You either need to move the form into the loop of linenumbers, generating a form per row, or apply the logic on the submit button in question.
If you go with a form per row, you don't even need the linenumber thingy, cause then there would be exactly one value per variable in the submitted array. This would be the preferable way, cause you don't need to submit all values, when you want to modify one row.
And for the validation itself, you also wouldn't need it, cause you could refer to the form in question.
<?php
$line = 0;
while ($row_profile = mysql_fetch_array($result)){
$field_id = "_" . $line;
?>
<form action="admin_profiles_main_update.php" method="post" name="submit_order" enctype="multipart/form-data" onsubmit="return validateForm(<?php echo $line; ?>);">
<!-- do all the row stuff -->
</form>
<?$line++; }?>

Related

Getting the value of a select, with onchange and add row id number

Hi guys I'm having a hard time with this one please help me.
So I have an add row function where I can add dynamic rows to the form. My plan is to get the value of the Particulars with onchange event. So when you change the particular if will get the current value of the selected Particulars specifically on the selected row only.
The form looks like this:
So to test this out I'm trying to put the value in alert messages.
So this is the one I've done so far, I don't know if I'm making this correctly.
This is my html code.
<table class="table table-bordered" id="addSubPaymentTable">
<thead>
<tr>
<th >Particulars</th>
<th style="width:10%;"><button type="button" class="btn btn-success btn-sm" onclick="addPaymentRow()">Add Row</button></th>
</tr>
</thead>
<tbody>
<?php $arrayNumber = 0; for($x = 1; $x < 2; $x++) { ?>
<tr id="row<?php echo $x; ?>" class="<?php echo $arrayNumber; ?>">
<td class="form-group">
<select class="form-control particulars" name="subparticulars[<?php echo $x; ?>]" id="subparticulars<?php echo $x; ?>"
onchange="specificBalance('<?php echo $x; ?>')" /> //AS YOU CAN SEE I HAVE AN ONCHANGE EVENT HERE
<option value="">Select Particulars</option>
<?php foreach ($particularsData as $particulars)
{
?>
<option value="<?php echo $particulars['feetype_id']; ?>"> <?php echo $particulars['feetype_name']; ?> </option>
<?php
}
?>
</select>
<?php $arrayNumber++; } // /.foreach?>
</tbody>
So this is the function for the onchange event of Specific Balance
Javascript
// Get Specific Balance
function specificBalance(row = null)
{
var particular = $(this).val();
alert('Testing value is' +particular );
}
Please help me to get the value of the Particular, that is different in every row.
replace this line
<select class="form-control particulars" name="subparticulars[<?php echo $x; ?>]" id="subparticulars<?php echo $x; ?>"
onchange="specificBalance('')" />
with
<select class="form-control particulars" name="subparticulars[<?php echo $x; ?>]" id="subparticulars<?php echo $x; ?>"
onchange="specificBalance(this)" />
and in the jquery function use this
function specificBalance(row = null)
{
var particular = $(row).val();
alert('Testing value is' +particular );
}
Use this.value in onchange() function for select tag in HTML
<select class="form-control particulars" name="subparticulars[<?php echo $x; ?>]" id="subparticulars<?php echo $x; ?>"
onchange="specificBalance(this.value)" /> //AS YOU CAN SEE I HAVE AN ONCHANGE EVENT HERE
<option value="">Select Particulars</option>
<?php foreach ($particularsData as $particulars)
{
?>
<option value="<?php echo $particulars['feetype_id']; ?>"> <?php echo $particulars['feetype_name']; ?> </option>
<?php
}
?>
</select>

Set value of input element using javascript and get the value using php

Here I have a form and input element:
cart.php
<form id="cartform" action="cart.php?action=update&pd=<?php echo $row['product_id'] ?>" name="form1" method="post">
<?php
$query = "select * from cart where customer_id='$user' ";
$result = mysqli_query($con,$query);$payableamount = 0;$totalsavings = 0;
while($row = mysqli_fetch_array($result))
{
$productid = $row['product_id'];
$query2 = "select * from product where product_id='$productid'";
$result2 = mysqli_query($con,$query2);
while($row2=mysqli_fetch_array($result2))
{
?>
<input tpe="text" name="quantxt[]" id="quantxt" value="<?php echo $qty = $row['quantity']; ?>" onkeyup="showsubmit(<?php echo $row['cart_id'] ?>,<?php echo $row['product_id'] ?>)">
<input type="text" name="s1" id="s1" value=""/>
<input style="visibility:hidden;width:80px;border-radius:10px;background-color:green;border:none;padding:5px;color:white;"
type="submit"
name="sub_<?php echo $row['cart_id'] ?>"
id="sub_<?php echo $row['cart_id'] ?>"
value="UPDATE">
</table>
</form>
and the javascript is:
<script>
function showsubmit(id,prodid)
{
alert(id);
alert(prodid);
document.getElementById("sub_"+id).style.visibility ="visible";
document.getElementById("s1").value = prodid;
f = document.getElementById("s1").value;
alert("product id is:"+f);
}
</script>
when i am accessign the value of s1 element in cart2.php it gives nothing.
on next page s1 has no value,while i am expecting the value that is updated using javascript
$prod_id = $_POST['s1'];
echo "product id of clickable product is:".$prod_id."<br>";
this line:
<input type="text" name="s1" id="s1" value=""/>
is inside a loop. can you make sure that the loop only has one row returning? because if not, then you're creating multiple elements with same id which javascript can not catch properly. id is supposed to be unique. in the case of multiple same ids it'll catch the first match and stop.

how to make my page auto submit?

I have one payment page where payment values will fill automatically . so i don't want allow that page to user to submit . how can i do auto submit of my page ?
my code is
include "configaration/config.php";
// Merchant key here as provided by Payu
$MERCHANT_KEY = "4LbrUG";
// Merchant Salt as provided by Payu
$SALT = "EhDp06FA";
// End point - change to https://secure.payu.in for LIVE mode
$PAYU_BASE_URL = "https://test.payu.in";
$sucess_url = 'http://localhost/georamble/success.php';
$failur_url = 'http://localhost/georamble/failure.php';
$action = '';
$posted = array();
if(!empty($_POST)) {
foreach($_POST as $key => $value) {
$posted[$key] = $value;
}
}
$formError = 0;
if(empty($posted['txnid'])) {
// Generate random transaction id
$txnid = substr(hash('sha256', mt_rand() . microtime()), 0, 20);
} else {
$txnid = $posted['txnid'];
}
$hash = '';
// Hash Sequence
$hashSequence = "key|txnid|amount|productinfo|firstname|email|udf1|udf2|udf3|udf4|udf5|udf6|udf7|udf8|udf9|udf10";
if(empty($posted['hash']) && sizeof($posted) > 0) {
if(
empty($posted['key'])
|| empty($posted['txnid'])
|| empty($posted['amount'])
|| empty($posted['firstname'])
|| empty($posted['email'])
|| empty($posted['phone'])
|| empty($posted['productinfo'])
|| empty($posted['surl'])
|| empty($posted['furl'])
|| empty($posted['service_provider'])
) {
$formError = 1;
} else {
//$posted['productinfo'] = json_encode(json_decode('[{"name":"tutionfee","description":"","value":"500","isRequired":"false"},{"name":"developmentfee","description":"monthly tution fee","value":"1500","isRequired":"false"}]'));
$hashVarsSeq = explode('|', $hashSequence);
$hash_string = '';
foreach($hashVarsSeq as $hash_var) {
$hash_string .= isset($posted[$hash_var]) ? $posted[$hash_var] : '';
$hash_string .= '|';
}
$hash_string .= $SALT;
$hash = strtolower(hash('sha512', $hash_string));
$action = $PAYU_BASE_URL . '/_payment';
}
} elseif(!empty($posted['hash'])) {
$hash = $posted['hash'];
$action = $PAYU_BASE_URL . '/_payment';
}
//data from previous page
if(isset($_POST['submit1']))
{
$packname = $_POST['pname'];
$package_price = $_POST['advn_pay'];
$person = $_POST['person'];
$date = $_POST['date'];
$date = date('Y-m-d', strtotime($date));
$package_id = $_POST['pkid'];
$wallet_amount = $_POST['wallet_amount'];
$wallet_amount_use = 0;
if(isset($_POST['wuamount']))
{
$wallet_amount_use = $_POST['wuamount'];
}
$ref_no =rand(20,10000000);
$pay_status = "unpaid";
$req_status = "requested";
$wallet_update_money= $wallet_amount - $wallet_amount_use;
$update= mysql_query("UPDATE wallet SET amount='$wallet_update_money' WHERE user_id='$login_session'");
//fetch a user name
$query = mysql_query("select * from user where user_id= '$login_session'");
if(!$query)
{
echo "error";
}
while($row=mysql_fetch_array($query))
{
$name = $row['first_name'];
$email = $row['email'];
$contact_number = $row['contact_number'];
}
$p_name=$_POST['name'];
$age=$_POST['age'];
for($i=0;$i<count($p_name);$i++)
{
$qry_add="INSERT INTO trvel_person_details (ref_user_id,ref_cus_name,cus_name,cus_age,travel_date)
VALUES ('$login_session', '$name','$p_name[$i] ','$age[$i]','$date')";
if(!mysql_query($qry_add))
{
die('Error: ' . mysql_error());
}
}
$total_amount= $package_price - $wallet_amount_use ; //total amount
$qry="INSERT INTO pack_req (user_id,user_name,package_id,pacakage_name,amount,date_jrny,no_person,refrence_number,payment_status,req_status)
VALUES ('$login_session', '$name','$package_id ','$packname','$total_amount','$date ','$person','$ref_no','$pay_status ','$req_status')";
if(!mysql_query($qry))
{
die('Error: ' . mysql_error());
}
}
?>
<html>
<head>
<script>
var hash = '<?php echo $hash ?>';
function submitPayuForm() {
if(hash == '') {
return;
}
var payuForm = document.forms.payuForm;
payuForm.submit();
}
</script>
</head>
<body onload="submitPayuForm()">
<h2>PayU Form</h2>
<br/>
<?php if($formError) { ?>
<span style="color:red">Please fill all mandatory fields.</span>
<br/>
<br/>
<?php } ?>
<form action="<?php echo $action; ?>" method="post" id="payuForm" name="payuForm">
<input type="hidden" name="key" value="<?php echo $MERCHANT_KEY ?>" />
<input type="hidden" name="hash" value="<?php echo $hash ?>"/>
<input type="hidden" name="txnid" value="<?php echo $txnid ?>" />
<table>
<tr>
<td><b>Mandatory Parameters</b></td>
</tr>
<tr>
<td>Amount: </td>
<td><input name="amount" id="amount" value="<?php echo (empty($posted['amount'])) ? $total_amount : $posted['amount']; ?>" /></td>
<td>First Name: </td>
<td><input name="firstname" id="firstname" value="<?php echo (empty($posted['firstname'])) ? $name : $posted['firstname']; ?>" /></td>
</tr>
<tr>
<td>Email: </td>
<td><input name="email" id="email" value="<?php echo (empty($posted['email'])) ? $email : $posted['email']; ?>" /></td>
<td>Phone: </td>
<td><input name="phone" value="<?php echo (empty($posted['phone'])) ? $contact_number : $posted['phone']; ?>" /></td>
<td>transation Id: </td>
<td><input name="txnid" value="<?php echo (empty($posted['txnid'])) ? $ref_no : $posted['txnid']; ?>" /></td>
</tr>
<tr>
<td>Product Info: </td>
<td colspan="3"><textarea name="productinfo"><?php echo (empty($posted['productinfo'])) ? $packname : $posted['productinfo'] ?></textarea></td>
</tr>
<tr>
<td>Success URI: </td>
<td colspan="3"><input name="surl" value="<?php echo (empty($posted['surl'])) ? $sucess_url : $posted['surl'] ?>" size="64" /></td>
</tr>
<tr>
<td>Failure URI: </td>
<td colspan="3"><input name="furl" value="<?php echo (empty($posted['furl'])) ? $failur_url : $posted['furl'] ?>" size="64" /></td>
</tr>
<tr>
<td colspan="3"><input type="hidden" name="service_provider" value="payu_paisa" size="64" /></td>
</tr>
<?php if(!$hash) { ?>
<td colspan="4"><input type="submit" value="Submit" /></td>
<?php } ?>
</tr>
</table>
</form>
even i have tried with one javascript to auto submit the form
<script type="text/javascript">
$(document).ready(function(){
$("#payuForm").submit();
});
</script>
but still its not redirecting . how can do this . any hint or help . sorry for my bad english
Create a hidden submit type button(i.e. display:none;), after page load through jquery click on it automatically(i.e. $('#submit').click() ), Create a function for clicking on submit button, call it after page loads...
EDIT:
HTML:
<form ...>
...
<input type="submit" id="submit" style="display:none;" />
</form>
Javascript:
function submit_click(){
$("#submit").click();
}
Now, when your auto form populating data's function called, call this function in last line submit_click();
try this
<script>
$(document).ready(function(){
$('#payuForm').trigger('submit');
})
</script>
Remember that some browser do not let you trigger the "submit" event if you have not an ENABLED submit button (be it an input or button, with type="submit")
Thus, you need to a button in the form, and if you don't want it to be shown, you can add
#button {
display: none;
visibility: hidden;
}

Can only post first result of while loop

I am using a while loop to display results from a query. The while loop is working fine. In hidden fields I would like to post the values of userID and accessID to the user details page. I am submitting the form using javascript to submit from a link. My problem is that regardless of the username I click I can only post the values for the first displayed record. What am I doing wrong?
The code:
<?php
while($row = $result->fetch_array()) { ?>
<form method="post" action="edit_user.php" id="userForm">
<tr>
<td>
<?php echo $row['firstname'].' '.$row['surname']; ?>
<input type="hidden" name="userID" value="<?php echo $row['userID']; ?>" />
<input type="hidden" name="accessID" value="<?php echo $row['accessID']; ?>" />
</td>
</tr>
</form>
<?php } ?>
The javascript used for submitting the form:
function submitForm() {
var form = document.getElementById("userForm");
form.submit();
}
Thank you.
EDIT - I don't want to pass the values in the url.
you are generating multiple <form>s inside loop, move your <form> outside while loop, like:
<form method="post" action="edit_user.php" id="userForm">
<?php
while($row = $result->fetch_array()) { ?>
<tr>
<td>
<?php echo $row['firstname'].' '.$row['surname']; ?>
<input type="hidden" name="userID[]" value="<?php echo $row['userID']; ?>" />
<input type="hidden" name="accessID[]" value="<?php echo $row['accessID']; ?>" />
</td>
</tr>
<?php } ?>
Submit
</form>
You're running into trouble because of this line
var form = document.getElementById("userForm");
In Javascript and HTML, an ID is supposed to be unique to a certain DOM element. In this case, you've got a whole load of form tags that have the same ID. You need to give each form a different ID, and then pass that ID to the submitForm function.
For example:
<?php
$id = 0;
while($row = $result->fetch_array()) { ?>
$id++;
<form method="post" action="edit_user.php" id="<?php echo "userForm".$id ?>">
<tr>
<td>
<?php echo $row['firstname'].' '.$row['surname']; ?>
<input type="hidden" name="userID" value="<?php echo $row['userID']; ?>" />
<input type="hidden" name="accessID" value="<?php echo $row['accessID']; ?>" />
</td>
</tr>
</form>
<?php } ?>
and then
function submitForm(id) {
var form = document.getElementById(id);
form.submit();
}
edit: how do I php? :D

handling multiple buttons with same name and value in one form

I have multiple submit buttons on a site. They used to move elements up and down and I want to be them in one whole form in case of the user changes meanwhile some other values so everything is saved. The Problem now is I need the element ID of the button which was clicked.
So here is the code in the loop :
div class="form-order"><?php echo $elements[$z]['element_order']; ?> </div>
<input type="submit" name="edit_form_operation" value="▲" class="button-primary"
<?php if($elements[$z]['element_order'] == 1) echo 'disabled="disabled"'; ?> /><br />
<input type="submit" name="edit_form_operation" value="▼" class="button-primary"
<?php
$highest_element = $fdb->get_element_highest_order($form[$i]['form_id']);
if($elements[$z]['element_order'] == $highest_element) echo 'disabled="disabled"'; ?> />
And onclick of that specific button in the for loop he should write this code first so I know which element has to be moved
echo '<input type="hidden" name="change_element_id" value="'.$elements[$z]['element_id'].'" >';
I'm also open for another solution of this problem.
Ok I solved it like that now
Here you process the input:
// Select Operation
if(isset($_POST['edit_form_operation_up'])) {
echo "move up id ";
$operation = array_keys($_POST['edit_form_operation_up']);
echo $operation['0'];
}
else if(isset($_POST['edit_form_operation_down'])) {
echo "move down id ";
$operation = array_keys($_POST['edit_form_operation_down']);
echo $operation['0'];
}
And this is in the for loop for infinite Elements the input with same value and name.
<?php $elements = $fdb->get_elements($form[$i]['form_id']);
for($z = 0; $z < sizeof($elements); $z++) {
?>
<tr>
<td><div class="form-order"><?php echo $elements[$z]['element_order']; ?> </div>
<input type="submit" name="edit_form_operation_up[<?php echo $elements[$z]['element_id']; ?>]" value="▲" class="button-primary"
<?php if($elements[$z]['element_order'] == 1) echo 'disabled="disabled"'; ?> /><br />
<input type="submit" name="edit_form_operation_down[<?php echo $elements[$z]['element_id']; ?>]" value="▼" class="button-primary"
<?php
$highest_element = $fdb->get_element_highest_order($form[$i]['form_id']);
if($elements[$z]['element_order'] == $highest_element) echo 'disabled="disabled"'; ?> />
</td>
<td><?php echo $elements[$z]['element_id']; ?> </td>
<td></td>
<td></td>
</tr>
<?php } ?>
In case of somebody finds this topic and want to find a good solution.
Greetings

Categories