Hi All,

In my attempt to learn javascript by jumping in with both feet, I have run into the following scenario:

I have a registration form that requires different information based on a combobox selection. My thought was to resubmit the form with some special identifier when the combobox changes, then read this identifier with PHP and re-display the form with the proper fields.

I have the combobox onchange event firing to a js function, which is currently submitting normally (I can't tell the difference between this submit and a normal user submit). I'm kinda stuck here. I guess I have the following questions:

1. Can I submit the form with some unique variable
2. How can I read this variable in PHP after the submit to know that I need to process it differently?

Am I on the right track? Any help will be greatly appreciated.

Thanks,
Jimmy

Hey, you can always have hidden input tag to which you can set values in form.
For example:-

<form action="page.php" method="post">
    <input type='hidden' name='var1' value='param1'/>
    <input type='hidden' name='var2' value='param2'/>
    <!-- Rest of our form elements ->
</form>

so when you submit this form you can get those hidden inputs as normal inputs:-

<?php echo $_POST["var1"]; ?>!<br />
<?php echo $_POST["var2"]; ?>!<br />

Yup that's pretty well how I would do it.

If you name the two hidden fields "action" and "actionValue" then you have a flexible system for instructing the server-side code what to do. If necessary, multiple values can be passed in the single "actionValue" field by using suitable delimiters, eg. "35:25:Smith:Red". Use (from memory) explode( ":", $_POST('actionValue')) in php to make an array of the individual values.

Whatever technique you use, don't forget htmlspecialchars() and range checks etc. in php to nutralise anything nasty. There are some wicked people out there.

Airshow

Here's a simple demo...
You can set/get different ( values or variables ) using hidden field's, asside from the values supplied by the combo boxes.
Form page

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<meta http-equiv="Content-Script-Type" content="text/javascript" />
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" />
<title>Browser Information</title>
<style type="text/css">
/* <![CDATA[ */

html, body {
  border : none;
  background-color : #ccc;
  color : #405060;
  font : normal normal normal 95%/1.4 "Trebuchet MS", "Bernard MT Condensed", Tahoma, Verdana, Helvetica, Arial, sans-serif;
  min-height : 600px;
  text-align : center;
  height : auto;
  width : auto; }

body .m-title {
  background-color : #444;
  border-top : 2px solid #000;
  border-bottom : 2px solid #000;
  color : #757575;
  margin-top : 0;
  padding : .100em 1em .100em 1em;
  text-align : left;
  width : auto; }

form { 
  border : none;
  margin : 0;
  padding : 0; }



div#main {
  border : none;
  background-color : #f0f0f0;
  margin : 0 auto;
  height : inherit !important;
  padding : 0;
  width : 100%; }

div.tube {
  border : 1px solid;
  background-color : inherit;
  height : inherit !important;
  clear : both;
  padding : 1em;
  margin : 0;
  overflow : hidden;
}

  table {
  border : none;
  border-collapse;
  margin : 1em auto 0 auto;
  padding : 0;
  text-align : left;
  width : 100%; }

  td, th {
  border-top : 1px solid;
  font : normal normal normal 12pt Verdana, Arial, sans-serif;
  border-bottom : 1px solid;
  white-space : pre;
  vertical-align : middle;
  padding : .300em 1em .300em 1em; }
  td { width : 35%; }
  select { margin : 0 auto; width : 85%; }
  table th:first-child {
  letter-spacing : 2px;
  border-right : 1px solid;
  background-color : #ccc;
  width : 30% !important; }
/* ]]> */
</style>
<script type="text/javascript">
// <![CDATA[
var setMyUniqueVar, makeItUnique;

setMyUniqueVar = function() {
   sel = (( document.getElementById ) ? document.getElementById("selection") : document.all.selection );
   index = sel.selectedIndex;
   hide = (( document.getElementById ) ? document.getElementById("hideme") : document.all.hideme );
   hide.value = sel.options[ index ].value;

   switch( hide.value ) {   
   case "default" : { 
      alert( "Please select different entry!" );
      break;
      }
   case "selectionOne" : {
      alert( hide.value );
      break;
      }
   case "selectionTwo" : {
      alert("Not Bad!");
      break;
      }
   case "unique" : {
      alert( "Good Choice!");
      break;
      } 
   }
};

makeItUnique = function() {
   hide = (( document.getElementById ) ? document.getElementById("hideme") : document.all.hideme );
   if ( hide.value === "unique" ) { return true 
   } else { 
   hide.value = "normal";
   return true; } 
   return false;
};

// ]]>
</script>
</head>
<body>
<div id="main">
<div id="content" class="tube">
<h2 class="m-title">Javascript Live Demo</h2>

<form id="myForm" action="process.php" method="post" onsubmit="return makeItUnique();">
<table frame="void" rules="none" summary="Creating Unique Variable's Using JavaScript">
<tr>
<th><input type="hidden" value="" id="hideme" name="hideme" /><label for="selection">Select Entry</label></th>
<td style="text-align:center;"><select id="selection" name="selection" onchange="setMyUniqueVar();" size="1">
<option value="default">Default Entry</option>
<option value="selectionOne">Selection One</option>
<option value="selectionTwo">Selection Two</option>
<option value="unique">Selection Three</option>
</select>
</td>
<td style="text-align : center;"><input type="submit" value="submit" id="sbm" name="sbm" /></td>
</tr>
</table>
</form>
</div>
</div>
</body>
</html>

