Jump to content
Larry Ullman's Book Forums

Passing Javascript Variable


Recommended Posts

Hello all,

I am struggling with passing a javascript variable to my php after i submit. I tried using $phpVar=$_GET["javascript"] and have the form element as <form name="form1" method="post" action="brv.php?javascrip='.javascript_variable.'''>

 

Any ideas?

Link to comment
Share on other sites

For starters, in your action, you have javascrip without the "t". Even with that corrected, I suspect that if you look at your HTML source code, you'll see no value there, as you'll need to have JavaScript write the value of the variable there. But if you're doing that, I'd have JavaScript create the value as a hidden form input. It'd be much cleaner that way.

Link to comment
Share on other sites

Larry, no offense, but I don't think that answer is gonna help kobena too much.

 

kobena, to answer your question, there are two main ways to pass a JavaScript variable value to a PHP script.

 

The more sensible option would be to use Ajax. I recommend Larry's Ajax book for details.

 

The slightly odder (but still plausible) method would be to, as Larry mentions, use JavaScript to create a new DOM element that is a hidden input element in a form, and then submit the form.

 

However, I must admit, the second option is rather odd. Learning how to use Ajax, or using the Ajax function in jQuery would probably be your best bet.

Link to comment
Share on other sites

Thanks for your responses. HartleySan, i would read the Ajax stuff but i want to easily pass the value to the php page after the submit button which i thought is within the remit of php. Maybe i need to be more specific: i used jquery to create dynamic textboxes and populates the values in an array called comp_msg. Below is the details about my code:

 

 

 

<?php # brv.php

 

$page_title = 'BRV Calibration Certificate Details ';

include ('includes/header.html');

require_once ('includes/config.inc.php');

require_once (MYSQL);

 

 

