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.
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 am having a problem where I am successfully setting a URL variable in the form of mywebsite.com/contact/?product=VAR1 from one page to another, and it will be read on the 2nd page with my simple code.
First use is fine but any thing after that is not. There is a problem with the variable not being cleared/re-read/reset. The URL Bar even reads fine in the URL bar mywebsite.com/contact/?product=VAR2 so that first part works.
But the code doesn't want to get the VAR2 part once it has stored VAR1. It just keeps re-displaying VAR1 once it is loaded once.
<?php echo htmlentities($_GET['product']); ?>
If it makes a difference, I am succesfully displaying the ?product= information inside of a jQuery value changer with this:
$(".input-text").val('<?php echo htmlentities($_GET['product']); ?>');
I have tried my own solutions like putting in a unset($product); before the last ?> but no avail.
I have a limited knowledge of PHP/jQuery and would like to use this way of setting/grabbing variable since it is simple. I am using it in jQuery because it can re-write the exact form input-box value with this variable passed along, and successfully send it in my CMS's contact form.
------------------------ updated: added code ------------------------
(I am just displaying all the code logically as I can think of)
#1: Set up the variable into the URL. The first echo getURL displays the url, I add my ?product= and then it gets the item name. This is all fine.
<a href="<?php echo Mage::getURL('webforms/index/index/id/2') ?>?product=<?php echo $_product->getName(); ?>">
#2: My form is set up within my CMS. It has a special class so I can select it exactly within my jQuery. I do not have access to all of this, it is generated by the CMS. The purpose obviously is to get selected products to be rememmberd via this Variable, and serve purpose in the contact form.
<div class="field webforms-fields-enquiryfield">
<label for="field_20">
Product in Enquiry
</label>
<div class="input-box">
<input type="text" name="field[20]" id="field[20]" class="input-text" style="" value="">
</div>
</div>
#3: Now that my area to display, & variable are set up, we use jQuery to insert the variable into the actual value of the input-text form. I am doing this because within my CMS I am not able to simply add it in. I have to use jQuery to replace the text (which is empty box anyway).
$(".webforms-fields-enquiryfield .input-text").val('<?php echo htmlentities($_GET['product']); ?>');
Hope that made more sense.
I have figured the answer to this, the problem was that the CMS Magento likes to cache certain blocks - which is why I could view it first, then my CMS would store the variable but not erase it. No matter what kind of fixes I tried to disable caching, no go.
Instead I ended up using the following code, using a # variable, and some simple JavaScript that anyone can understand. I will be using this in future projects no doubt! Very easy variable passing ...
if(window.location.hash) {
var hash_value = window.location.hash.replace('#', '');
$("my-css-input-field-or-whatever-you-want").val(hash_value);
}
The hash_value can be used in a variety of ways now I suppose, and this works well around my Magento set up, it does not get cached/stored. Grabbing the URL location & hash instead.
(And the PHP used, simplified for anyone to replace/reuse within a CMS)
<a href="[GetBaseURLfromCMS]#[MyDynamicVariableHere] ">
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.
I've never really thought about this, but it helps with some security of something I'm currently working on. Is it possible to submit GET data without an actual input field, and instead just getting it from the URL?
If so, how would I go about doing this? It kind of makes sense that it should be possible, but at the same time it makes no sense at all.
Perhaps I've been awake too long and need some rest. But I'd like to finish this project a bit more first, so any help you can offer would be appreciated. Thanks
Yes. If you add some query-string to yourl url, you can obtain that in php using $_GET without form submitting.
Going to this URL adress http://yoururl/test.php?foo=bar cause echoing foo (if there will be no foo query string, you'll get warning).
# test.php
echo $_GET['foo'] # => bar
Is this what you mean?
Link
// page.php
echo $_GET['type']; // foobar
This is what I understand of your question:
You have a <form method="get" action="foo.php">-like tag on your page
You have a series of <input type="text" name="bar"/> in your page
You want to pass additional GET parameters that are not based on an input from the form
If so, it is possible, but I hardly see how it could help with security. Input from a client cannot be trusted, so even if you hardcode the GET value, you have to check it serverside against SQL injection, HTML injection/XSS, and whatnot.
You have two ways:
Use a hidden input: <input type="hidden" name="myHiddenGetValue" value="foobar"/>
Add the GET parameter to the form action: <form method="get" action="foo.php?myHardcodedGetValue=foobar">
If what you meant is that you want to have a GET request without a form, you just need to pass all the GET parameters to the href of a link:
Click here!
Yes it's possible. Just append the GET data to the link.
For example:
<a href="main.htm?testGet=1&pageNo=54>Test</a>
You can also use Javascript to build the url.
If you happen to be using jQuery and want to build the GET data dynamically you can do this:
var getParams = { testGet:1, pageNo:54 };
$(".myLink").attr("href", url + "?" + $.param(getParams));
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.