Undefined Index for $_POST (noob question!) [duplicate] - xampp

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
PHP: “Notice: Undefined variable” and “Notice: Undefined index”
I am just learning PHP and I keep getting an Undefined Index error. The book I'm learning from has an HTML form and a PHP page that processes the form, using the following format:
<!-- The form fields are all set up something like this -->
<input type="text" id="howlong" name="howlong" /><br />
// The PHP starts with one line like this for each of the form fields in the HTML
$how_long = $_POST ['howlong'];
// And there is one line for each one like this to output the form data:
echo ' and were gone for ' . $how_long . '<br />';
The example I'm working with has about 12 form fields.
What's odd is that not all of the variables throw this error, but I can't see a pattern to it.
I've checked that all HTML fieldnames match up with the PHP $_POST variable name I entered, and I've made certain that when I fill out the form and submit it that all fields are filled in with something. Interestingly, the completed code that can be downloaded for the book also throws this error.
I realize this code may not reflect best practices, it's from the first chapter of the book and obviously I am a noob :)
In case it makes a difference, I am using PHP 5.3.5 on XAMPP 1.7.4 with Windows 7 Home Premium.

Remember to set the method to POST on the form tag...
heres the code i used to try yours, and it worked to me:
in a file named test.php:
<html>
<body>
<form method="POST" action="testProc.php">
<input type="text" id="howlong" name="howlong" /><br/>
<input type="submit" value="submit"/>
</form>
</body>
</html>
and in testProc.php:
<?php
if (isset($_POST)) {
if (isset($_POST["howlong"])){
$howlong = $_POST['howlong'];
echo ' and were gone for ' . $howlong . '<br />';
}
}
?>
Just as an advise, to make display manipulation with stylesheets i recommend to put forms within a table, like this:
<html>
<body>
<form method="POST" action="testProc.php">
<table>
<tbody>
<tr>
<th>
<label for="howlong">How long? :</label>
</th>
<td>
<input type="text" id="howlong" name="howlong" />
</td>
</tr>
<tr>
<input type="submit" value="submit"/>
</tr>
</tbody>
</table>
</form>
</body>
</html>
Hope you can use this...

