I am building an ecommerce site on Wordpress to be used by multiple agents. At present, the page uses a standard PayPal link which includes the line:
<input type="hidden" name="business" value="somewhere#this-site.com">
My theory WAS that I could use PHP to get new user's business email address from my site, and then use javascript to change the value. For test purposes, I 'faked' the former, and so used this code ...
<script language="javascript">
// alert(document.getElementsByName('business').value);
document.getElementsByName('business').value='changed#paypal_address.com';
alert(document.getElementsByName('business').value);
</script>
IN THEORY, the page should now have a revised "business" field - but it stayed the same. So I added the second commented out alert ... which - when the page was reloaded - came back as 'undefined'
I cannot check data via forms as there are several (un-named) forms on the page, (such as form buttons with no action field that are used as delete items from cart buttons, and the PayPal webscr form which is also un-named)
Although the code is in a footer widget, I know it's loading / running as I get the alert pop ups. It also executes PHP code within the footer as it loads the page.
Is there a restriction whereby "hidden" fields cannot be found, or altered dynamically? If so, is there any work around?? (If all else fails, will have to contact the UltraCart pugin team to see if the business name can be set at source)
Try this:
function setValueForElementsByName(name, value) {
var elements = document.getElementsByName(name);
for(var e in elements) {
elements[e].value = value;
}
}
setValueForElementsByName('business', 'changed#paypal_address.com');
getElementsByName returns a NodeList. Therefore, you need to access individual items by index like
document.getElementsByName('business')[0].value
If you wish to modify multiple elements with the same name, simply iterate over them like
var elements = document.getElementsByName('business');
for(var i=0; i < elements.length; i++){
elements[i].value = ...;
}
document.getElementsByName('business')[0].value='changed#paypal_address.com';
alert(document.getElementsByName('business')[0].value);
<input type="hidden" name="business" value="somewhere#this-site.com">
Related
I'm using Javascript to create more form fields, to be more specific I'm using jQuery append() to create copies of form fields I already have when a button is pressed.
For example there is an exercise form field, then when someone presses the + button they get another form field to add a second exercise. Now I have to get all these exercises into a PHP file, with no limit so someone could add a 1000 exercises and they would all get sent to my PHP.
I have it setup so jQuery gives them all a name tag with exercisex, the 2nd x being the number of the form field, so the original is exercise1, the second one exercise2, etc.
Now I submit the form and it gets send to another file, submitted.php.
In this file I have it setup for the original form field like this:
$exercise1 = $_POST['exercise1'];
and to put it in an array
$arrExercise = array (
>"exercise1" => $exercise1 );
What I'm looking is for a way that PHP automatically adds this:
$exercise2 = $_POST['exercise2'];
$exercise3 = $_POST['exercise3'];
and adds to the array
"exercise2" => $exercise2
"exercise3" => $exercise3
etc. for all the numbers ofcourse
Now obviously I can't add a unlimited amount into this myself so I was wondering how to get PHP to add them automatically according to how many were added.
I see the obvious risk that someone could spam it by adding a million exercises but that's not a concern for the environment this will be used in.
I tried a for loop but got stuck eventually:
I don't remember the exact code but I tried to add a variable, lets call it n, this variable would get a +1 everytime I pressed the + button so if n=1 at the start, pressing the button once makes it 2, then 3, then 4 etc. and then I got stuck thinking I'd still need to add an infinite amount of
$exercise + n = $_POST['exercise' + n];
if that would even work anyways.
Thanks for any help in advance.
I just solved a similar issue yesterday - here's how.....
The 'key' is to get the form names setup before sending to PHP.
(as you didn't give examples of your form, I will use mine for example - easy enough to port over to your project)
In my project, the user is allowed to add custom menu (nav bar) items as well as links under it, etc.
The way I solved it was to name things where PHP would get a nicely formed array in the $_POST;
<input type="text" name="menu1[Name]" value="">
<input required type="text" name="menu1[data][1][text]" value="">
<input required type="text" name="menu1[data][1][link]" value="">
'rinse/repeat' for all the form values that get added (replacing the '1' in the name with your variable) - you would also replace all 'menu1' with your 'exerciseX'
Now, put a 'Submit' button on the page;
<button type="button" id="custommenusave">Save Changes</button>
A bit of jQuery makes simple work of it....
$("#custommenusave").click(function () {
update_custom_menus();
});
function update_custom_menus() {
var form = $("#form_custom_menus");
$.post("../data/ajax.php", 'function=set_custom_menu&' + form.serialize(), function (data) {
form.submit();
});
}
PHP gets a nice array to work with (I've done a json_encode to make it simpler to see....)
{"menu1":{"Name":"'my menu #1'","data":{"1":{"text":"first","link":"https:\/\/example.com","options":"tab"},"2":{"text":"the second link","link":"http:\/\/example2.com","options":"tab"}}},"menu2":{"Name":"'menu #2!!!!'","data":{"1":{"text":"link in menu #2","link":"https:\/\/example.com","options":"tab"}}}
Then, pull your user's answers and work with them (of course, you should clean any data that comes from a user - no matter how much you 'trust' them!)
This should give you an idea of at least one way (with working code) that you can go.
name of your input should be an array so you can add multiple inputs by same name
<input required type="text" name="exercise[]">
$count = 1;
$finalArray = array();
if(is_array($_POST) && count($_POST) > 0){
foreach ($_POST as $value) {
$finalArray['exercise'.$count] = $value;
$count++;
}
}
print_r($finalArray);
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.
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).
I am trying to create a list of links that would make up the elements of a form (will be used as a search feature).
Basically, each link in the list represents a search category, so as users click on a link, their search results will be filtered.
I would need a category value to be able to be passed whenever someone clicks on one of those category links, and also have each link act as the form submit as well. Is that possible?
(There may be easier ways to accomplish this, however with the CMS and search module I'm using, this will have to do.)
Are you trying to pass values via both POST and GET? I am not sure that that would work. Why not just used hidden form fields? In your form, add a number of <input type="hidden" name="foo" value="bar"> and each one of them will be passed back to the server along with all the regular form fields.
Note: Hidden form fields can be read and edited by a sufficiently tech savy user (it is not too hard), but this would be the case with any variables that you are passing between the server and client, even cookies.
If you give the links an internal data-category attribute like this:
Foo
then you can do with jQuery:
$('a[data-category]').click(function() {
filterResults($(this).data('category')); // call the function that filters
// results according to chosen
// category
$('#theform').submit();
}
You can do something along the lines of...
Puma
and use the a script like...
$('a.category').click(function(e) {
$('#someForm input[name=category]').val( $(this).text() );
$('#someForm').submit();
});`
I'm not 100% sure what you intend to do with the data from the link, or even which part of it you need, but I hope this helps.
<form name="myForm">
link
</form>
<script>
function submitMyForm(link){
var mylinkText = link.text;
var myLinkHref = link.href;
document.myForm.submit();
}
</script>
If you need the link clicked to come across as part of your form data, perhaps you could put it in a hidden field on the form... something like:
document.myForm.myHiddenLinkField.value = mylinkText;
Since the jQuery tag has been removed, here's an example of doing this form submit with pure javascript:
http://www.neubreed.com.au/blog/2010/07/submit_form_anchor_tag_using_javascript_and_supply_action
You can create an extra hidden input like in the example to set your category:
function submitForm(id, category){
var myform = document.getElementById(id);
if (document.createElement) {
input = document.createElement('input');
input.type = 'hidden';
input.name = 'category';
input.value = category;
myform.appendChild(input);
}
myform.submit();
return false;
}
Then, in your form:
click
You could work with a hidden field.
<form id="cuteform" action="thedestiny.php">
<input type="hidden" id="filter"/>
</form>
<a onclick="javascript:linkaction(this);" id="linkA">blablabla</a>
<a onclick="javascript:linkaction(this);" id="linkB">blablabla</a>
<script>
function linkaction(link) {
// get the field
var f = document.getElementById("filter");
// then you could use some of the link element's property like id or innerHTML
f.value = link.id;
// or you could use a switch structure
switch (link.id) {
case "linkA": f.value = "the huge filter string"; break;
case "linkB": f.value = "another stuff"; break;
}
// submit the form
document.getElementById("cuteform").submit();
}
</script>
I'd be inclined to style an actual form button as a link using CSS.
So essentially for each "link":
<form method="get">
<input type="submit" class="form-link">
</form>
For the CSS (off the top of my head) something like this should do it:
.form-link {
background-color: transparent;
border: none;
text-decoration: underline;
color: #00f;
}
That way it isn't dependent on JavaScript to work and users without it will still be able to make use of your site. Additionally, inline event handlers (onclick) etc shouldn't be used as they mix semantics with behaviour. If the functionality isn't core to the experience and (perhaps therefore doesn't require a base non-JavaScript version) then write the links into the page with JavaScript from an external JavaScript include. You won't then have a bunch of dead links in the page for users that visit your site with JavaScript disabled or from a non-JavaScript capable device.
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.