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);
Related
I want to add a number of input fields in form which depends on value of previous input fields.
For example:
I have two inputs
if user
1.<tr><td>Number of Articles/Posts/Pages:</td><td><input type="number" name="count" ></td></tr>
2.<tr><td>Keywords:</td><td><?php
$number_of_keywords=$_POST['count'];
i="<input type='text' name='keyword'>";
i++;
i==$number_of_articles;
echo i;
?></td></tr>
For example if user type 3 in count field, then i want to show 3 input field. Number of input fields depend on how much user type in count field.
Please tell me that if this above code will work here and how can i get the count field value at run time?
No, you can't get the count field value at run time, the value must be submitted via a form or passed as a parameter in a query string, so that PHP knows about it.
This question is more appropriated to be tagged as a javascript question, than a PHP question. if you want to do it at run time. If you would like to do it strictly using PHP, then you will have to pass the count value to the server somehow, either by submitting a form, or by sending it via a parameter in a query string, as I have told you before.
Please take into consideration that if this is your real code, it will create n inputs with the attribute
name="keyword"
which is not correct and it might get you into a lot of problems later on.
I would simply use some JS and a php file for this.
What i would do is have an onchange on the first input like
<input type="number" name="count" onchange="getval(this);">
The getval is a JS function that it will according to the input fill in a class with the according number of inputs you like.
function getval(sel){
var load = $.get('yourPHPFILE.php',{number:sel.value);
$(".someClass").html('Refreshing');
load.error(function() {
console.log("Mlkia kaneis");
$(".someClass").html('failed to load');
// do something here if request failed
});
load.success(function( res ) {
console.log( "Success GET VA" );
$(".someClass").html(res);
});
load.done(function() {
console.log( "Completed GET VA" );
});
}
You then in the php file get the value by $_GET['number']
and with a loop there you echo the according number of inputs you like.
someClass is going to be the class that you would like to populate with the inputs.
So I'm trying to pass a javascript function value across pages in an html form. I'm using to show the value, and a hidden input field to store it. Here is my code:
<div class="totalPrice"></div>
<input type="hidden" name="totalPrice" class="totalPrice">
It's part of a bigger form, that gets submitted with a button. On the following page:
session_start();
$_SESSION['totalPrice'] = $_POST['totalPrice'];
On my javascript page, it does the calculations correctly, and here is the javascript function:
function getTotal()
{
var weekTotalPrice = weekPrice();
document.getElementByClassName('totalPrice').innerHTML = weekTotalPrice;
}
Here are the problems:
the class function, getElementByClassName, isn't working because I can't see my total price. When I use id just on with no hidden input field, it works perfectly.
My old code in javascript was the following:
document.getElementByClassName('totalPrice').innerHTML = "Total Price: $" + weekTotalPrice;
However, it still shows the "Total Price: $" part, although clearly I've taken it off. I double checked if I saved my files, and I reset my local MAMP server.
I would love to hear of any solutions to these two problems, much help appreciated. Thanks.
Your getElementByClassName is wrong, it should be getElementsByClassName. Also, getElementsByClassName returns a set of items, not a single item. You'll need to specify which item to use. Contrary to this, you can use getElementById and specify an ID on the element you wish to change to make it easier to handle. Referencing DOM objects by ID's are faster than classes.
Try document.getElementByClassName('totalPrice').innerHTML = " "+weekTotalPrice; and tell me if it printed out correctly.
I hope I'm not posting a duplicate question but I've looked around (and googled as well!) and nothing has given me the answer I'm looking for.
I have a form in HTML. When the user submits the form the values get stored with mysql under their user account for the site.
The issue is, I'd like the user to be able to go back and edit the form any time they like.
I could certainly just populate the form with values from php when the users review the form, but it gets tricky when I try to populate a file input field (and the file has been saved in mysql using the blob type). Not to mention that I'd like to do this as cleanly as possible.
Ideally it would be nice if there was a convenient module for reviewing forms that have already been submitted in JQuery per se.
Can anyone offer any advice? Thanks in advance!
Edit:
Here's a good example of what I mean - in chrome if I fill out a form and redirect to the next page after hitting submit, if I hit back I come back to the form and it's still filled out with the information I entered previously! Could I invoke this behaviour whenever I want to, as opposed to only when the user hits back?
You can't pre-fil an <input type="file" . . but surely when they come back to the form, they want to see the file they've uploaded .. this is what you mean right ..
So if its a picture, you could just do: <img src="loadpic.php?id=$var" />
If it's files they've uploaded, just list the file name / date and other data.. etc in some sort of list.
Then you could still show the <input type="file"> .. but with the label, 'add more pictures' or 'add another file'. .etc
Unless someone has a better way, at the moment I'm using a combination of 2 things:
1) Utilizing the $_SESSION variable
2) Setting the "name" attribute of every input in the form to the name of the field it corresponds to in the database.
This way I can loop through all the values dynamically instead of hardcoding them all in. Some input types (like file) are exceptional and will be handled on their own. Other that I can do something like this:
To insert into mysql:
$fields = array();
$values = array();
foreach ($_POST as $field => $value) {
$fields[] = $field;
$values[] = addslashes($value);
}
$fieldString = 'Table_Name('.implode(', ', $aFields).')';
$valueString = "VALUES('".implode("', '", $aValues)."')";
mysql_query("INSERT INTO $fieldString $valueString");
Reviewing the form is somewhat similar. I am using javascript to hook into document.onload. I need to pass javascript the records from mysql so that it may populate the form. Then it's a simple matter of getting elements by their name and assigning them their values that were passed from php.
The easiest way to do it and not have to go back to the database would be to store the values in a session.
<?php $_SESSION['myvalue'] = $inputvalue; ?>
On the html form use:
<input type="text" name="myName" value="<?php echo $_SESSION['inputvalue']; ?>" />
When completed don't forget to unset the session variable:
<?php session_start(); unset($_SESSION['myvalue']); ?>
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?
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.