fetch db mysql value in search input field and modifying in dropdown - javascript

I cannot find a solution for my problem because for me it is an advanced level of programming.
I have a custom search field, but I need to 'convert it' in a dropdown menu that fetching some users values in mysql, avoiding writing hundreds of selection options.
This is the registration form field Im working it
<tr class="user-luogo-wrap">
<th><label for="luogo">
Luogo: </label></th>
<td><input type="text" name="luogo" id="luogo" value="Treviso" class="regular-text"></td>
</tr>
Created with a function
function my_user_contactmethods( $user_contactmethods ){
$user_contactmethods['luogo'] = 'Luogo:';
return $user_contactmethods;
}
add_filter('user_contactmethods', 'my_user_contactmethods', 5);
and this is the field where I need to fetch the 'luogo' mysql values and modifying it in dropdown
<div class="um-search-filter um-text-filter-type "> <input type="text" autocomplete="off" id="luogo" name="luogo" placeholder="Luogo" value="" class="um-form-field" aria-label="Luogo"></div>
I hope I have explained it well. Can someone help me?

In Console I have found the Form data , Request payload generated after a search action:
directory_id=3f9fc&page=1&search=&sorting=display_name&gmt_offset=8&post_refferer=61&nonce=f47827a450&luogo=boston&action=um_get_members
So Im trying to modify this function
function field_choices( $field ) {
// reset choices
$field['luogo'] = array();
// get the textarea value from options page without any formatting
$choices = get_field('my_select_values', 'option', false);
// explode the value so that each line is a new array piece
$choices = explode("\n", $choices);
// remove any unwanted white space
$choices = array_map('trim', $choices);
// loop through array and add to field 'choices'
if( is_array($choices) ) {
foreach( $choices as $choice ) {
$field['luogo'][ $choice ] = $choice;
}
}
// return the field
return $field;
}
add_action('um_get_members', 'field_choices');
Is my intuition correct?

Related

passing primary key instead of attribute on submit

I have an input tag that takes a users input that calls an AJAX dynamically outputs suggestions from my database. The issue is I want to store the primary key associated with that attribute.
I have figured out a way set it to the primary key when the user selects a value; however I would rather only have the attribute displayed on the front end. Essentially what I was thinking about doing was using the option tag and setting the value to the primary key, but after reading the documentation for it, that doesnt look like it would work.
HTML:
<input type="text" id = "zip_id" class="tftextinput2" autocomplete = "off" name="zip" placeholder="Zip Code" onkeyup = "autocompleter()">
<ul id = "zip_codes_list_id"></ul>
JS:
function autocompleter()
{
var min_length = 1; // min caracters to display the autocomplete
var keyword = $('#zip_id').val();
if (keyword.length >= min_length) {
$.ajax({
url: 'ajax_refresh.php',
type: 'POST',
data: {keyword:keyword},
success:function(data){
$('#zip_codes_list_id').show();
$('#zip_codes_list_id').html(data);
}
});
} else {
$('#zip_codes_list_id').hide();
}
}
// set_item : this function will be executed when we select an item
function set_item(item)
{
// change input value
$('#zip_id').val(item);
// hide proposition list
$('#zip_codes_list_id').hide();
}
PHP:
<?php
//connect to db here
$keyword = '%'.$_POST['keyword'].'%';
$sql = "SELECT * FROM zip_codes WHERE zip LIKE (:keyword) ORDER BY zip_codes_id ASC LIMIT 0, 10";
$query = $pdo->prepare($sql);
$query->bindParam(':keyword', $keyword, PDO::PARAM_STR);
$query->execute();
$list = $query->fetchAll();
foreach ($list as $rs)
{
// put in bold the written text
$zip = str_replace($_POST['keyword'], '<b>'.$_POST['keyword'].'</b>', $rs['zip']);
// add new option
// echo '<li onclick="set_item(\''.str_replace("'", "\'", $rs['zip']).'\')">'.$zip.'</li>'; (this one only passes the attribute)
echo '<li " onclick="set_item(\''.str_replace("'", "\'", $rs['zip_codes_id']).'\')">'.$zip.'</li>';
//this one passes the attribute but changes the displayed value to the primary key.
}
?>
As you can see from the PHP file, what I am trying to do is pass in the primary key value but keep the displayed value the attribute. I am not sure how to do that. Should I be using the UL tag?
The issue in your code is that you try to the zip_id value for the input, but this input contains the zip field value - I assume it's the textual representation. There are a few ways how you could save the zip_id on the frontend - either store it in the model (if you're using some MVC framework, but I gues it's not the case) or simply add a hidden input field:
<input type="hidden" id="actual_zip_id" name="zip_id">
And
function set_item(item)
{
// change input value
$('#actual_zip_id').val(item);
// hide proposition list
$('#zip_codes_list_id').hide();
}
UPD
Speakng about the entire idea of autocompleting zip codes, it looks pretty nasty, as pointed by Darren Gourley (check the comments).
So you'd rather validate it with regex first, and then do your db-related logic like that:
$('#zip_id').on('change', function(){
// your stuff
})
Best regards, Alexander

