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

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;

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

get value DIV in PHP

I want to get DIV contents in PHP to submit a form.
<div id="hello"></div>
In my search, I was advised to use <input type="hidden" but I do not know how to do.
If you are obtaining the HTML as a string, or even if its a remote web page, you will need a HTML parser. There are lots of these for PHP and the question has already been asked and answered. How do you parse and process HTML/XML in PHP?
If you are looking to do this on click or some other page event when a user does something, you need to use javascript instead of PHP. PHP is a server side language and cant be used to access elements in the users web browser, you need to use javascript for this.
If you don't want to use an input field to show a value (perhaps because you don't want the user to modify it or for styling reasons). You can display it in a div, and pass the value with the form submission by duplicating the value in a hidden input positioned inside your form. The div may be inside or outside your form.
<div id="user">Jaber</div>
<form>
... any other form fields
<input type="hidden" name="user" value="Jaber">
... submit button
</form>

How can I make a form post to a url determined by the value selected in drop down?

I'm writing a simple PHP program with a form that has multiple fields to be filled in.
Among the fields is a <select> box.
I want the same form to post to 3 different URLs, determined by which of the three values have been selected in that <select> box.
How do I code something like this in PHP (with a typical HTML form)?
Any code samples/guides would be helpful.
I (being a newbie) am especially confused about this part: The form opening tag already specifies the target URL, so how can I change this later, depending on the input given by user in the drop down box, as the drop down box's HTML code is after the opening form tag(which already declares the form's target URL)?
You can use JavaScript like this:
<form method="get" action="http://example.com/url1">
<select name="_" onchange="this.form.action=this.value">
<option value="http://example.com/url1">URL1</option>
<option value="http://example.com/url2">URL2</option>
</select>
<input type="submit" value="Submit" />
</form>
Whenever the value in <select> changes, the form's action is updated to the required URL.
You can't do this in PHP. You must dynamically alter the form's action attribute with JavaScript to point to the URL you wish the form to submit to.
This can only be done in JavaScript, as only JavaScript has access to the client's browser where the form is being interacted with.
The alternative would be to have your form always submit to the same URL, and handle the submitted data with branching logic in PHP. I would prefer this method, as there is no requirement for JavaScript on the client.
With javascript you could grab the value of the drop down option selected and populate the form's action attribute.
With php, you could have one "results.php" page that could repackage the $_POST vars and send to the correct URL based on the $_POST['send_to_this_url'] var.
I'd do the JS version.

Unable to pre populate form with url

I am trying to pre-populate a set of form fields by passing info via parameters in the URL. I have been able to do this with html forms before by simply adding the parameters to the URL, for example ?name=John. The variable I enter usually appears in the form field.
I am finding that this approach is not working on the latest form. I have been able to identify the parameter names but when I add them to the end of the URL they are not populated in to the form.
For example using website.co.uk/admin/usersearch.php?email=test#test.com I would expect the email field to be populated with test#test.com but the page refreshes and the form is still blank.
Is this because it is a .php form? Is there anyway round this? I only have the options to use the URL or javascript.
Thanks
Give your field value as <?php echo $_GET['email'];?>
Like this :
<input type="text" name="email" value="<?php echo $_GET['email'];?>" />
There is no such default procedure for pre-populating form fields built in to any web server. So, I'm not sure how you got it working earlier. Maybe the developer had actually coded it such that the form pre-population occurred.
For the new form, you could do as Prasanth suggested. However, since you require only JavaScript or HTML, refer to this prior question for further assistance: How to retrieve GET parameters from javascript?
Basically, what you'll be doing is getting the value of the field from the url and setting the field's value to it in the form using JavaScript.

Change Form Elements Depending On Selected Option

I have seen several sites where there is a form, starting with a dropdown box, and depending on the box chosen there is different form elements, for example, let's say I wanted to make an uploader script, the dropdown box might hold:
Upload
Delete
And is Upload is selected I would want a browse file element, while with Delete selcted maybe only the name should be imputted into a text field. How can I make it do so? I plan on using php for it and using the echo syntax to create the html for the forms, but is ther a way to have, for example an if statment, that changes the other form elements that show based on the option selected.
I have seen people use jQuery for it, but I can ONLY use PHP ad HTML for my project.
This isn't a direct solution but if you intend on carrying out this task exclusively with php/html then you should consider setting up a system such as this in the php file which serves the page.
<?php
/*Check to see if the user has submitted the form*/
if(isset($_POST['action']))
$action = $_POST['action'];
/*If no action has been sent from the client side, generate form*/
if(!isset($action)){ ?>
<form name="test" action="example.php" method="POST">
<select name="action">
<option value="update">Update</option>
<option value="delete">delete</option>
</select>
</form>
<?}
/* if update action, load file dialog*/
elseif($action == "update"){?>
<!-- relevant HTML or action for file load -->
<?}
/*Default to delete*/
else{?>
<!-- some action to place the input field -->
<input name="fileName" value="<? echo $FILE_NAME; ?>" />
<?}
?>
Essentially you're going to have to handle both page serving and form processing within the one page, using the value from the form select element to determine which blocks of HTML need to be loaded. Note that you will still have to provide a submit button for the form in order to trigger the action since there's no javascript events.
I want to distance myself from this solution as I know of it only through experiencing the Dunning Kruger effect and I'm sure the lack of client side involvement will be frowned upon by most.
You can't do what you want in purely server-side code without some sort of submission from the browser to trigger the check. PHP code runs on the server and returns the page to the browser. Once the page has left the server there's nothing PHP can do to it.
Sites I've seen that do this kind of thing on the server-side reload usually have an initial page where you choose the action you want, and then load the form for the chosen action. That's really all you can do without some kind of javascript on the client side.
If you can use javascript then you have many more options:
Trigger a reload of the form when the drop-down box is changed.
Send an ajax request when the drop-down box is changed and dynamically add the HTML returned by the server to the form.
Send fields for all options in the original page, and use the change event on the drop-down to show/hide the relevant fields.
Based on your comments to other answers there seems to be some confusion as to the role of javascript in the application. The server doesn't need to know about Javascript, or even JQuery. The server runs your PHP code to build the HTML for your page. The HTML can reference CSS stylesheets, images, Javascript files, etc, which, as far as the server is concerned, are just static files requested by the browser. Once the client browser gets the javascript file from the server it can execute it and enable whatever dynmiac page behaviour is intended. There is no Javascript code in your server-side application. The application is just a bunch of PHP files, with a collection of other static files to support the generated HTML.
Im no expert, but i guess since PHP is a Server-Side Scripting Language, there is no way to do this purely in php, other than to reload the page evertime you switch the dropdown option. Maybe you could accomplish it with frames (but who wants to use those?).
jQuery is just a pre-written javascript subset, are you not allowed to use javascript? if you can not use it, then your ability for dynamic pages diminishes greatly.
AJAX uses javascript as well and is the solution I use to load dynamic content. do you need examples or a way to do this without javascript.

Categories