How to get selected index of dropdown from PHP post - php

I have an HTML form which contains a drop down, a tinyMCE textarea, and a save button.
The dropdown is used to select a file to edit.
I load up the required file into the tinyMCE editor by making an ajax call when the jquery change() event is triggered from the dropdown. That works fine.
The problem I'm having is saving the file off. I am trying to do it by posting the form off to another php page which will write to the file and then send us back to the main page.
This is the php code within my writeFile.php page:
<?php
session_start();
if (!isset($_SESSION['id'])) {
header ('Location: index.php?error=0');
}
else {
if (isset($_POST['save'])) {
$text = $_POST['mceContent'];
$index = $_POST['files']; // << PROBLEM LINE!
$array = array('homeText.txt', 'anotherText.txt');
$fileName = $array[$index];
$path = '../txt/'.$fileName;
$length = strlen($text);
echo "INDEX: $index"; // TO TEST THE INDEX VARIABLE.
$fh = fopen($text,'w',true);
fwrite($fh,$text,$length) or die('Could not write');
fclose($fh);
header ('Location: admin.php');
}
}
?>
The $index variable is meant to be the selected index in the dropdown, however it is posted by my form as the selected string value in the dropdown.
I can think of three solutions (ordered from least likely to work to most likely)
There is some way to get the index from that php post?
I can make a change in the HTML form/select tag to tell it to post the index and not the value string
I change it to a jquery event, with the on-click, and pass in the index to a post manually with xhr.
If someone could help me with implementing one of these method that would be great.
If you have your own, better solution I would be happy to hear that as well.
Also note that I can't build the path from the value string, because my dropdown uses descriptive strings, not actual file names.
Thanks in advance, bear in mind I'm new to php and especially jquery.

I am not sure why you can't use the value attribute - the descriptive string would be the text portion of the option element, the filename to save could be the value:
<option value="path/to/file_to_save.php">Descriptive file name</option>
Doing it that way, the user sees the descriptive text, the server gets a useful bit of information it needs when the form posts.
If that is not an option, you could add an onSubmit event to the form in which you pass the selectedIndex property to a hidden form field, then return true and let the form submit normally.
Form snippet
<form onsubmit="return beforeSubmit()">
<input type="hidden" name="file_index" value="" id="file_index_fld" />
<select id="file_name_dropdown">
<option>...</option>
Javascript snippet
var beforeSubmit = function () {
$('#file_index_fld').val($('#file_name_dropdown').attr("selectedIndex"));
return true;
}
... now in PHP's $_POST variable, you'll see $_POST['file_index'] contains the selectedIndex of the select element.
The long and short of it is that the selectedIndex property is a DOM item and not part of the POST data. No matter what, you are either going to have to intervene with javascript to add the data to POST, or modify your option elements to pass the desired data. I would always lean toward the former route as it is less complex.

Another option I can think of: Before posting, catch the new index in the change-event and write it to a hidden input-field of your form. After that, you can serialize and post it with jQuery.

Related

php : cannot see the hidden value submitted by Javascript

