Store input field value in session without form submit - php

How can I store input field value in session without form submit?
<input type="text" size="3" name="quantity" id="quantity" value="<?php echo $product_quantity; ?>" />

PHP does not interact directly with the browser. You'll need to use javascript to obtain the value of the textbox and then append it to the url (GET OR POST).
I don't understand why you cannot use a form - they're there for the purpose of passing data to pages.
PHP is server side, as in once the page has been sent to the browser from the server, PHP is useless and has no control. PHP can process forms, use variables etc.
Javascript is the opposite. It only works once the page is sent and is entirely reliant on the browser. It can be used to auto fill forms and even submit forms for you. Because it is browser dependant, if your visitor has turned off javascript, is will not work at all.
AJAX is between these forms, so it can auto submit forms, process variables etc... It's
simply an extension of javascript, so if you know javascript, AJAX isn't that much more work.

Related

How to clear an HTML Form, even the form's initial values?

I have an HTML form that sends information via post to a PHP file.
On the user's second visit the page should remember the last search input. So if on their first visit they were looking for pencil then on their second visit, the form would already have prefilled the Product Name input with pencil. I'm doing this via a session variable that is shared between the two files.
For example this is what my code looks like:
<label for="minPrice">Minimum Price</label>
<input id="minPrice" type="text" value="<?php echo $_SESSION['minPrice'];?>" name="minPrice">
<input class="clearForm" type="reset" value="Clear Form">
As you can see, I'm setting the value of the input field using the session variable. Which means the initial value on the second visit of the input will be the value of $_SESSION['minPrice'], so the typical type="reset" for clearing forms doesn't work. Reset just resets the form to it's initial values.
My first thought was to unset the session variables, but that wouldn't change the current values in the input fields of the form.
There are 2 ways to make it happen
Using PHP session the correct way
Using Javascript local storage
Using PHP sessions
Make sure your .php file has session_start() at the top.
Now you need to request the server to save the value(s) you wanna use on "the next visit". This means, requesting the server without refreshing the page through an HTML form submit, using AJAX.
Following JS snippet will post a form to the server, you can modify what to post as easily as eating an apple pie.
fetch(url, {method: 'POST', body: new FormData(form)})
But you have to POST when the user types something so add an eventListener that triggers the fetch method.
document.getElementById('minPrice').addEventListener('keydown', () => {fetch...})
url is the name of the file or the url you wanna POST to,
form is the form you wanna submit, in case you wanna submit some input field(s) alone, replace new FormData(form) by {minPrice: document.getElementById('minPrice').value} and so on.
assign the fetch method to a variable and you can get the server's response using
variable.then(res => res.json()).then(response => //do whatever you want)
On the server side, get the value(s) using the superGlobal $_POST, such as $_POST['minPrice'] and you can save it in the $_SESSION['minPrice'] variable and whenever the user reloads or makes a second visit, the $_SESSION['minPrice '] will assign the last written minPrice to the input field.
Using Javascript local storage
localStorage is built-into javascript and is quite easier to use. Read more about localStorage on MDN docs. Use
localStorage.setItem('minPrice', document.getElementById('minPrice').value)
And assign the localStorage value to the field on every page load.
document.getElementById('minPrice').value = localStorage.getItem('minPrice')
That's it!
Take a look at this !
Make page to tell browser not to cache/preserve input values
Stop browser from filling textboxes with details
Alternatively, try adding this in Jquery :
$("form :input").attr("autocomplete", "off");
Use JavaScript to clear out the values of the form fields.
Something like:
<button onclick="() => {
document.querySelectorAll('input').value = '';
}" />
That way when you click the reset button, it sets all inputs value to empty string.
If you're never going to want the field autofilled by the browser it seems like you'd simply want to use the autocomplete="off" flag on the input field you desire to be dynamically filled by your php script.
You can read more about the specific of this on the MDN docs.
Basically though you'd take the input, store it as a session variable, load the next page and populate the search variable into the input field as a value and turn the autocomplete functionality off so that the browser cannot override the value you provide from the session value.
The support for for this seems fairly broad. and should in most cases prevent the browser from overriding whatever it has stored for the field.
If you're still running into issues with it filling you cvould maybe look to adding some javascript functionality with the reset() function. However depending on how this is fired it might actually end up overriding whatever you populate with the PHP function at the time the DOM is actuall rendered

Prevent a line of source code from showing

