I’ve got a <select element on a php/xhtml page. Instead of using a submit button, I’m trying to implement the Javascript onchange() and submit()method. I need to pass multiple variables to make up for the lost hidden field. The onchange and submit methods are firing, but I can’t get it to trigger the PHP isset which is on the same page.
<?php
if(isset($_POST['companykey'])){
$nowIveGot1 = $_POST['COMPANYKEY'];
$nowIveGot2 = $_POST['USERNAME'];
?>
<script language="javascript">
function copy(selectedValuePassed, selectedNamePassed, userIDPassed, formNamePassed) {
var formNameReceived = formNamePassed;
var userIDReceived = userIDPassed;
var selectedValueReceived = selectedValuePassed;
var selectedNameReceived = selectedNamePassed;
var form = document.createElement("form");
form.setAttribute("method", "post");
form.setAttribute("action", "");
form.setAttribute("name", formNameReceived);
form.setAttribute("id", formNameReceived);
var valueSelected = document.createElement("input");
valueSelected.setAttribute("type", "hidden");
valueSelected.setAttribute("name", selectedNameReceived);
valueSelected.setAttribute("id", selectedNameReceived);
valueSelected.setAttribute("value", selectedValueReceived);
form.appendChild(valueSelected);
var passusername = document.createElement("input");
passusername.setAttribute("type", "hidden");
passusername.setAttribute("name", "USERNAME");
passusername.setAttribute("id", "USERNAME");
passusername.setAttribute("value", userIDReceived);
form.appendChild(passusername);
document.body.appendChild(form);
form.submit();
}
</script>
<select onchange="copy(this, 'COMPANYKEY','jarrett', 'companykey');">
<option value="Text1">Text 1</option>
<option value="Text2">Text 2</option>
</select>
SOLVED: Create a parent element for valueSelected and passusername. Name it the isset check name.
If I am understanding your problem…
The
$_POST['companykey']will always benulland theifconditonal will never execute.This is because key value pairs are not passed into the
$_POSTarray when they are attached to the<form>element, only the embedded<input>‘s.In your javascript, you pass
'companykey'as the last argument tocopy. From there it is assigned toformNameReceived. You then assign it to thenameattribute of the form with:'companykey'will never appear in the$_POSTarray like this, it’s not attached to an input, but rather theformitself.As a vanilla HTML analogue, imagine this:
No matter how many times you submit this form, it will never contain the
cat -> dogpair. If you want'companykey'to appear in the array, you’ll have to assign it to another hidden input.