if (isset($_SESSION['first_name'])) {

 

 

$first_name=$_SESSION['first_name'];

$last_name=$_SESSION['last_name'];

 

$user=$first_name.' '.$last_name;

 

 

 

//echo ',<h1/>';

 

echo '<h2>Add a BRV Calibration Certificate Details</h2>';

 

 

if (isset($_POST['submitted']))

 

{

echo "working well";

 

 

$errors = array(); // Initialize an error array.

//$phpVar= array();

//$Kobena=$_GET('comp_msg');

 

 

 

 

// Check for a valid dailydelivery ID, through GET or POST:

if ( (isset($_GET['comp_msg'])))

{ // From view_dailydeliveries.php

$id = $_GET['comp_msg'];

echo $id;

}

elseif ( (isset($_POST['comp_msg'])) )

{ // Form submission.

$id = $_POST['comp_msg'];

}

else

{ // No valid ID, kill the script.

 

echo '<p class="error">This page has been accessed in error1.</p>';

include ('includes/footer.html');

exit();

}

 

 

 

// Check for a transporter Selection:

if (empty($_POST['transporter_id'])||($_POST['transporter_id']=="NULL"))

{

$errors[] = 'You forgot to Select the transporter';

}

else

{

$transporter_id = mysqli_real_escape_string($dbc, trim($_POST['transporter_id']));

}

 

// Check for a omc Selection:

if (empty($_POST['omc_id'])||($_POST['omc_id']=="NULL"))

{

$errors[] = 'You forgot to Select the omc';

}

else

{

$omc_id = mysqli_real_escape_string($dbc, trim($_POST['omc_id']));

}

 

$current_date=ISSET($_REQUEST["date1"])? $_REQUEST["date1"] : $errors[] = 'Please select a valid expiration date!';

 

/*$month= (!empty($_POST['MM'])) ? mysqli_real_escape_string($dbc,trim($_POST['MM'])) : $errors[] = 'Please select a valid month!';

$day= (!empty($_POST['DD'])) ? mysqli_real_escape_string($dbc,trim($_POST['DD'])) : $errors[] = 'Please select a valid day!';

$year= (!empty($_POST['YYYY'])) ? mysqli_real_escape_string($dbc,trim($_POST['YYYY'])) : $errors[] = 'Please select a valid year!';*/

 

 

 

 

 

 

$brv_number= (!empty($_POST['brv_number'])) ? mysqli_real_escape_string($dbc,trim($_POST['brv_number'])) : $errors[] = 'Please provide vehicle number';

 

// Check for a quantity Selection:

if (!empty($_POST['brv_capacity']))

{

$brv_capacity =mysqli_real_escape_string($dbc, trim($_POST['brv_capacity']));

$brv_capacity=str_replace(",","",$brv_capacity);

//echo $brv_capacity;

}

else

{

$errors[] = 'Please provide the capacity of brv';

}

 

 

 

 

 

// Check for compartment selection:

if (empty($_POST['number_of_compartments '])||($_POST['number_of_compartments ']=="NULL"))

{

$errors[] = 'You forgot to Select the a value representing the number of compartments';

}

else

{

$number_of_compartments = mysqli_real_escape_string($dbc, trim($_POST['number_of_compartments ']));

echo "number of compartments is $number_of_compartments";

}

 

 

// Check for ullage Selection:

if (empty($_POST['ullage_levels '])||($_POST['ullage_levels ']=="NULL"))

{

$errors[] = 'You forgot to Select the a value representing the number of ullage levels';

}

else

{

$ullage_levels = mysqli_real_escape_string($dbc, trim($_POST['ullage_levels ']));

echo "ullage level is $ullage_levels";

}

 

 

 

// Check for Ccmments

if (empty($_POST['comments']))

{

$comments = NULL;

}

else

{

$comments = mysqli_real_escape_string($dbc, trim($_POST['comments']));

}

 

 

 

 

 

 

 

 

 

if (empty($errors))

{ // If everything's OK.

//create date

$modified_by=$user;

$dailydelivery_date=$year.'-'.$month.'-'.$day;

 

//discharge

$discharge_date=$discharge_year.'-'.$discharge_month.'-'.$discharge_day;

$temperature_change=$temperature-$discharge_temperature;

 

if (($product_id==1) && ($product_id!="NULL")) //ie product is AGO

{

$apparent_loss=0.00082*$brv_capacity*$temperature_change;

$current_price_per_litre=1.5346;

}

elseif (($product_id==2) && ($product_name!="NULL")) //ie product is SUPER

{

$apparent_loss=0.00122*$brv_capacity*$temperature_change;

$current_price_per_litre=1.5207;

}

 

elseif (($product_id==3) && ($product_name!="NULL")) //ie product is MOGAS

{

$apparent_loss=0.00122*$brv_capacity*$temperature_change;

$current_price_per_litre=1.5207;

}

else

{

$apparent_loss=0.00;

}

$physical_loss=$total_loss-$apparent_loss;

 

if ($physical_loss>0)

$actual_loss=$physical_loss;

else

{

$actual_loss=0.00;

}

$loss_value=$price_per_litre*$actual_loss;

$amount_claimed=$brv_capacity*$rate;

$amount_to_be_paid=$amount_claimed-$loss_value;

//$amount_paid=$amount_claimed;

 

 

 

$q = 'INSERT INTO dailydeliveries(depot_id,bdc_id,transporter_id,omc_id,product_id,

region_id,quantity_id,dailydelivery_date,serial_number,waybill_number,brv_number,

collection_order_number,destination,modified_by,temperature,

initial_reading,final_reading,variance,comments,driver,delivery_time,date_entered,

 

discharge_date,discharge_temperature,total_loss,apparent_loss,physical_loss,actual_loss,

price_per_litre,rate,loss_value,brv_capacity,amount_claimed,amount_to_be_paid)

VALUES (?,?,?,?,?, ?,?,?,?,?, ?,?,?,?,?, ?,?,?,?,?,?,NOW(),?,?,?,?,?,?, ?,?,?,?,?,?)';//22 in total

 

$stmt = mysqli_prepare($dbc, $q);

mysqli_stmt_bind_param($stmt, 'iiiiiiissssssssdddsssssdddddddddd',$depot_id,$bdc_id,$transporter_id,$omc_id,$product_id,

$region_id,$quantity_id,$dailydelivery_date,$serial_number,$waybill_number,

$brv_number,$collection_order_number,$destination,$modified_by,$temperature,

$initial_reading,$final_reading,$variance,$comments,$driver,$delivery_time,

 

$discharge_date,$discharge_temperature,$total_loss,$apparent_loss,$physical_loss,$actual_loss,

$price_per_litre,$rate,$loss_value,$brv_capacity,$amount_claimed,$amount_to_be_paid);

 

 

 

mysqli_stmt_execute($stmt);

 

 

// Check the results....

if (mysqli_stmt_affected_rows($stmt) == 1)

{

echo '<p>The Daily delivery record has been added</p>';

$a = mysqli_stmt_insert_id($stmt); // Get the artist ID.

}

else

{ // Error!

$errors[] = 'The Delivery record could not be added to the database! Please try again';

$errors[] = 'It is possible you have submitted the data for the Delivery already ';

 

}

 

}

 

// Check for any errors and print them:

if ( !empty($errors) && is_array($errors) )

{

echo '<h1>Error!</h1>

<p style="font-weight: bold; color: #C00">The following error(s) occurred:<br />';

foreach ($errors as $msg)

{

echo " - $msg<br />\n";

}

 

}

 

 

}//End of SUBMITTED IF

 

 

 

 

 

 

 

 

 

 

 