Filemaker, PHP and jquery > show hide elements

I am echoing out a form (foreach) from my filemaker records which will result in the items ID, Name, a Checkbox and then an image.
In my understanding i will have to use classes or the elements will all have the same id.
My Code;
foreach($result->getRecords() as $record){
$id = $record->getField('Record_ID_PHP');
$name = $record->getField('DB_Name');
$pic = $record->getField('Photo_Path');
echo '"'.$id.'"<br>';
echo $name.'<br>';
echo '<input type="checkbox" class="check" value="Invoices/Photos/RC_Data_FMS/Invoices_db/Photos/'.$pic.'">';
echo '<div class="pics">';
echo '<img style="width:200px;" src="Invoices/Photos/RC_Data_FMS/Invoices_db/Photos/'.$pic.'"><br>';
echo '<hr>';
echo '</div>';
}
Which results in a page full of the records, a checkbox and the relating image.
I wish to only show these images when the checkbox is checked but cannot find a solution, i have tried many jquery scripts, to no avail.
The images will then populate the next page as a pdf to be printed.
I am hoping not to have to grab the checkbox's values as an array to then use the get method with 100's of if statements but cant see another way ?
The jquery ive used.
$(document).ready(function () {
$('.pics').hide();
$('.check').click(function () {
$('pics').show;
});
$('.pics').hide;
});
and
$(function() {
$(".check").click(function(e) {
e.preventDefault();
$('.pics').hide();
$('.pics').show();
});
});
Plus many similar alternatives.
Is there something obvious i am missing ?
Query to filemaker method;
I have changed the path field to a calculated value which works great, thank you, although with 1000's of records, i would need lots of php code to echo the checkbox's to the website and lots more to be able to edit them from the website.
I have done this previously with the value held within the checkbox in filemaker.
$sesame = $print->getField('Allergens::Allergens[11]'); if ($sesame == "Sesame") { $sesame = "checked" ;} else if ($sesame !== "Sesame") {$sesame = "" ;}
This displays the checkbox synced with filemaker.
if ($_POST['Sesame'] == 'Sesame'){ $a_sesame = 'Sesame';} else { $a_sesame = 'No Sesame'; }
This is sent as a variable to my script.
if($a_sesame == "Sesame"){$contains_sesame = "Yes";} else { $contains_sesame = "No";}
This grabs the new value from the form.
Which all work great, but then i am writing a script in filemaker too to enable the to and from of the different names for each checkbox state.
which is for this part 120 lines long, this is a sample which i have to repeat for each repetition of this field.
Set Variable [ $sesame; Value:GetValue ( Get ( ScriptParameter ) ; 11 ) ]
If [ $sesame = "Sesame" ]
Set Field [ Allergens::Allergens[11]; "Sesame" ] Commit Records/Requests
[ Skip data entry validation; No dialog ]
Else If [ $sesame = "No Sesame" ]
Clear [ Allergens::Allergens[11] ] [ Select ]
Commit Records/Requests
[ Skip data entry validation; No dialog ]
Refresh Window
[ Flush cached join results; Flush cached external data ]
End If
This would be far too large to write for so many records, just for these 14 fields used 120 in filemaker and 400 plus in the php.
I am not 100% sure what you are trying to do but this should work. First add an extra div that closes input and div pics like below.
foreach($result->getRecords() as $record){
$id = $record->getField('Record_ID_PHP');
$name = $record->getField('DB_Name');
$pic = $record->getField('Photo_Path');
echo <<<TEXT
'{$id}'<br>
{$name}<br>
<div>
<input type='checkbox' class='check' value='Invoices/Photos/RC_Data_FMS/Invoices_db/Photos/{$pic}'>
<div class='pics'>
<img style='width: 200px;' src='Invoices/Photos/RC_Data_FMS/Invoices_db/Photos/{$pic}'><br>
<hr>
</div>
</div>
TEXT;
}
then change your java to this
$(document).ready(function() {
$(".pics").hide();
$(".check").click(function() {
$(this).siblings().toggle();
});
});
well I hope this helps
Another alternative would be to set up a simple calculated container field in FileMaker, with a calculated value of:
If ( checkbox; imageField )
This would only pass the image when the checkbox was ticked for a record. This should be faster than handling this in JavaScript, since you'd be limiting the number of images being sent over the wire.
Note: For performance, you might try this with this calculated container field stored and unstored. I suspect stored v unstored should make little difference, in which case I'd suggest leaving this unstored to minimize disk space consumed.
You can use the toggle()function:
$(function() {
$('.pics').hide();
$(".check").is(':checked',function(e) {
e.preventDefault();
$('.pics').toggle();
});
});