I'm pretty sure I'm missing something simple here, but it's driving me nuts !
This isn't the first form I'm using in PHP, but the first time submitting a hidden value.
When a menu item is clicked, I want to submit the page to itself - setting a simple parameter, so the php code does the processing.
The page gets submitted fine, but the hidden variable I set isn't available through _GET, _POST or _REQUEST. It should be _GET since that is what I've set as the method.
Here is the code if anyone can spot where I'm going wrong..
paramCustom is the one that I'm trying to set and work on.
The menu is a series of DIVs & anchors :
Option Xyz
The activateMenu javascript function is :
function activateMenu(optionTaken)
{
// Set the hidden variable
document.getElementById('paramCustom').value = optionTaken;
// Display it to confirm it is set correctly
var tt = document.getElementById('paramCustom').value;
console.log("paramCustom set to : " + tt);
// Submit the form
document.getElementById('linkSubmit').submit();
return false;
}
The form is coded this way :
<form method="get" action="showProducts.php" id="linkSubmit">
<input type="hidden" id="paramCustom" name="paramCustom" />
<input type="submit" tabindex="-1" style="display:none;" />
</form>
In the php of the same page I'm trying to spit them out but all of them show blank !!
echo "paramCustom get is : ".$_GET['paramCustom']."<br/>"; // This should work
echo "paramCustom request is : ".$_REQUEST['paramCustom']."<br/>";
echo "paramCustom post is : ".$_POST['paramCustom']."<br/>";
OK, problem is that you are not actually stopping the event from firing. So clicking on the link, the function gets called, form submitted but you are not actually stopping the event in the onclick. So form submits but is immediately redirected to the href of the link cancelling the form submit. When the href is blank, it defaults back to the page you are currently on.
The way you are adding the onclick to the link (using an inline attribute) is like wrapping the event in a closure. So when onclick fires, what is really fired is more like function(){ activateMenu('option-xyz'); }. Your call to activateMenu is returning false, but the closure around it is not. You can just add return in front of activateMenu to have the event itself return false and cancel. Change the link like so:
Option Xyz
And then the actual event itself will return false, not just the function.
Here is a simple example to illustrate what is happening.
Doing a little change to the HTML you can set the inline event via Javascript, which is a way better:
<a id="xyz" href="#">Option Xyz</a>
And this is the Javascript edited for your purpose:
function activateMenu(optionTaken)
{
var paramCustom = document.getElementById('paramCustom');
// Set the hidden variable
paramCustom.value = optionTaken;
// Display it to confirm it is set correctly
var tt = paramCustom.value;
console.log("paramCustom set to : " + tt);
// Submit the form
document.getElementById('linkSubmit').submit();
return false;
}
window.onload = (function() {
document.getElementById('xyz').onclick = function() {
activateMenu('option-xyz');
};
});
In PHP, as you know, $_GET gets the parameters of query string, $_POST of the POST data and $_REQUEST is a concat of the two arrays. In this case your method is GET so the value can be retrieved via _GET and _REQUEST, _POST is not going to work. Your code didn't worked to me probably because you had your function defined before DOM was loaded, so the event, when fired, probably throwed an exception.
This doesn't work because you haven't assigned a value. PHP won't recognize a field with a null value.
<input type="hidden" id="paramCustom" name="paramCustom" value="somevaluehere" />
[edit]
After testing this myself, it's because the onclick event is not behaving the way you anticipate. The easiest way to fix this is to use a HREF for you link. It's actually bad practice to rely solely on the onclick event anyway.
Option Xyz
This works perfectly.
The proper way to write an onclick looks like this:
Option Xyz
This works as well.
I've been using JQuery lately and it might be worth a shot.
Download the latest JQuery script and just link it to your page.
function activateMenu(optionTaken)
{
// Set the hidden variable
$("#paramCustom").val() = optionTaken;
// Display it to confirm it is set correctly
var tt = $("#paramCustom").val();
console.log("paramCustom set to : " + tt);
// Submit the form
document.getElementById('linkSubmit').submit();
return false;
}
This isn't that much different than what you had but maybe JQuery will do a better job of assigning the value to your hidden field...
Cheers,
K

Validating dynamic number of form elements in PHP

I need to make a form where client information can be added by people at the administration department. On the first form page, information like client name, address and contact details can be entered, as well as whether or not the client has children.
The form gets validated by PHP. If the client does not have children, the data is saved to the database. If the client does have children, the form data gets saved in hidden form fields, and a second form page is shown, where up to 10 children and can be added.
However, on initial page view, only one text input is visible. With a javascript button, more text input fields can dynamically be added (until the limit of 10 is reached).
The problem is the validation in PHP. If one of the text inputs contains a non-valid string, the form should be re-displayed with the right number of fields, and those containing errors in a special HTML class (in the CSS i give that class a red border for usability reasons, so the user can immediately see where the error resides). However, because the adding of fields happens with Javascript, the form gets re-displayed with only one field.
Any ideas on how to address this problem are very welcome. I'm proficient in PHP, but JavaScript is very new to me, so I'm not able to make big changes to the script i found to dynamically add fields.
I've dealt with something similar in the past. There are a couple of options that come to mind.
Since you have JS code to generate new fields at the click of the button, why not expand that JS function so it can also be called with some parameters passed. If there are parameters, it will populate the fields with existing data.
Then, if the form is being re-displayed due to errors, or for editing, from PHP, pass some information to Javascript so that when the page loads, you create the fields and populate them with data.
To illustrate, I assume you have something like this:
Add Another Child
And you have the function:
function addNewFormField() {
// create new HTML element to contain the field
// create new input, append to element container
// add container to DOM
}
Change it so it is like this:
function addNewFormField(data) {
// create new HTML element to contain the field
// create new input, append to element container
// add container to DOM
if (data != undefined) {
newFormElement.value = data.value;
newContainerElement.class = 'error';
}
}
And from PHP, add some code that runs onload:
<script type="text/javascript">
window.onload = function() { // replace me with jQuery ready() or something proper
<?php foreach($childInList as $child): ?>
addNewFormField({ value: '<?php echo $child['name'] ?>' });
<?php endforeach; ?>
}
</script>
Hope that helps, its a high level example without knowing exactly how your form works but I've used similar methods in the past to re-populate JS created fields with data from the server side.
EDIT: Another method you could use would be to create the HTML elements on the PHP side and pre-populate them from there, but that could end up with duplicate code, HTML generation from JS and HTML generation of the same stuff from PHP. As long as the JS side was smart enough to recognize the initial fields added by PHP you can go with whatever is easiest to implement. Personally I'd just extend your JS code to handle optional data like illustrated above.