How to hide this html line, that will not appear for the user in inspect element or view source.
<input type="hidden" name="kda" value="<?php echo $code;?>">
how can I do this?
You can't do that - everything you send to the browser can eventually be read and stored somehow.
What you can do instead, however, is using a session to store this information. Then, only a session identifier will be sent to the browser (and back to the server) while your sensitive information can stay on the server.
It's impossible to hide HTML from view source. Any HTML gets sent to the client and can be viewed in view source. Try storing it in $_SESSION, a PHP superglobal. It gives the user a cookie that tells PHP where to look to find that user's information in $_SESSION.
$_SESSION is an array. That means you can store $_SESSION['pies_bought'] = 7 and $_SESSION['cakes_bought'] = 3.
http://www.php.net/manual/en/session.examples.basic.php
If you "hide" it, it won't work.
You could surround in PHP comment so it's stripped when the server renders the page, but I think you are asking to hide the value of this hidden form field, and that you can not do as you are suggesting.
You could post the "viewable" form fields to another php script that then adds this "confidential" key, and then submits the form wherever it's going.
You could, upon submission of form, call an ajax request to get the value and submit all at once.
Many ways to skin a cat.
Set this flag as a PHP variable instead of actually including the hidden input field in the form.
You may use encryption if you still want to use it as a query parameter in your form otherwise session is your best bet.
<input type="hidden" name="kda" value="<?php echo some_php_crypt_function($code);?>">
When you receive kda on the server,just decrypt it and get the value.
This link http://www.php.net/manual/en/mcrypt.examples.php has examples of how to use encryption/decryption in php.

What's the easiest way to re-populate a form when the page is reloaded?

What's the easiest way to re-populate a form when the page is reloaded? Is there a script in jquery, php, or javascript/ajax that would achieve this?
If the submitted failed, I want the user to go back. My problem is all my CSS hovers and background-changes don't work via keyup.
If you mean reloaded before it is submitted you will need to use JavaScript to capture and store the values in a cookie, or to the server using Ajax, and then refill the form on page load.
If you mean after it is submitted then will need to use PHP to re-populate the form with the submitted form values:
<input type="text" name="somefield" value="<?php if (isset($_POST['somefield'])) echo htmlspecialchars($_POST['somefield'], ENT_HTML5, 'utf-8'); ?>">

JS/PHP: Who is responsible for generating the content?

Here's a situation which I have encountered, creating a form on the client side and using PHP to process. Here are some considerations
The PHP script generates the form and send to the client side. This is because of internationalization issues
The client side uses JavaScript to submit form; the ID of the form is hard-coded inside the JavaScript as it is generated by PHP. This means everytime the PHP code is updated, the JS must change.
The question here is, who should be dependent on who? Should the JS generate the form instead, so that the PHP script has to know the names of the form elements? OR should it be the other way round?
PHP should generate the Form + a hidden field with the ID of the Form.
then the javascript submits the form.
Thats how I would do it...
If the Form is being generated from the PHP Script, then it should be easy to (as #xXx suggested) have that script add the relevant ID to the form for later processing. Whether that ID is added as an "id" attribute for the "form" element, or as a hidden "input" field would be dependent on a number of factors.
The Javascript, rather than needing a hard-coded value within itself, should be configured to (if needed) find the ID within the form, as set by the PHP Script above.
Of course, this advice is a little airy-fairy as I have no idea how your solution has been designed.
But, for some visual aids:
In the PHP Script creating the Form
<?php
//After the Form open tag has been echo'd
//Assuming $formID is the Form's ID
echo '<input type="hidden" name="formID" value="'+$formID+'">';
?>
Which would create something like
<form ... >
<input type="hidden" name="formID" value="1234">
...
</form>
And then the Javascript should be able to do something like
//Assuming Javascript variable "targetForm" is pointing at the above form object
formID = targetForm.formID.value;

Form Textbox Caching Problem

I have a PHP form, with various input fields and textboxes. If you submit and go back, all of the data that was submitted in the input fields remains, however the textboxes are blank. How can I get the data entered in the textbox to cache like the regular text inputs?
This is a client-side issue. Although there's no way to force the browser to cache the textarea input you can send the data back yourself using cookies if you want. One easy way to do so would be to store the textarea input in cookies when the form is submitted and then to check for the cookies and insert the values into the page source on subsequent requests to the server.
Check out this page for information on setting the cookies and this one to learn how to access the information the next time your form is accessed.
I generally prefer the back button myself, but if you want to re-populate all your fields, an alternative is to have the form page submit to self and then do like this:
<form action="whatever" method="POST">
<input type="text" size="20" name="text_field" value="<?php echo $_POST['text_field']; ?>">
<textarea name="text_area"><?php echo $_POST['text_area']; ?></textarea>
<input type="submit" value="Submit">
</form>

Categories