?>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<script type="text/javascript" src="calendar.js"></script>

<script type="text/javascript" src="jquery.js"></script>

<title>Enter BRV Calibration Details</title>

 

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">

 

 

 

<style type="text/css">

<!--

.style7 {font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 10px; }

.style10 {font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 12px; }

.style11 {font-size: 11px}

.style4 {font-size: 12px; font-family: Arial, Helvetica, sans-serif; font-weight:100; }

.style5 { color: #FFFFFF;

font-family: Verdana, Arial, Helvetica, sans-serif;

font-size: 11px;

font-weight: bold;

}

-->

</style>

 

<link href="../../style.css" rel="stylesheet" type="text/css">

<script type="text/javascript" src="../../script.js"> </script>

<style type="text/css">

<!--

.style1 {color: #FFFFFF}

-->

</style>

 

 

 

<script type="text/javascript">

 

$(document).ready(function(){

 

var counter = 1;

var comp_counter=1;

 

 

$("#addButton").click(function () {

 

if(counter>100)

{

alert("Only 10 Capacityes allow");

return false;

}

 

var newCapacityDiv = $(document.createElement('div'))

.attr("id", 'CapacityDiv' + counter)

.attr("class", 'CapacityDiv');

 

var newUllageDiv = $(document.createElement('div'))

.attr("id", 'CapacacityDiv' + counter)

.attr("class", 'CapacityDiv');

 

newCapacityDiv.html('<label>Capacity #'+ counter + ' : </label>' +

'<input type="text" name="Capacity' + counter +

'" id="Capacity' + counter + '" value="" >'+" "+

 

'<label>Ullage #'+ counter + ' : </label>' +

'<input type="text" name="Ullage' + counter +

'" id="Ullage' + counter + '" value="" ><p></p>');

 

newCapacityDiv.appendTo("#CompartmentGroup");

 

 

 

counter++;

 

 

});

 

 

 

 

$("#addCompartment").click(function () {

 

if(comp_counter>20){

alert("Only 20 Capacityes allow");

return false;

}

 

 

var newCompartmentDiv = $(document.createElement('div'))

.attr("id", 'CompartmentDiv' + comp_counter)

.attr("class", 'CompartmentDiv');

 

newCompartmentDiv.html('<td><h3>Compartment#'+ comp_counter + ' :</h3></td>');

 

 

newCompartmentDiv.appendTo("#CompartmentGroup");

comp_counter++;

 

});

 

 

 

 

 

 

 

$("#removeButton").click(function () {

if(counter==0 || comp_counter==0){

alert("No more Details to remove");

 

return false;

}

 

if ($("#CompartmentGroup div:last-child").attr("class")=='CapacityDiv')

{

$("#CompartmentGroup div:last-child").remove();

counter--;

}

 

if ($("#CompartmentGroup div:last-child").attr("class")=='CompartmentDiv')

{

$("#CompartmentGroup div:last-child").remove();

comp_counter--;

}

 

 

 

 

 

 

 

});

 

 

 

 

 

$("#getButtonValue").click(function () {

 

var comp_msg = '';

for(n=1; n<comp_counter; n++)

{

comp_msg += "\n\n Compartment #" + n + " : " + $('#CompartmentDiv' + n).val();

for(i=1; i<counter; i++)

{

comp_msg += "\n Capacity #" + i + " : " + $('#Capacity' + i).val();

comp_msg += "Ullage #" + i + " : " + $('#Ullage' + i).val();

}

 

}

 

alert(comp_msg);

 

 

 

});

 

});

 

 

</script>

 

 

 

 

 

 

 

 

 

 

 

 

 

</head>

 

<body>

<table width="775" border="0" align="center" cellpadding="0" cellspacing="0" bgcolor="#FFFFFF">

 

<tr>

<td><hr size="1" noshade></td>

</tr>

<tr>

<td> <table width="775" border="0" align="center" cellpadding="0" cellspacing="0">

 

<tr>

<td><form name="form1" method="post" action="brv.php">

<table width="550" border="0" align="center" cellpadding="1" cellspacing="2">

 

 

 

 

 

 

<tr>

<td width="205"><span class="style10">BRV Number </span></td>

<td width="335"><input name="brv_number" type="text" id="name"></td>

</tr>

 

<tr>

<td width="205"><span class="style10">Capacity of BRV (lts) </span></td>

<td width="335"><input name="brv_capacity" type="text" id="name"></td>

</tr>

 

<tr>

<td width="205"><span class="style10">Expiry Date: </span></td>

<?php

require_once('classes/tc_calendar.php');

//echo '<p></p>';

//echo '<b> Expiry date</b> ';

 

 

$calendar_date="2011-09-01";

$calendar_day=date("j", strtotime($calendar_date));

$calendar_month=date("n", strtotime($calendar_date));

$calendar_year=date("Y", strtotime($calendar_date));

 

 

 

//instantiate class and set properties

 

$myCalendar = new tc_calendar("date1", true);

$myCalendar->setIcon("images/iconCalendar.gif");

$myCalendar->setDate($calendar_day,$calendar_month,$calendar_year);

 

//output the calendar

?>

<td>

<?php

$myCalendar->writeScript();

?>

</td>

 

 

</tr>

 

 

<tr>

<td><span class="style10">Transporter </span></td>

<td>

 

<select class="element select medium" id="element_23" name="transporter_id" onChange="javascript autoSubmit(this);">

<option value="NULL"></option>

<?php // Retrieve all the transporters and add to the pull-down menu.

 

$q = "SELECT transporter_id, transporter_name FROM transporters ORDER BY transporter_name ASC";

$r = mysqli_query ($dbc, $q);

if (mysqli_num_rows($r) > 0) {

while ($row = mysqli_fetch_array ($r, MYSQLI_NUM)) {

echo "<option value=\"$row[0]\"";

 

//Make dropdown Sticky

if (isset($_POST['transporter_id']) && ($_POST['transporter_id'] == $row[0]) ) echo ' selected="selected"';

echo ">$row[1]</option>\n";

}

} else {

echo '<option>Please add a new transporter.</option>';

}

 

?>

</select>

</span></td>

</tr>

 

 

 

 

<tr>

<td><span class="style10">OMC </span></td>

<td>

 

<select class="element select medium" id="element_23" name="omc_id" onChange="javascript autoSubmit(this);">

<option value="NULL"></option>

<?php // Retrieve all the transporters and add to the pull-down menu.

 

$q = "SELECT omc_id, omc_name FROM omcs ORDER BY omc_name ASC";

$r = mysqli_query ($dbc, $q);

if (mysqli_num_rows($r) > 0) {

while ($row = mysqli_fetch_array ($r, MYSQLI_NUM)) {

echo "<option value=\"$row[0]\"";

 

//Make dropdown Sticky

if (isset($_POST['omc_id']) && ($_POST['omc_id'] == $row[0]) ) echo ' selected="selected"';

echo ">$row[1]</option>\n";

}

} else {

echo '<option>Please add a new omc.</option>';

}

 

?>

</select>

</span></td>

</tr>

 

 

 

 

 

 

<tr><p>

<td><span class="style10">Number of Compartments:</span></td>

<td><span class="style7">

<select name="number_of_compartments" id="number_of_compartments">

<option value="NULL"></option>

<option value="1">1</option>

<option value="2">2</option>

<option value="3">3</option>

<option value="4">4</option>

<option value="5">5</option>

<option value="6">6</option>

<option value="7">7</option>

<option value="8">8</option>

<option value="9">9</option>

<option value="10">10</option>

 

</select>

</span></td>

</p> </tr>

 

 

<tr><p>

<td><span class="style10">Number of Levels per Compartment:</span></td>

<td><span class="style7">

<select name="ullage_levels" id="ullage_levels">

<option value="NULL"></option>

<option value="1">1</option>

<option value="2">2</option>

<option value="3">3</option>

<option value="4">4</option>

<option value="5">5</option>

<option value="6">6</option>

<option value="7">7</option>

<option value="8">8</option>

<option value="9">9</option>

<option value="10">10</option>

 

</select>

</span></td>

</p> </tr>

 

 

 

 

<tr>

<td width="205"><span class="style10">Comments </span></td>

<td width="335"><textarea id="element_20" class="element textarea medium" name="comments"></textarea> </td>

</tr>

 

 

 

 

 

 

<tr>

<td><span class="style11"></span></td>

<td> </td>

</tr>

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

</table>

 

</tr>

</table></td>

</tr>

<tr>

<td> </td>

</tr>

</table>

 

 

 

 

 

<div id='CompartmentGroup'>

<div id="CompartmentDiv">

 

</div>

</div>

 

 

<input type='button' value='Add Button' id='addButton'>

<input type='button' value='Remove Button' id='removeButton'>

<input type='button' value='Get Capacity Value' id='getButtonValue'>

<input type='button' value='Add Compartment' id='addCompartment'>

 

 

<input type="hidden" name="form_id" value="20900" />

<input type="hidden" name="submitted" value="TRUE" />

<p></p>

<p></p>

<p></p>

<input name="submit" type="submit" value="SUBMIT ">

 

</form></td>

</body>

</html>

<?php

 

}

 