you need to check that form is submitted and then you can try to use $_POST array, so you should put this code above:
if(isset($_POST['send'])) {
where "send" is name of submit button

You can test to see if a variable is set using the isset() function.
Also, not all HTML form elements will post a value in all cases. The common example is the checkbox; an unchecked checkbox doesn't form part of the the data posted back to the server. Therefore the $_POST element you're expecting to be set won't be.

Related

Load Dojo form from ajax call

I am trying to implement something like this.
http://app.maqetta.org/mixloginstatic/LoginWindow.html
I want the login page to load but if you click the signup button then an ajax will replace the login form with the signup form.
I have got this to work using this code
dojo.xhrGet({
// The URL of the request
url: "'.$url.'",
// The success callback with result from server
load: function(newContent) {
dojo.byId("'.$contentNode.'").innerHTML = newContent;
},
// The error handler
error: function() {
// Do nothing -- keep old content there
}
});'
the only problem is the new form just loads up as a normal form, not a dojo form. I have tried to return some script with the phaser but it doesnt do anything.
<div id="loginBox"><div class="instructionBox">Please enter your details below and click <a><strong>signup</strong>
</a> to have an activation email sent to you.</div>
<form enctype="application/x-www-form-urlencoded" class="site-form login-form" action="/user/signup" method="post"><div>
<dt id="emailaddress-label"><label for="emailaddress" class="required">Email address</label></dt>
<dd>
<input 0="Errors" id="emailaddress" name="emailaddress" value="" type="text"></dd>
<dt id="password-label"><label for="password" class="required">Password</label></dt>
<dd>
<input 0="Errors" id="password" name="password" value="" type="password"></dd>
<dt id="captcha-input-label"><label for="captcha-input" class="required">Captcha Code</label></dt>
<dd id="captcha-element">
<img width="200" height="50" alt="" src="/captcha/d7849e6f0b95cad032db35e1a853c8f6.png">
<input type="hidden" name="captcha[id]" value="d7849e6f0b95cad032db35e1a853c8f6" id="captcha-id">
<input type="text" name="captcha[input]" id="captcha-input" value="">
<p class="description">Enter the characters shown into the field.</p></dd>
<dt id="submitButton-label"> </dt><dd id="submitButton-element">
<input id="submitButton" name="submitButton" value="Signup" type="submit"></dd>
<dt id="cancelButton-label"> </dt><dd id="cancelButton-element">
<button name="cancelButton" id="cancelButton" type="button">Cancel</button></dd>
</div></form>
<script type="text/javascript">
$(document).ready(function() {
var widget = dijit.byId("signup");
if (widget) {
widget.destroyRecursive(true);
}
dojo.parser.instantiate([dojo.byId("loginBox")]);
dojo.parser.parse(dojo.byId("loginBox"));
});
</script></div>
any advice on how i can get this to load as a dojo form. by the way i am using Zend_Dojo_Form, if i run the code directly then everything works find but through ajax it doesnt work. thanks.
update
I have discovered that if I load the form in my action and run the __toString() on it it works when i load the form from ajax. It must do preparation in __toString()
Firstly; You need to run the dojo parser on html, for it to accept the data-dojo-type (fka dojoType) attributes, like so:
dojo.parser.parse( dojo.byId("'.$contentNode.'") )
This will of course only instantiate dijits where the dojo type is set to something, for instance (for html5 1.7+ syntax) <form data-dojo-type="dijit.form.Form" action="index.php"> ... <button type="submit" data-dojo-type="dijit.form.Button">Send</button> ... </form>.
So you need to change the ajax contents which is set to innerHTML, so that the parser reckognizes the form of the type dijit.form.Form. That said, I urge people into using a complete set of dijit.form.* Elements as input fields.
In regards to:
$(document).ready(function() {});
This function will never get called. The document, youre adding innerHTML to, was ready perhaps a long time a go.
About Zend in this issue:
Youre most likely rendering the above output form from a Zend_ Dojo type form. If the renderer is set as programmatic, you will see above html a script containing a registry for ID=>dojoType mappings. The behavior when inserting <script> as an innerHTML attribute value, the script is not run under most circumstances (!).
You should try something similar to this pseudo for your form controller:
if request is ajax dojoHelper set layout declarative
else dojoHelper set layout programmatic

Ajax-Generated Element Values In Form Won't Post to PHP

Although I'm getting correct options for an ajax-generated drop-down (based on the selection of another), I'm not seeing the value post to the PHP script. However, I see all the values from the normal HTML elements (not generated by ajax). What am I missing?
1. HTML produced by my scr_ajax.php script. - OK
$options is produced by the SQL query and the resulting selections are accurate. This is nearly identical to drop_down_1.).
<td>Drop Down 2</td>
<td></td>
<td>
<select name="drop_down_2" id="drop_down_2" value="" style="width:100%">
<option></option>
'.$options.'
</select>
</td>';
2. Where the ajax-generated HTML data goes.. - OK
Properly receives AJAX-generated form element above for the 2nd drop-down.):
...
<tr id="ajaxContent">
</tr>
...
3. Regular 'ol submit button.. - Not OK
drop_down_1 can be captured in $_POST data, but drop_down_2 cannot. I know I'm missing something here..)
<input type="submit" value="Submit Request" />
better start using jquery for everyday tasks.
http://api.jquery.com/jQuery.ajax/
[UPDATE: 11-25-2012]
I'm now able to combine the HTML and AJAX-generated post results by using the jQuery submit listener and populating the hidden field. However, this seems like more of a special technique/workaround as opposed to a more direct approach.
1st, I added the hidden input element:
<input type="hidden" name="drop_down_2" id="drop_down_2" value="" />
2nd, I added the jQuery submit listener:
<script type="text/javascript">
$(document).ready(function(){
$("#form_name").submit(function() {
var field = "drop_down_2";
var param = document.getElementById(field).options[document.getElementById(field).selectedIndex].value;
document.forms[0].elements[field].value = param;
});
});
</script>
[UPDATE: 12-01-2012]
It sounds like the proper solution involves mastery of the serialize function. I will post an update upon verification.

