How to send info on HTML elements via POST? - php

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).

Related

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 get selected index of dropdown from PHP post

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.

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.

how can i get values from multiple forms and submit them?

I have several forms inside DIVS on my page.
I have one form which contains a text field and is always visible, and this is where the user hits 'enter' key and submits...
I want to get values selected in the other forms on the page, and submit them all together, not one by one, so that my PHP code can use "ALL VALUES" and search a mysql database...
Is this possible by javascript using the "<form onsubmit>" to call a javascript?
any codes would be appreciated...
thanks
Without some Javascript hocus-pocus, you can't. One form = one request.
You can do it with JS, and you have a few options. The easiest would be to loop through all the forms on the page, and basically duplicate all the input fields and values into one form and then submit that combined form.
With jQuery it'd go something like this:
$("form").submit(function() {
combineAndSendForms();
return false; // prevent default action
});
function combineAndSendForms() {
var $newForm = $("<form></form>") // our new form.
.attr({method : "POST", action : ""}) // customise as required
;
$(":input:not(:submit, :button)").each(function() { // grab all the useful inputs
$newForm.append($("<input type=\"hidden\" />") // create a new hidden field
.attr('name', this.name) // with the same name (watch out for duplicates!)
.val($(this).val()) // and the same value
);
});
$newForm
.appendTo(document.body) // not sure if this is needed?
.submit() // submit the form
;
}
You need to make a script which will collect the data from the forms, and inject them into the only form that is visible. Only one form will be submitted, you can not submit multiple forms.
You can create multiple hidden fields, or you can construct a single hidden field in that form, then use javascript to collect all the data from the various forms, then create a JSON string, set the value of the hidden one, and submit.
Edit:
Say you have a single hidden input like this:
<input type='hidden' name='hiddenfield' id='hiddenfield' />
you could use JQuery to do this:
$('#hiddenfield').val('myvalue');
To get the value from other forms is as simple as calling $('#elementid').val()
before form submission. To use JQuery, go to the jquery website, download the library, and link it (follow their installation guide).
you can add an onsubmit to that form, and then collect other values with javascript:
<input type="hidden" name="hidden1" id="hidden1" />
<input type="hidden" name="hidden2" id="hidden2" />
<script>
document.getElementById("the_form").onsubmit = function(){
document.getElementById("hidden1").value = document.getElementById("other-field1").value;
document.getElementById("hidden2").value = document.getElementById("other-field2").value;
};
</script>
Wrap the whole Page in your form tag (if possible) and use the server side code, along w/ Javascript, to handle your business rule validation.
kind of a hack solution, but it should minimize the necessity for Javascript "hacks" depending on your skill level with javascript.

Categories