jQuery/js val() overwriting PHPs' $_POST['field']. How to fix? - php

I've got a pretty complicated (for me!) form validation to do. I did all js and now I'm doing php stuff.
The thing is I've put a possibility to copy part of the inputs to other, similar section (recipient -> payer). It's all done by jQuery first copying $("input.payer_sth").val() to $("input.payer_sth"), and then doing it again and again on keyup and blur.
All my inputs are built like that:
<input id="payer_name" name="payer_name" class="foo" type="text" value="<?=$_POST['payer_name']?>"/>
as long as the ones that aren't modified by jQuery work all right on submit and "back", the ones that has modified val() are empty on back.
What's obvious for me is that jQuery is overwriting value="<?=$_POST['field']?>" .
How can this be fixed?

Based on my comments above, you may want to do this on server-side instead of client side.
Example (not the cleanest, but you'll get the point)
<input id="payer_name" name="payer_name" class="foo" type="text" value="<?= (!isset($_POST['player_name'])) ? 'Enter your name' : $_POST['payer_name']?>"/>
So what this will do, is if there is no post set it will output "Enter your name" into the field, if the $_POST is set it will output the value of the post into the field.
The construct is called a ternary operator: http://php.net/manual/en/language.operators.comparison.php
You can clean it up a bit on your side, but this will do the trick and it'll avoid the use of JavaScript for something like this where JS should not be required by the end-user.

Related

HTML input tag passing placeholder as value to PHP

I'm trying to implement the 'placeholder' attribute on a new mobile web site. Running into an issue where if a user leaves the field blank (showing the placeholder) then that placeholder is submitted as the field value for PHP to receive and place in the database. Instead it should (I assume) be sending an empty value. This causes problems with server side validation - the receiving PHP script thinks a legitimate value has been submitted instead of an empty value which would throw an error back to the user.
I am hoping there is a quick fix to this issue.
Sample code below:
<form action="somepage.php" method="post">
<input type="text" name="yourName" placeholder="Enter your name here">
<input type="submit">
</form>
PHP sees:
$_POST['yourName'] = 'Enter your name here';
instead of:
$_POST['yourName'] = '';
The latter is what I want it to see.
Any help would be greatly appreciated!!!
* EDIT **
Here is an example form with the problem:
https://www.badgleymischka.com/mobileTest.php
Leave all fields as is (note in the source these are filled in by the placeholders, not the values). Click the "CONTINUE" button and you will see the _POST variables with the placeholder values.
Something is removing the placeholder attr text on page load on several inputs...
Based on your source, you're calling two different jQuery scripts. Delete this found near your closing <body /> tag. This may be conflicting with Foundation's included Placeholder plugin.
<script src="js/vendor/jquery.js"></script>
But this is probably the culprit: Not sure what you're trying to write here. But this looks to be the issue. See line 17 in jquery.main.js. Remove this all. I don't think it's needed and is conflicting.
// clear inputs on focus
function initInputs() {
PlaceholderInput.replaceByOptions({
// filter options
clearInputs: true,
clearTextareas: true,
clearPasswords: true,
skipClass: 'default',
// input options
wrapWithElement: false,
showUntilTyping: false,
getParentByClass: false,
placeholderAttr: 'value' // <-- ding, ding! Prob the conflictor, if not this entire function
});
}
I cannot reproduce your error. I tested it using Firefox 25 and 26, Chrome 31, IE 11, Opera 12.16 and Safari 5.1.7. And looking at the specification I don't believe that the placeholder is intended to be submitted - so you are indeed experiencing some kind of bug.
The only reason for this behavior I can think of is that you are including a (java)script in your HTML, aimed at browsers that don't support HTML5 (and the placeholder attribute). Such a script could be filling empty inputs with their placeholders, but failing to remove them before the form is submitted.
If this is indeed the case, and your problems are caused by such a script, you can solve them by either fixing the script or removing it completely. If you choose to fix the script, you'll need to make sure that inputs whose value equals their placeholder are reset to their default value.
Just stumbled across this in my own search, so if anyone else is looking for an answer to this try this:
<input type="text" name="yourName" placeholder="Enter your name here" required>
By adding "required" to the input tag the user must fill out this field before submitting.
This should work like charm but i assume since its on mobile something is different.
One solution(i am sure there is a better one) is to check it with an if.
So if the value is the same as the place holder then make it blank and then continue your validations.
Also try to put val="".

Simple Calculator without page reload

I have two input boxes, the first input box will accept a value that will be subtracted from the value stored in a cookie. The second input will auto generated the difference while I am typing.
What is the best solution for this?
The best solution is to use vanilla Javascript only.
You can read cookies directly from Javascript:
http://www.quirksmode.org/js/cookies.html
You can make the second input un-editable using readonly attribute:
http://www.w3schools.com/tags/att_input_readonly.asp
You can do math directly in the onkeyup event of the first input:
http://www.w3schools.com/jsref/event_onkeyup.asp
Hook the keyup and mouseup events on the first input box. In the handler do parseInt() on its value, if !isNaN() calculate the difference and write it to the second input box.
I don't see, why you would need ajax for a subtraction!
As cookies can be created, read and erased by JavaScript you can accomplish this task using javascript. As Eugen Rieck points out you can use keyup/down events.
You only need Javascript. Use Serverside (PHP|PYTHON|JAVA|PERL) only if you need to store it on server. Or wants to show results to other people.
For your case , server side is only needed If you want to:
Store it on the server so other people can see it.
Multi User subtraction ?
Log what visitor did.
<script>
function subtract(first, second)
{
total = first - second;
obj("total").value = total;
}
function obj(id)
{
return document.getElementById(id);
}
</script>
<input type="text" id="first" onkeyup="javascript:subtract(this.value, obj('second').value)" />
-
<input type="text" id="second" onkeyup="javascript:subtract(obj('first').value, this.value)"/>
=
<input type="text" id="total"/>

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?

Submitting GET data with no input field?

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

Validating one or the other

I've created a javascript function that allows me to validate if one field or the other is filled (called, shockingly enough, oneortheother). Essentially, it checks if neither is filled, or both, and throws an error.
One of the fields being validated is a input type="file" field. I'm displaying below the field the existing file, so that the users can see if it's the file they want.
Is there any way to still validate via oneortheother without having a value in the input type="file"? Any kind of javascript trickery?
I'm at wits end at this point, and have a demo later today that needs this functionality, so any help would be greatly appreciated.
EDIT:
As requested, here's some examples:
<label for="pdf">Upload PDF:
<span class="fieldnote">Files of type .pdf</span>
</label>
<input type="file" name="pdf" id="pdf" class="external_form_field oneortheother_url" value="/downloads/white_papers/HigherOrderPerl.pdf" />
<label>Existing file:</label><span class="preview">HigherOrderPerl.pdf</span>
<label for="url">Link to asset:</label>
<input type="text" name="url" id="url" class="external_form_field oneortheother_pdf" value="" size="25" />
Notice that the class oneortheother_url and oneortheother_pdf are applied. This allows the validation routine to know which field to compare to. The comparison is:
if (fObj.value && fObj2.value) { }
and
if (!fObj.value && !fObj2.value) { }
I unfortunately I couldn't understand the actual question, but here's a sidebar tip:
The XOR operator can come in handy (though obscure) in cases like this:
if (fObj.value ^ fObj2.value) {
// Only one value is set, we're good
} else {
// Both of them are set or neither of them are set
}
I am not sure how your validation function works, but it seems like you could add a hidden input that holds the url of the uploaded preview file OR the value in the file input. Then you could just compare the url input with the hidden input.
But it seems likely you'll just need to write a custom validation function.
I'm not sure I understand your question completely as it's not clear to me.
You want to check this:
if (fObj.value && fObj2.value) {}
and
if (!fObj.value && !fObj2.value) {}
So why not add this in as well...
if (fObj.value && !fObj2.value) {}
or
if (!fObj.value && fObj2.value) {}
What about adding a radio button next to each option, and allowing the selected radio button to determine which option is used?
I'm not sure exactly what you're trying to do here, but you could add a hidden form field, then attach a function to both the file input and the URL inputs' onchange events, that would set the hidden field to this value.
Fundamentally I'm not even sure that the approach you're currently taking is appropriate - Firefox 3, for example, doesn't let you edit the contents of a file field directly and as far as I can tell gives you no way to "unset" a value. So once a file has been chosen, the "pdf" input will always be non-null, which with the constraints you have set (as I understand them) means that the "url" input is effectively permanently disabled. This is even worse since you give the file input an initial value so that it will never ever be null/empty string.
You may need to take a step back and think about exactly what you're trying to acheive and whether an alternative technique might be better. For example, a radio button to select between the file upload box or a URL resource, which disables and enables fields as appropriate.
Additionally, the fact that most people here didn't understand quite what you're asking even after an edit is an indication that there's something about it that's not too intuitive, and it implies that people who will need to maintain this code in future might go through a similar thing. Again, refactoring the design is probably in order, or perhaps jsut a bunch of descriptive comments.

Categories