Loading a codeigniter view with a form from inside another view

Using codeigniter, I've been trying to load a view inside of a foreach loop, as follows:
$posts = $this->postslibrary->getAllPosts();
foreach($posts as $post){
$home['content'][$i] = $this->load->view('post', $post['data'], true);
$i++;
}
$this->load->view('head');
$this->load->view('home', $home);
$this->load->view('footer');
Each of those post views looks a little like this:
<div class="postnum<?=$post_num?>">
<p>Posted by: <?=$poster_name?></p>
<p>Reply to: <?=$poster_name?></p>
<form>
<input type='text' />
<input type='submit' />
</form>
</div>
And they're being loaded mostly successfully in the 'home' view (which is below for thoroughness).
<div ="posts">
<?php
for($i=0;$i<$count;$i++)
{
echo($content[$i]);
}
?>
<div class="clear"></div>
<a href='/posts/browse/'>Load more items</a>
</div>
But my output ends up looking like:
<div class='posts'>
<div class='postnum1'>
<p>Posted By: Jim</p>
<p>Reply to Jim</p>
<input type='text' />
<input type='submit' />
</div>
</div>
Why are my form tags not coming through?
Check if you already have a form around the current form. Chrome is one of the browsers which doesn't accept this and removes the second form. Using a form in a form is bad practice and I suggest you find a different solution to do the form handling.
Slightly left-of-field answer, but have a look at CodeIgniter Form Generator. I've used it a couple of times and it seems pretty good for generating forms from an array. It's a bit tricky to get your head around it to begin with, but it works well once you've gotten into it.
The basic idea is that you implement a form controller from your ordinary controller, and then just output it in your view file. It might be a more elegant (and sustainable) solution to what you're trying.

Form Submit using a Javascript to invoke webflow transition, doesn't take the updated value on form

I am trying to invoke a form submit using javascript (jquery) to invoke a webflow transition. It works and the submit invokes the desired transition. But, the updated radio button values is not reflected on the model object which is posted.
Here is the code:
<form:form method="post" action="#" commandName="infoModel" name="pageForm">
<form:input type="input" path="testMsg" id="success" />
<input type="button" id="clearSelections" value="Clear Selections">
<div class="question">
<h4><c:out value="${infoModel.questionInfo.description}"/> </h4>
<form:radiobuttons path="infoModel.answerId"
itemValue="answerId" itemLabel="answerDescription" items="${infoModel.answers}" delimiter="<br/>" />
</div>
<input type="submit" name="_eventId_saveQualitativeInput" value="Save" id="save" />
$(document).ready(function() {
$('#tabs').tabs();
//Clear selections (copy is server-side)
$('#clearSelections').click(function() {
//$('input[type="radio"]').prop('checked', false);
$('input[type="radio"]').removeAttr('checked');
$('#save').trigger('click');
});
});
</form:form>
The form:radiobutton, generates the below html:
<div class="question">
<h4>Is this a general obligation of the entity representing a full faith and credit pledge? </h4>
<span>
<input type="radio" checked="checked" value="273" name="infoModel.answerId" id="infoModel.answerId1">
<label for="infoModel.answerId1">Yes</label>
</span>
<span><br>
<input type="radio" value="274" name="infoModel.answerId" id="infoModel.answerId2">
<label for="infoModel.answerId2">No</label>
</span>
<br>
<span class="error"></span>
</div>
The input id= "success" value is registered and when the control goes to the server, the value of input id= "success" is updated in the "infoModel" object. But the value of answerId is not updated on the "infoModel" object.
Thoughts if i am missing something in the form:radiobutton element or if there is something else wrong?
Thanks in advance!
EDIT:::::::
Thanks mico! that makes sense. I stripped of some of the code first time to make it precise, but i have a list which is being used for building the radio-buttons, below is the code:
<c:forEach items="${infoModel.list["index"]}" var="qa" varStatus="rowCount">
<div class="question">
<h4><c:out value="${question.questionInfo.description}"/> </h4>
<form:radiobuttons path="list["index"][${rowCount.index}].answerId" itemValue="answerId" itemLabel="answerDescription" items="${question.answers}" delimiter="<br/>" />
<br>
</div>
</c:forEach>
Could you please suggest how i could try this one out?
NOTE: The same code works on a regular form submit on click of a button of type submit. Its the javascript form submit which is not working. I also tried to do whatever i want to do in javascript and then invoke the button.trigger('click'); form got submitted but the changes made on form in my javascript didnt reflect.
With commandName inside a form:form tag you set "Name of the model attribute under which the form object is exposed" (see Spring Documentation). Then in path you should tell the continuation of the path inside the model attribute.
With this said I would only drop the extra word infoModel from path="infoModel.answerId" and have it rewritten as path="answerId" there under the form:radiobutton.