How to send info on HTML elements via POST?

I want to send the properties of HTML elements as data via POST, for example whether an element is visible or not?
You cannot do it with PHP and HTML alone, since the HTML form would only post a form input's name. You would need to add some JavaScript, which at the time the form is submitted, would iterate over all its inputs and modify their values to include the attribute values as well.
Example:
yourform.onbeforesubmit = function() {
// Loop over form elements and append -visible or -hidden to its value based on CSS style
// jQuery selectors like .is(":visisble") would help a lot here.
// This is just a basic example though - it would require an explicit visibility CSS rule on each
// input element...
for (var i=0; i<yourform.elements.length; i++) {
yourform.elements[i].value = += "-" + yourform.elements[i].style.visibility;
}
}
Another method would be rather than to modify the values of the inputs themselves, keep a hidden input for each visible user input and set the attributes as the value to the hidden input rather than the visible input.
You can not do this with PHP. You will need to use Javascript to determine this information and then either send an Ajax Request or add this information to an existing form.
To elaborate a bit more: PHP is executed Server Side and then sent to the Client (Browser). The Server is not aware of the state of the HTML Elements in the Browser.
As far as i can tell you have a form that is submitted anyway? So add a piece of javascript which is called before the form is submitted (onsubmit property of the form) and have it read out the status of the elements (visible, hidden, ...) and set this information to some hidden form fields.
Make sure the javascript that is called before the form is submitted is returning true, otherwise the action gets cancelled.
In ajax.
Try Prototype Framework, it is really easy to use!
http://prototypejs.org/api/ajax/request
If you want to do that I suppose you will have to create some hidden fields and javascript that would fill them in with information depending on your elements attributes. As far as I know there is no other way.
You have to define your data definition standard first: what do you want to store, and under what name.
then, imho you have to serialize the result and send it through POST, for finally unserializing it once at the server.
Use JSON serialization for an effective way of proceeding.
Include Hidden inputs using PHP like the following:
<input type="hidden" id="hidden1" name="hidden1" value="<?php if(condition) echo "default"; else echo "default";?>">
This default value can be set by PHP during page load, for transferring extra hidden data from one page load to another. But can also be modified by javascript after page load:
<script type="text/javascript">
document.getElementById("hidden1").value="true";
</script>
Note: PHP can change the value of any hidden or non-hidden element only during the next page load. It doesn't have any control over the HTML it sends to the browser. This is why you need Javascript(Client side scripting).

Accessing text in a field placed by JS, via PHP

