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

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.

Related

Accessing Drop Down Menu Value using asp/VBscript

I have a very simple drop down menu:
<select name="sNumR" id="sNumR" onChange="addTable()">
<option value=1>1</option>
<%For i=2 to 10
Response.write("<option value="&i&">"&i&"</option>")
Next%>
</select>
All I'm trying to do is access the selected value, whether it be the default value of 1 or otherwise. Please don't list a jQuery or javascript solution as I already know how to do that and am not concerned about that at all.
The simple: Request.Form("sNumR") doesn't work. I've tried it, many times...
What is it I'm missing? Is this even possible with vbscript/asp? I prefer a method that is simple as I believe this task should be but at this point I'm willing to take whatever I can get.
Request.Form() collection can only be accessed once data has been submitted, you do this either using client-side code to trigger a form submit or using an <input type="submit" />
This whole mechanic relies on the fact that your <select> and <input> tags are wrapped inside a <form> tag. The form has specific attributes you have to set to to access the Request.Form() collection.
action - Specifies URL you are submitting the form to, empty string will submit to the current page.
method - Either GET (to populate the Request.QueryString() collection) or POST (to populate the Request.Form() collection.
A simple HTML form example would like this;
<html>
<head>
<title>Sample Form</title>
</head>
<body>
<form action="" method="post">
<input type="submit" name="submit" value="Submit Form" />
</form>
</body>
</html>
This will do a form POST to the current page (assuming it's called example.asp)
POST /example.asp HTTP/1.1
Host: example.com
Content-Type: application/x-www-form-urlencoded
Content-Length: 20
submit=Submit%20Form
You can then insert ASP anywhere in that page to access the Request.Form() collection for example, placing this code above the HTML in example.asp
<%
Dim is_submit
'Have we submitted the form?
is_submit = (Request.Form("submit") = "Submit Form")
Response.Write "Form submitted: " & is_submit
%>
Will produce Form submitted: False before submission and Form submitted: True after submission.
Try wrapping your value attribute value with double quotes.
<option value="1">1</option>
Other than that, check your variable names.

reinitialize datatables with external form data (server-side django app)

I am working on a django web app, and successfully implemented the fantastic jQuery datatables to present my data with server-side processing. I don't have access to the original files (this is a project for my workplace, they don't have internet access and I'm home now), but it looks something like this:
template:
<script type="text/javascript">
$(document).ready(function() {
$('#example').dataTable( {
"bProcessing": true,
"bServerSide": true,
"sAjaxSource": "/user_table/"
} );
} );
</script>
<table id='example'>
<thead>
<th>name</th>
<th>state</th>
<th>email</th>
</thead>
<tbody>
<td colspan="3" class="dataTables_empty">Loading data from server</td>
</tbody>
</table>
server_side:
def main_view(request):
return render_to_response('index.html')
def datatables_view(request):
start = request.GET['iDisplayStart']
length = request.GET['iDisplayLength']
query = myUser.objects.all()
if request.GET.has_key('sSearch'):
# filtering...
query = query[start:start+length]
response = ["aaData": [(q.name, q.state, q.email) for q in query]]
# return serialized data
again, like I mentioned, I'm not having any trouble with this. The integration works fine. Even better than fine, really. I love it.
What I really need though, is little more complex filter than the default one that datatables comes with. There are very specific types of search relevent for my work that will be very useful. So I have a form that appears vertically above the table. Let's say it looks something like this:
<form>
<label for='name'>name:</label>
<input type='text' name='name'></input>
<label for'costumer'>costumer?</label>
<input type='checkbox' name='costumer'></input>
<select multiple="multiple">
<option id='regular'>regular</option>
<option id='new'>new</option>
</select>
<input type='submit' value='filter!'> </input>
</form>
I want that when a user clicks on the submit button it would send the form data and re-initialize the datatable with my costumized filtering. Then I want another button that would refresh and reload the datatable and cancel out any initial data it was sending (as if you refreshed the page, without actually).
I'm not very experienced with javascript, so simple solutions are the best, but any help would be very much appreciated.
I solved it! Finally...
I used the jquery-datatables-column-filter plugin. It's decent and simple to use, and they have an example on their site how to use an external form. It's true that I'm not actually filtering on specific columns, but since I'm using server-side it doesn't really matter.

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

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.

JSP drop down list - using selected item

I have a drop down list and a form with a few textboxes. I would like to populate this form with details of selected item in the drop down list.
I'm doing this in java MVC app (or wannabe) and I have in my jsp page something like this:
<select name="item">
<c:forEach items="${persons}" var="selectedPerson">
<c:set var="person" value="${selectedPerson}" />
<option value="$selectedPerson.id">${selectedPerson.LastName}</option>
</c:forEach>
</select>
Persons is a list of the Person class.
I wonder is it possible to use the variable 'person' directly to fill the form, for example:
<textarea name="name" rows="1" cols="34" >
${selectedPerson.Name}
</textarea>
so that the rest of the form updates when the selectedPerson is changed?
I know how to do this within c#, but I don't have experience with java technologies.
Is it necessary to submit the form to servlet to do this, or it can be done on the client, since I have all my data in the persons list, from the moment of populating the drop down list?
The ${} syntax is JSP syntax, which will only be parsed and run once on the server to generate the HTML, and then sent down the wire as HTML. The changes to the select list then just happen in the client browser: the server doesn't know anything about them.
What you want to do is register a javascript listener on the select box. You should look into using a library ideally to help you do this. JQuery is a very popular solution and is worth reading up on if you're going to be doing this type of development.
If you end up using JQuery, you'll want to do something like the following
<select id="item" name="item">
<c:forEach items="${persons}" var="selectedPerson">
<c:set var="person" value="${selectedPerson}" />
<option value="$selectedPerson.id">${selectedPerson.LastName}</option>
</c:forEach>
</select>
<input name="lastName" id="lastName" type="text"/>
<script type="text/javascript">
$(function() {
$("#item").change(function() {
$("#lastName").val($("option:selected", this).text());
});
});
</script>
This will make more sense once you've read a basic JQuery tutorial, but basically what it does is that each time the select list changes value, it gets the selected option and sets it's content to the lastName input field. Hope this helps.

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