Form fields added via AJAX fail to load into the $_POST array

I've got a plain and simple HTML form which allows people to order some brochures. The form first loads with something looking a little like this:
<script type="text/javascript">
var tableRowN = 1;
</script>
<form id="Order" name="Order" method="post" action="includes/orderCheck.php">
<input id="name" type="text" name="name" width="100" />
<table id="orderingTable">
<tr class="lastRow">
<td><div id="itemGroupdiv1">
<input type="text" class="disabled" name="itemGroup1" id="itemGroup1" />
</div></td>
<td><div id="itemCodediv1">
<input type="text" name="itemCode1" id="itemCode1" class="disabled" />
</div></td>
<td><div id="itemCodeVersiondiv1">
<input type="text" class="disabledSmall" id="itemcodeversion1" name="itemcodeversion1" />
</div></td>
</tr>
</table>
<input type="submit" name="submit" id="submit"/>
</form>
Then when the user wants to add a new line to the table he can click a button which fires the following javascript function to grab the new table code via AJAX and insert it.
function createItemLine() {
tableRowN++;
$('tr.lastRow').attr('class', '');
$('#orderingTable').append('<tr class="lastRow"></tr>');
$.ajax({
url: "/orderingTable.php?rNumber=" + tableRowN,
cache: false,
success: function(html){
$("tr.lastRow").append(html);
alert('loaded');
}
});
}
The AJAX function then runs off to a PHP script which creates the next line, rolling the IDs and Names etc with +1 to the number.
<td><div id="itemGroupdiv2">
<input type="text" class="disabled" name="itemGroup2" id="itemGroup2" />
</div></td>
<td><div id="itemCodediv2">
<input type="text" name="itemCode2" id="itemCode2" class="disabled" />
</div></td>
<td><div id="itemCodeVersiondiv2">
<input type="text" class="disabledSmall" id="itemcodeversion2" name="itemcodeversion2" />
</div></td>
So so far, nothing suprising? Should all be pretty straight forward...
The problem is that when I add new lines (In Firefox and Chrome) the new lines are completely ignored by the form submission process, and they never get passed through into the $_POST array.
Is this a known problem? I've not come across this before...
Thanks for any pointers,
H
use jQuery.trim(data) but this is not pretty sure because can affect the
content of your data. or see this one may help u
Is your table missing an html id? The jQuery selector $('#orderingTable') is looking for something with id="orderingTable"
On some thorough (and boy do I mean thorough) it turned out that the following simple (yet obvious) HTML errors can cause this issue:
Badly formed code EG missing etc
Duplicate or missing form "name" attributes
On creating properly validated HTML, the form submitted and all values were passed correctly into the _POST array. An object lesson in making sure your developers pay attention to the basics before trying to get all fancy in their coding approach ;)
I've found that using .html() to insert the content instead of .append() or .prepend() causes the inserted form fields to work as expected.
I've just spent quite a while laboring over a problem like this.
I was ajax-ing an input field into a form and that input field was not showing up in the $_POST submission array, was completely annoying!!!! Aaaaanyway, I fixed it by just checking over all my html and it turns out that my form 'open' was inside one of the main div's on page and not outside.
thus:
<div>
<form>
<input type="text" name="input_field">
</div>
</form>
is now fixed to be:
<form>
<div>
<input type="text" name="input_field">
</div>
</form>
Silly, I know, but in a massive form, it was tricky to spot! So in short just be tidy with your html and it WILL work, I hope that helps someone somewhere :-)
M

Resources