tricky situation with ajax, php, mysql, and javascript

First time using ajax. Have successfully progressed through a number of teething problems, so far with happy results. However now is a more confusing one specific to one particular input field nested within a table - there is a good reason for that.
First the html:
<table id="speakersName" style="width: 100%; height: auto;">
<tbody><tr class="activity_row">
<td class="right" style="width: 190px;">Name of Speaker:</td>
<td><input type="text" id="input_3_1" name="input_3_1" id="input_3_1" placeholder="Name of Speaker" value="<?=$input_3_1?>" required></td>
<td><input type="button" name="button2" id="button2" value=" +1 " class="button" style="width: auto !important; margin: 5px;"></td>
</tr>
<tr>
<td class="center" colspan="3"><input type="hidden" name="MAX_FILE_SIZE" value="5632000">
<label for="file">Filename:</label> <input type="file" name="file" id="file">
<input class="button" style="width: 70px; margin-top: 12px;" type="submit" name="submit" value="Upload"></td>
</tr></tbody>
</table>
We can fairly much ignore the section containing the file upload. I just wanted to be clear about the entire table structure.
The .js file that is included in the head contains this relevant code:
function doSend_3_1() {
$.post('./post.4.ConSupAp.php?appID=' + (appID) + '&ident=input_3_1', $('#input_3_1').serialize());
}
$("document").ready(function() {
$("#input_3_1").blur(doSend_3_1);
})
Which ajax's the data entered into the text input field over to this bit of php:
// include the funcky stuff
include './conf/Funcs.php';
include './conf/DBconfig.php';
// GET the constants
$appID = $_GET['appID'];
$ident = $_GET['ident'];
if(($ident) == "input_3_1") {
$userInput = $_POST['input_3_1'];
if(($userInput == "") || ($userInput == " ") || ($userInput == NULL)) { $userInput = NULL; }
try {
$stmt = $conn->prepare("UPDATE $database.app_ConSupAp SET `nameOfSpeakers` = :userinput, `lastModified` = :time WHERE `appID` = :appid");
$stmt->bindParam(':userinput', $userInput, PDO::PARAM_STR, 128);
$stmt->bindParam(':time', time(), PDO::PARAM_INT, 11);
$stmt->bindParam(':appid', $appID, PDO::PARAM_INT, 11);
$stmt->execute();
} catch(PDOException $e) { catchMySQLerror($e->getMessage()); }
}
Which happily drops in the text that the user typed into the initial text input field, soon as they click out of it. This technique is being used across the form successfully.
True I don't yet have a success or error message coming back to the user facing page, but I'll get onto that after I've sorted this query out. One thing at a time, right? :)
Ok so now I'll show what makes the particular table input (the one above the file upload ) a little more complicated. In the head of the html facing page, I have also got the following code, within a tag:
$(window).load(function() {
// trigger event when button is clicked
$("#button2").click(function() {
// add new row to table using addTableRow function
addTableRow($(this),$("#speakersName"));
// prevent button redirecting to new page
return false;
});
// function to add a new row to a table by cloning the last row and incrementing the name and id values by 1 to make them unique
function addTableRow(btn,table) {
// clone the last row in the table
var $tr = btn.closest($("tr")).clone(true);
var num; // Current unique field number
// Clear the input fields (that are not the button)
$tr.find(":not(:button)").val("");
// get the name attribute for the input field
$tr.find("input").attr("name", function() {
// break the field name and its number into two parts
var parts = this.id.match(/(\D+)(\d+)$/);
num = parts[2]; //Get the number for later
// create a unique name for the new field by incrementing the number for the previous field by 1
return parts[1] + ++parts[2];
// repeat for id attributes
}).attr("id", function() {
var parts = this.id.match(/(\D+)(\d+)$/);
return parts[1] + ++parts[2];
});
btn.remove();
num++;
// append the new row to the table
$(table).find(".activity_row:last").after($tr);
};
});
And this function works wonderfully on it's own, it pops up new table rows for other input, in a nice unlimited manner. I've used a variation on this once before (for which it was originally written for) but that was not utilising ajax. This version works as expected for the initial input value, but I believe I need some sort of JS foreach function to arrange each of the additional new input text fields into one value, separated by a delimiter such as ^ so that I can break them up in the php and count them there with an explode and foreach.
jQuery is being used.
This is where I'm lost as I do not know how to achieve this. Help warmly received. :)
I carefully study your job at http://jsfiddle.net/k3dj214k/2/
Now, I will try explain all the steps to fix errors:
The form page html:
<form id="ConSupAp_section_3" name="ConSupAp" action="./post.4.ConSupAp.php" method="post" enctype="multipart/form-data"><!-- edited by kazumov#gmail.com -->
<input type="hidden" name="token" value="3e57334833283e22579f77e3a1ade083edf637bd3f4ab8009bbf1f4d7f517fde">
<input type="hidden" name="uID" value="1">
<input type="hidden" name="uaID" value="1">
<input type="hidden" name="appID" value="1">
<input type="hidden" name="ident" value="input_3_1"><!-- edited by kazumov#gmail.com -->
<h2 style="margin: 0 auto 20px;">Conference Support Application - Section 3</h2>
<table id="speakersName" style="width: 100%; height: auto;">
<tbody>
<tr>
<td colspan="3" style="padding: 30px;"><span class="h3">3.1</span>Please list names of guest speaker(s). Use the <strong>+1</strong> button to add addtional speakers.</td>
</tr>
<tr class="activity_row">
<td class="right" style="width: 190px;vertical-align:top">Name of Speaker:</td>
<td id="speakers_list"><!-- edited by kazumov#gmail.com -->
<!--<input type="text" name="s" placeholder="Name of Speaker" value="" required>--><!-- edited by kazumov#gmail.com -->
</td>
<td>
<input type="button" id="btnAddSpeaker" value=" +1 " class="button" style="width: auto !important; margin: 5px; vertical-align:bottom"><!-- edited by kazumov#gmail.com -->
</td>
</tr>
</tbody>
</table>
</form>
I added one hidden input and delete text input. The form tag id should be renamed to ConSupAp_section_3.
The app_ConSupAp.js editions:
Kill doSend_3_1() function
// edited by kazumov#gmail.com
//function doSend_3_1() {
// $.post('./post.4.ConSupAp.php?appID=' + (appID) + '&ident=input_3_1', $('#input_3_1').serialize(), function(data) {
// $("#errorText_3_1").html(data.errorText_3_1);
// $("#resultImg_3_1").html(data.resultImg_3_1);
// }, 'json');
//}
Kill whole module for names manipulation:
// edited by kazumov#gmail.com
// // trigger event when button is clicked
// $("#button2").click(function() {
// // add new row to table using addTableRow function
// addTableRow($(this), $("#speakersName"));
// // prevent button redirecting to new page
// return false;
// });
//
// // function to add a new row to a table by cloning the last row and incrementing the name and id values by 1 to make them unique
// function addTableRow(btn, table) {
// // clone the last row in the table
// var $tr = btn.closest($("tr")).clone(true);
// var num; // Current unique field number
// // Clear the input fields (that are not the button)
// $tr.find(":not(:button)").val("");
// // get the name attribute for the input field
// $tr.find("input").attr("name", function() {
// // break the field name and its number into two parts
// var parts = this.id.match(/(\D+)(\d+)$/);
// num = parts[2]; //Get the number for later
// // create a unique name for the new field by incrementing the number for the previous field by 1
// return parts[1] + ++parts[2];
// // repeat for id attributes
// }).attr("id", function() {
// var parts = this.id.match(/(\D+)(\d+)$/);
// return parts[1] + ++parts[2];
// });
// btn.remove();
// num++;
// // append the new row to the table
// $(table).find(".activity_row:last").after($tr);
// };
append the script page with:
// ---------------------------------------------------
// code addition for phase (3) "Speakers" of "Guests"
// edited by kazumov#gmail.com
// ---------------------------------------------------
$(document).ready(function() {
function addSpeakerNameField() {
var $txtInput = $("<input type=\"text\" name=\"speakers[]\" placeholder=\"Name of Speaker\" value=\"\" required />");// extended notation to create input element, 'id' is not nesessary
$("#speakers_list").append($txtInput);
$txtInput.blur(function(){// change value event
$.post(
"post.4.ConSupAp.php", // your address of page is different, i made temporary php page to debug
$("#ConSupAp_section_3").serialize(),// get all form values
function(data) {
// actually, your html have no tags with id "errorText_3_1" and "resultImg_3_1"
$("#errorText_3_1").html(data.errorText_3_1);// not working
$("#resultImg_3_1").html(data.resultImg_3_1);// not working
},
'json');
});// end of blur()
}
addSpeakerNameField();// the first field
$("#btnAddSpeaker").click(function() { // add one more field
addSpeakerNameField();
});
});
// end of edition by kazumov#gmail.com
As you can see, the important editions are:
a) you should generate all the input text fields from code, because it will create the whole sending routine for all the fields in one place;
b) you should naming the text fields in html like name="speaker[]", because it will create array after serialization;
c) you should adding hidden inputs inside the form, if you want to send static values;
d) i recommend you delete all over-navigation:
and rename the tabs:
Finally, in post.4.ConSupAp.php you will reach the names:
$speakers = $_POST["speakers"];// returns array
And you should to add the header to the post.4.ConSupAp.php
header("Content-type: application/json");
if you expecting the data.errorText_3_1 and data.resultImg_3_1 output to the form.
This looks like a situation where you have a jquery event you would like to bind to a number of elements, but not all of those elements have been created when the event - blur() - is bound.
You can bind events to higher DOM element and use the following syntax to bind events to new elements as they are created:
$("body").on("blur", "input.some_class_name", do_send);
When do_send() is called, "this" will be defined as the element where the event was generated, so you can identify which element needs to be posted:
function do_send(e) {
// "this" is the dom element
var the_id = $(this).attr('id');
var value = $(this).val();
// post away!
}