else

{ // Redirect.

 

$url = BASE_URL . 'login.php'; // Define the URL:

ob_end_clean(); // Delete the buffer.

header("Location: $url");

exit(); // Quit the script.

 

}

 

include ('includes/footer.html');

?>

Link to comment
Share on other sites

kobena, I hate to say it, buddy, but no one is going to take the time to read all that code.

 

Please only post the relevant part of the code, and use the code tags to increase readability.

 

jQuery has an Ajax method that greatly simplifies things.

 

Attach an onsubmit event to the form in question, and when the event fires, use the jQuery Ajax method to make your request.

 

That is probably the easiest way to do what you want to do.

 

Please look into the onsubmit event and the jQuery Ajax method, and try to make it work before coming back to post.

 

Thank you.

Link to comment
Share on other sites

Thanks for your comments. But what i have been trying to do is to use javascript to create a new DOM element. I have a variable called "comp_msg" and need to set it as the value attribute. Could someone point it out to me why the following does not work?

 

var hiddenelement = document.createElement("input");

hiddenelement.setAttribute("id","comp_msg");

hiddenelement.setAttribute("type","hidden");

hiddenelement.setAttribute("value","'"+comp_msg+"'");

hiddenelement.setAttribute("name","comp_msg");

 

 

hiddenelement.appendTo("#kobena");