In PHP, in a particular CMS I am using a custom field, which works like google suggest.
As in, for each letter I type an SQL query is performed and matching records are displayed. When clicking on a record it fills the field with that record.
I am fairly certain this is all done with JavaScript.
I need to know how I can access the resultant content of that field, with the text placed through JS, before it is submitted so I can explode() it.
The CMS I am using is using mootools, so a solution relying on mootools would be ideal.
(This answer assumes that you have control over the markup of your forms (the form that requires a string "explosion" before submit) and/or you feel comfortable tinkering with whatever plugins you're using.)
first, make sure that you aren't submitting your form using an actual submit button (). We'll need to submit the form using javascript after fiddling with the field's contents.
next, make sure that your input box (the one you're grabbing text from) and your hidden inputs have unique ids. This will make it easier to query the DOM for the data we need.
Inside your form, in place of a "real" submit button, create a form button:
<form action="something.php" name="myform">
<input type="hidden" id="hiddenItem">
// SOME STUFF
<input type="text" id="autocomplete_field" value="whatever"/>
// SOME OTHER STUFF
<input type="button" value="Submit" onclick="processForm(this)"/>
</form>
Then, write a javascript function to process the string and submit the form:
processForm = function(el){
text = $('autocomplete_field').get('value');
// Lets assume the strings separates words (what you're exploding apart) using spaces
// something like 'DOGS CATS BIRDS PETS'
var array = text.split(' ');
// returns ['DOGS','CATS','BIRDS','PETS']
$('hiddenItem').set('value',array[0]);
// #hiddenItem now has the value 'dogs'
//SUBMIT THE FORM
el.getParent('form').submit();
};
Hope this helps!
You could try to use JS to send the field on some event (onkeyup?) to your php script. After it does it's part, store the result as a session variable and you can retrieve that later.
Try using jquery's get function.
Was that your question?

Add and remove form fields in Cakephp

Im looking for a way to have a form in cakephp that the user can add and remove form fields before submitting, After having a look around and asking on the cake IRC the answer seems to be to use Jquery but after hours of looking around i cannot work out how to do it.
The one example i have of this in cake i found at - http://www.mail-archive.com/cake-php#googlegroups.com/msg61061.html but after my best efforts i cannot get this code to work correctly ( i think its calling controllers / models that the doesn't list in the example)
I also found a straight jquery example (http://mohdshaiful.wordpress.com/2007/05/31/form-elements-generation-using-jquery/) which does what i would like my form to do but i cannot work out how to use the cakephp form helper with it to get it working correctly and to get the naming correct. (obviously the $form helper is php so i cant generate anything with that after the browser has loaded).
I an new to cake and have never used jQuery and i am absolutely stumped with how to do this so if anyone has a cakephp example they have working or can point me in the right direction of what i need to complete this it would be very much appreciated.
Thanks in advance
I would take the straight jquery route, personally. I suppose you could have PHP generate the code for jquery to insert (that way you could use the form helper), but it adds complexity without gaining anything.
Since the form helper just generates html, take a look at the html you want generated. Suppose you want something to "add another field", that when clicked, will add another field in the html. Your html to be added will be something like:
<input type="text" name="data[User][field][0]" />
Now, to use jquery to insert it, I'd do something like binding the function add_field to the click event on the link.
$(document).ready( function() {
$("#link_id").click( 'add_field' );
var field_count = 1;
} );
function add_field()
{
var f = $("#div_addfield");
f.append( '<input type="text" name="data[User][field][' + field_count + ']" />' );
field_count++;
}
Of course, if a user leaves this page w/o submitting and returns, they lose their progress, but I think this is about the basics of what you're trying to accomplish.
This was my approach to remove elements:
In the view, I had this:
echo $form->input('extrapicture1uploaddeleted', array('value' => 0));
The logic I followed was that value 0 meant, not deleted yet, and value 1 meant deleted, following a boolean logic.
That was a regular input element but with CSS I used the 'display: none' property because I did not want users to see that in the form. Then what I did was that then users clicked the "Delete" button to remove an input element to upload a picture, there was a confirmation message, and when confirming, the value of the input element hidden with CSS would change from 0 to 1:
$("#deleteextrapicture1").click(
function() {
if (confirm('Do you want to delete this picture?')) {
$('#extrapicture1upload').hide();
// This is for an input element that contains a boolean value where 0 means not deleted, and 1 means deleted.
$('#DealExtrapicture1uploaddeleted').attr('value', '1');
}
// This is used so that the link does not attempt to take users to another URL when clicked.
return false;
}
);
In the controller, the condition $this->data['Deal']['extrapicture1uploaddeleted']!='1' means that extra picture 1 has not been deleted (deleting the upload button with JavaScript). $this->data['Deal']['extrapicture1uploaddeleted']=='1' means that the picture was deleted.
I tried to use an input hidden element and change its value with JavaScript the way I explained above, but I was getting a blackhole error from CakePHP Security. Apparently it was not allowing me to change the value of input elements with JavaScript and then submit the form. But when I used regular input elements (not hidden), I could change their values with JavaScript and submit the form without problems. My approach was to use regular input elements and hide them with CSS, since using input hidden elements was throwing the blackhole error when changing their values with JavaScript and then submitting the form.
Hopefully the way I did it could give some light as a possible approach to remove form fields in CakePHP using JavaScript.

Categories