Separating variables for SQL insert using PHP and JavaScript

A grid table is displayed via PHP/MySQL that has a column for a checkbox that the user will check. The name is "checkMr[]", shown here:
echo "<tr><td>
<input type=\"checkbox\" id=\"{$Row[CONTAINER_NUMBER]}\"
data-info=\"{$Row[BOL_NUMBER]}\" data-to=\"{$Row[TO_NUMBER]}\"
name=\"checkMr[]\" />
</td>";
As you will notice, there is are attributes for id, data-info, and data-to that are sent to a modal window. Here is the JavaScript that sends the attributes to the modal window:
<script type="text/javascript">
$(function()
{
$('a').click(function()
{
var selectedID = [];
var selectedBL = [];
var selectedTO = [];
$(':checkbox[name="checkMr[]"]:checked').each(function()
{
selectedID.push($(this).attr('id'))
selectedBL.push($(this).attr('data-info'))
selectedTO.push($(this).attr('data-to'))
});
$(".modal-body .containerNumber").val( selectedID );
$(".modal-body .bolNumber").val( selectedBL );
$(".modal-body .toNumber").val( selectedTO );
});
});
</script>
So far so good. The modal retrieves the attributes via javascript. I can choose to display them or not. Here is how the modal retrieves the attributes:
<div id="myModal">
<div class="modal-body">
<form action="" method="POST" name="modalForm">
<input type="hidden" name="containerNumber" class="containerNumber" id="containerNumber" />
<input type="hidden" name="bolNumber" class="bolNumber" id="bolNumber" />
<input type="hidden" name="toNumber" class="toNumber" id="toNumber" />
</form>
</div>
</div>
There are additional fields within the form that the user will enter data, I just chose not to display the code. But so far, everything works. There is a submit button that then sends the form data to PHP variables. There is a mysql INSERT statement that then updates the necessary table.
Here is the PHP code (within the modal window):
<?php
$bol = $_POST['bolNumber'];
$container = $_POST['containerNumber'];
$to = $_POST['toNumber'];
if(isset($_POST['submit'])){
$bol = mysql_real_escape_string(stripslashes($bol));
$container = mysql_real_escape_string(stripslashes($container));
$to = mysql_real_escape_string(stripslashes($to));
$sql_query_string =
"INSERT INTO myTable (bol, container_num, to_num)
VALUES ('$bol', '$container', '$to')
}
if(mysql_query($sql_query_string)){
echo ("<script language='javascript'>
window.alert('Saved')
</script>");
}
else{
echo ("<script language='javascript'>
window.alert('Not Saved')
</script>");
}
?>
All of this works. The user checks a checkbox, the modal window opens, the user fills out additional form fields, hits save, and as long as there are no issues, the appropriate window will pop and say "Saved."
Here is the issue: when the user checks MULTIPLE checkboxes, the modal does indeed retrieve multiple container numbers and I can display it. They seem to be already separated by a comma.
The problem comes when the PHP variables are holding multiple container numbers (or bol numbers). The container numbers need to be separated, and I guess there has to be a way the PHP can automatically create multiple INSERT statements for each container number.
I know the variables need to be placed in an array somehow. And then there has to be a FOR loop that will read each container and separate them if there is a comma.
I just don't know how to do this.
When you send array values over HTTP as with [], they will already be arrays in PHP, so you can already iterate over them:
foreach ($_POST['bol'] as $bol) {
"INSERT INTO bol VALUES ('$bol')";
}
Your queries are vulnerable to injection. You should be using properly parameterized queries with PDO/mysqli
Assuming the *_NUMBER variables as keys directly below are integers, use:
echo '<tr><td><input type="checkbox" value="'.json_encode(array('CONTAINER_NUMBER' => $Row[CONTAINER_NUMBER], 'BOL_NUMBER' => $Row[BOL_NUMBER], 'TO_NUMBER' => $Row[TO_NUMBER])).'" name="checkMr[]" /></td>';
Then...
$('a#specifyAnchor').click(function() {
var selectedCollection = [];
$(':checkbox[name="checkMr[]"]:checked').each(function() {
selectedCollection.push($(this).val());
});
$(".modal-body #checkboxCollections").val( selectedCollection );
});
Then...
<form action="" method="POST" name="modalForm">
<input type="hidden" name="checkboxCollections" id="checkboxCollections" />
Then...
<?php
$cc = $_POST['checkboxCollections'];
if (isset($_POST['submit'])) {
foreach ($cc as $v) {
$arr = json_decode($v);
$query = sprintf("INSERT INTO myTable (bol, container_num, to_num) VALUES ('%s', '%s', '%s')", $arr['BOL_NUMBER'], $arr['CONTAINER_NUMBER'], $arr['TO_NUMBER']);
// If query fails, do this...
// Else...
}
}
?>
Some caveats:
Notice the selector I used for your previous $('a').click() function. Do this so your form updates only when a specific link is clicked.
I removed your mysql_real_escape_string functions due to laziness. Make sure your data can be inserted into the table correctly.
Make sure you protect yourself against SQL injection vulnerabilities.
Be sure to test my code. You may have to change some things but understand the big picture here.

Multiple form fields with same 'name' attribute not posting

I'm dealing with some legacy HTML/JavaScript. Some of which I have control over, some of which is generated from a place over which I have no control.
There is a dynamically generated form with hidden fields. The form itself is generated via a Velocity template (Percussion Rhythmyx CMS) and JavaScript inserts additional hidden form fields. The end result is hidden form fields generated with the same 'name' attribute. The data is being POSTed to Java/JSP server-side code about which I know very little.
I know that form fields sharing the same 'name' attribute is valid. For some reason the POSTed data is not being recognized the back end. When I examine the POST string, the same-name-keys all contain no data.
If I manipulate the code in my dev environment such that only a single input field exists for a given name, the data IS POSTed to the back end correctly. The problem is not consistent, sometimes, it works just fine.
Is there something I can do to guarantee that the data will be POSTed? Can anyone think of a reason why it would not be?
I should really update my answer and post code here, because POST requests without
variable strings indicates the problem is on the client side.
How about this:
<script type="text/JavaScript">
function disableBlankValues()
{
var elements = document.getElementById("form1").elements;
for (var i = 0; i < elements.length; i++)
{
if (elements[i].value == "")
elements[i].disabled = true;
}
}
</script>
<form action="page.php" method="POST" onsubmit="disableBlankValues()" id="form1">
<input type="hidden" name="field1" value="This is field 1."/>
<input type="hidden" name="field1" value=""/>
</form>
EDIT
I now realize the actual problem (multiple variables with the same name should be passed to JSP as an array) and my solution is probably not what the OP is looking for, but I'm leaving it here just in case it happens to help someone else who stumbles upon this post.
you could use something like:
var form = document.getElementById('yourformid');
var elements = form.getElementsByName('repeatedName');
var count = 0;
for(var item in elements){
elements[item].name += count++;
}
this way you will get each hiddenfield with the names:
name0
name1
name2
...
I've worked out a brute-force solution. Note that I'm pretty aware this is a hack. But I'm stuck in the position of having to work around other code that I have no control over.
Basically, I've created an ONSUBMIT handler which examines the form for the repeated hidden fields and makes sure they are all populated with the correct data. This seems to guarantee that the POST string contains data regardless of how the form gets rendered and the Java back end appears to be happy with it as well.
I've tested this in the following situations:
Code generates single instances of the hidden fields (which does happen sometimes)
Code generates multiple instances of the hidden fields
Code generates no instances of the hidden fields (which should never happen, but hey...)
My 'else' condition contains a tiny bit of MooTools magic, but it's otherwise straight-forward stuff.
Maybe someone else will find this useful one day...
Thanks for the help!
<form method="post" name="loginform" id="loginform" action="/login" onsubmit="buildDeviceFP(this);">
<script type="text/javascript">
function insertFieldValues( fields, sValue )
{
if ( 'length' in fields )
{
// We got a collection of form fields
for ( var x = 0; x < fields.length; x++ ) {
fields[x].value = sValue;
}
}
else
{
// We got a single form field
fields.value = sValue;
}
}
function buildDeviceFP( oForm )
{
// Get the element collections for Device Fingerprint & Language input fields from the form.
var devicePrintElmts = oForm.elements.deviceprint;
var languageElmts = oForm.elements.language;
// 'devicePrintElmts' & 'languageElmts' *should* always exist. But just in case they don't...
if ( devicePrintElmts) {
insertFieldValues( devicePrintElmts, getFingerprint() );
} else if ( oForm.deviceprint ) {
oForm.deviceprint.value = getFingerprint();
} else {
$('logonbox').adopt(
new Element( 'input', {'type':'hidden', 'name':'deviceprint', 'value':getFingerprint()} )
);
}
if ( languageElmts) {
insertFieldValues( languageElmts, getLanguage() );
} else if ( oForm.language ) {
oForm.language.value = getLanguage();
} else {
$('logonbox').adopt(
new Element( 'input', {'type':'hidden', 'name':'language', 'value':getLanguage()} )
);
}
}
</script>

Categories

Resources