Link to comment
Share on other sites

I think you can simply hiddenelement.setAttribute("value","'"+comp_msg+"'"); to the following:

 

hiddenelement.setAttribute("value",comp_msg);

 

Other than that, are the comp_msg variable and the #kobena HTML element properly defined before this point in your script?

 

I always use the appendChild method in JS, not its jQuery alternative, so not 100% about the appendTo syntax. According to the following link though, the appendTo syntax looks okay:

 

http://api.jquery.com/appendTo/

 

Also, there's the possibility that it's properly appended, but it's appended after the form is submitted.

 

Again, too many things to guess out without specifics. Feel free to post code, just not a mountain of it.

Link to comment
Share on other sites

(1)Please find below the relevant javascript code:

 

var comp_msg='';

 

$("#getButtonValue").click(function () {

 

for(n=1; n<comp_counter; n++)

{

comp_msg += "\n\n Compartment #" + n + " : " + $('#CompartmentDiv' + n).val();

for(i=1; i<counter; i++)

{

comp_msg += "\n Capacity #" + i + " : " + $('#Capacity' + i).val();

comp_msg += "Ullage #" + i + " : " + $('#Ullage' + i).val();

}

 

}

 

 

var hiddenelement = document.createElement("input");

hiddenelement.setAttribute("id","comp_msg");

hiddenelement.setAttribute("type","hidden");

hiddenelement.setAttribute("value",comp_msg);

hiddenelement.setAttribute("name","comp_msg");

 

hiddenelement.appendTo("#kobena");

 

alert(comp_msg);

(2) The hidden element is intended to be inserted in the div element with id=kobena as below:

 

<div id="kobena">

 

<input type="hidden" name="submitted" value="TRUE" />

</div>

<input name="submit" type="submit" value="SUBMIT ">

 

</form>

(3) The form element is shown below:

<form name="form1" id="form1" method="post" action="brv.php">

(4) The element for the creation of the getbutton is below:

<input type='button' value='Get Capacity Value' id='getButtonValue'>

 

Thanks

Link to comment
Share on other sites

I could be wrong, but don't input elements have to go in form elements? Otherwise, I think an error will occur. Anyway, I whipped up the following script, and everything works fine:

 

 

<!DOCTYPE html>

<html lang="en">

 <head>

   <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

   <title>Add input elements test</title>

   <style type="text/css">

     input {

       display: block;

     }

   </style>

 </head>

 <body>

   <form method="#" action="#">

     <input type="text" value="1" name="input1" id="input1">

   </form>

   <button type="button" id="clickme">Click me to add another text input element to the form</button>

   <script>

     var form = document.forms[0],
       button = document.getElementById('clickme'),
       newInput,
       i = 2;

     button.onclick = function () {

       newInput = document.createElement('input');

       newInput.setAttribute('type', 'text');

       newInput.setAttribute('value', i);

       newInput.setAttribute('name', 'input' + i);

       newInput.setAttribute('id', 'input' + i);

       form.appendChild(newInput);

       i++;

     };

   </script>

 </body>

</html>

 

I prefer normal JS, not jQuery, so you'll have to account for that. Anyway, copy the script into a text editor, save it as an HTML file, and play with it. If you have any other questions, please ask. Thanks.

 

Edit: And if you don't mind, could you please edit your post above by cutting out that massive amount of code? Thank you.

Link to comment
Share on other sites

 Share

×
×
  • Create New...