process.php

<html>
<head>
<title>Test Page</title>
</head>
<body>
<?php
$unique = $_REQUEST['hideme'];

if(( isset( $unique ) ) && ( $unique === 'unique' )):
?>
<h1>Unique Selection</h1>
<?php else: ?>
<h1>Normal Selection</h1>
<?php endif; ?>
</body>
</html>

Wow, not only did you guys come through with great explanations, but complete examples as well! I am quite anxious to look at this later tonight and to let you know how it goes.

Thanks,
Jim

Works wonderfully! I wasn't familiar with the hidden input fields, they sure make things much easier.

I have just a couple of follow up questions for clarification:

- In the example you list $unique = $_REQUEST; to capture the variable, which I couldn't get working. After switching it the $unique = $_POST; the variable was properly assigned. What is the difference?

- Before following your example, I was submitting the updated quantity via the following function

function SetQuantity(val){
$Quantity = val;
document.frmReg.action = "?repost=" + val; 
document.frmReg.submit(); 
}

which produced a URL of test.php?repost=4. Airshow mentioned wicked people out there, is this an acceptable method od retrieving the new value? Also, what function would allow me to break the value from repost into it's own variable?

Thanks again for all the help and suggestions!
-Jim

Hi Jim,

At the risk of straying too deeply into PHP in the js etc. forum ......

My remark about wicked people is a 100% server-side issue. Whatever measures you put in place client-side (HTML/Javascript) can be circumvented. Many, maybe most, malicious requests are submitted by robots which submit synthetic HTTP queries, typically simulating a form submission from your carefully designed web page. That's why, regardless of what you have coded in Javascript, you should always take defensive meaures in php (or asp/jsp/perl etc. etc.) as well.

In php, the defensive front line lies in making sure that parameters passed in the request are sanitised. I always use routines similar to those below (with credit to phpBB):

// String params
$params = array('url' => POST_URL, 'title' => POST_TITLE, 'provider' => POST_PROVIDER);
while( list($var, $param) = @each($params) )
{
	if ( !empty($_POST[$param]) || !empty($_GET[$param]) )
	{
		$$var = ( !empty($_POST[$param]) ) ? htmlspecialchars($_POST[$param]) : htmlspecialchars($_GET[$param]);
	}
	else
	{
		$$var = '';
	}
}
// Integer params
$params = array('refreshdelay' => POST_REFRESH_DELAY, 'charEnc' => POST_CHAR_ENCODING);
while( list($var, $param) = @each($params) )
{
	if ( !empty($_POST[$param]) || !empty($_GET[$param]) )
	{
		$$var = ( !empty($_POST[$param]) ) ? intval($_POST[$param]) : intval($_GET[$param]);
	}
	else
	{
		$$var = -1;
	}
}
// Boolean params
$params = array('showHeader' => POST_SHOW_HEADER, 'showLEftNav' => POST_SHOW_LEFTNAV);
while( list($var, $param) = @each($params) )
{
	if ( !empty($_POST[$param]) || !empty($_GET[$param]) )
	{
		$$var = true;
	}
	else
	{
		$$var = false;
	}
}

You just need to edit the lines starting $params = to reflect the particular params needed by the page in question. CAPITALISED "variables" are define()d constants (which can't be changed) and represent the parameter names against which POST/GET values appear in the request (eg. define('POST_URL', 'u') . I always keep all such define()s in a single file, which is include()d at the top of every page that needs to accept $_POST or $_GET parameters.

These routines (or similar) ensure that values you expect to be strings are passed through htmlspecialchars(), integers are cast with intval, and booleans are guaranteed true or false. Personally, I never use eg. $_POST('foo') or $_GET('foo') directly in my code (the thought makes me cringe). This reduces enormously the possibility of malicious code injection (which can mean "bye bye database").

******

I can't immediately see why $_REQUEST should not have worked for you. Maybe there's a setting somewhere in your php.ini that excludes it? Anyway, it's better to use $_POST if that's what you are expecting in the request.

Airshow

Sorry if came so late, quite busy with some new project.

Airshow,
is really great and knows how to handle everything and always definitive when he start to speak...
Just wanna say thanks for explaining all those details...

@ jim - if you are trying catch secured data, then it's better handled with $_POST rather than $_GET /* or */ $_REQUEST .

The only great thing about $_REQUEST is that it handles both method GET/POST sent by the server and ensuring all data transfer either set by post/get.

That's why i really hate to provide examples which i cannot run first before posting. If the $_REQUEST doesn't work, simply apply everything using $_POST .

Hope we have helped you with our solutions'...

Thanks for the kind words Essential.

That's why i really hate to provide examples which i cannot run first before posting.

Same here. Trialling HTML/Javascript = quick & easy (especially using FirstPage 2000 editor); PHP = harder (need to start up The Terminator and get brain into php mode).

Good luck with your project Jim.

Airshow

Thanks guys, I hadn't even thought of the security measures, but I think I have the architecture straight now and am on my way to finishing the project. I really appreciate the detailed explanations and examples, keep up the good work!

Thanks,
Jim

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.