Can you make a form with a single HTML file? - php

All of the examples of making drop-down forms that I can find involve having a separate PHP file. I'm trying to embed some code into a Weebly page, so I'm not sure that I can save a separate PHP file on the server. So is it possible to avoid PHP entirely? Maybe do everything in JavaScript and jQuery? Or to put the form and the PHP in the same HTML file?
More specifically what I'm trying to do is make a page where there are several drop-down forms. The user selects several options, clicks submit, the client-side back-end does some computation on the inputs, and prints out a result.
I've been trying to follow this guide for dropdowns: https://www.w3schools.com/tags/tag_select.asp
And I've been following this for using PHP in forms: https://www.ntchosting.com/encyclopedia/scripting-and-programming/php/php-in/
With that guidance I created this non-working code:
<!DOCTYPE html>
<?php
$Level = $_POST["level"];
?>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
</head>
<body>
<form action="<?php echo $PHP_SELF;?>" method="post">
Choose a level: <select name="level" id="level">
<option value="high">High</option>
<option value="med">Medium</option>
<option value="low">Low</option>
</select>
</form>
<p>
<?php
echo "".$Level;
?>
</p>
</body>
</html>
I say that it's not working because when I click on anything in the drop-down, nothing happens.
This further information came from an exchange in the comments:
Ah, this really doesn't need to interact with the server. It's ultimately just going to be a tool so that customers can get an automatically generated estimated quote on a price. So they answer some questions (i.e. select some drop-downs and enter some numbers in fields) and click submit, and the web page spits out an estimate. No information saved or anything like that, so it should be fine to handle everything client-side. From your description, though, it sounds like that can't be done with PHP then. I don't think Weebly will let me change the file extension.

You certainly can. You can use the onSubmit attribute on your form to run some javascript (and by extension jquery) without actually submitting the form. More specifically, it would look something like this:
<form onSubmit="return yourJavascriptFunction()" method="post">
Inside your script, you can get the dropdown values from the form's fields using document.getElementById(yourDropdownID) and perform any necessary actions. If you don't want your form to redirect, just return false; on your function. Using this method, you don't really need a form, and can use some <select> tags with id, as well as a pseudo submit button:
<button onclick="yourFunction()">Submit</button>

if you want to do this with php you have to change the extension as php and add a submit button otherwise you can do this without php easly like below.
<form action="#" method="post">
Choose a level: <select name="level" id="level" onChange="document.getElementById('selectedValue').innerHTML = this.value;">
<option value="high">High</option>
<option value="med">Medium</option>
<option value="low">Low</option>
</select>
</form>
<p> <span id="selectedValue"></span></p>

remove the DOCTYPE html and change the extension of your file to .php

Related

How to output an HTML page based on user input

I want to make an HTML (or php maybe?) page that constructs a new HTML page based on input parameters the user gives to a drop-down box. I just don't know how you handle the input.
Here's my HTML:
<html>
<body>
<input type="number" min="1">
</body>
</html>
Yes I know it's not the full HTML page, but I just want to focus on the <input> tag. I know you probably have to set it equal to a PHP variable maybe?
I want it to generate a different HTML page that looks like this:
<html>
<body>
<p>You have chosen: $input </p>
</body>
</html>
I might be asking this all wrong, but I hope it makes sense what I'm looking for. I need to know how to handle the user input. I couldn't find a thread that discusses this. Do I need to generate a new HTML file? Or just override the current one and maybe have a reset button? I'm so confused.
In the simple case, you'll have two pages: your form and your result page. You can send data from the form page to the results page with one of two methods: GET or POST.
GET means that the data you're sending gets put in the page URL. This is useful because then you can link to a specific version of the results page, but potentially dangerous because you don't want to put sensitive data in the URL bar.
POST means that the data is sent with the HTTP request in the background. This is preferable for something like a password.
The GET and POST data can be read by nearly any server-side language and used to generate HTML on-the-fly. The example below uses PHP.
The form page doesn't necessarily need any server-side code, just basic HTML. Here's a simple example:
<!DOCTYPE html>
<html>
<form method="GET" action="my_result.php">
<input type="text" name="my_value">
<input type="submit">
</form>
</html>
Your second page (the results page) should bear the name that you specified in the form's action attribute. This is the page which will need server-side code. So here is an example my_result.php:
<!DOCTYPE html>
<html>
<p><?php echo $_GET['my_value']; ?></p>
</html>
Obviously, my_value can and should be replaced by whatever you want to call your data, as long as the name attribute of the input element matches the key in the PHP.
This example uses the GET method. You can use POST by changing the method attribute of the form and using $_POST instead of $_GET (if you are using PHP).
If you use $_REQUEST rather than $_GET or $_POST, it finds a value that was passed via either GET or POST. This is usually less safe than explicitly stating how your value was passed.
Addendum: Some servers are configured to disallow you from directly using the values of php superglobals such as $_GET, $_POST, and $_REQUEST for security purposes. That is because you really should always sanitize user input before using it in an application. The type of sanitization required depends on the type of input and how it is being used, and is well outside of the scope of this question. For this purpose, php provides the filter_input function.
The sanitization filter is an optional parameter for the filter_input function, so if you really want to use the data unfiltered, you can simply omit it (but know that this is dangerous). In this case, you can replace all instances of $_GET['my_value'] in the above code with filter_input(INPUT_GET, 'my_value').
This is not a tutorial, but I guide you to some important points:
You can get user input with html by using form element. read more about form and methods of form (GET and POST).
Then, how can you print user input when submitted by user? php supports both (GET and POST) using $_GET and $_POST with input name as key.
Dealing with user-input needs extra care because of security. user might submit malicious content that later attacks you or another user.
Try like below
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<?php
if ($_POST) {
echo "<h3>You have selected ".$_POST['number']."</h3>";
} else {
echo '
<form method="post" action="">
<select name="number" id="number">
<option value="1" >1</option>
<option value="2" >2</option>
<option value="3" >3</option>
</select>
<input type="submit" value="submit">
</form>
';
}
?>
</body>
</html>
To handle a user input you have to use forms
<form action="action_page.php">
<input type="number" min="1 name="my-number">
<input type="submit" value="Submit">
</form>
After user set number and press submit button, you will get the value in action_page.php in $_REQUEST['my-number']

Add additional attributes to GetMenu2 Options

I currently have an box using GetMenu2 and is trying to assign additional java scripts to it. I read the website and it says that I can use "$moreAttr to add additional attributes such as javascript or styles." but I cannot get this to work,
php:
$info=$rs->GetMenu2('assign_val', $employee,$employee_id);
$smarty->assign('employee', $employee);
How can I add additional styles to this or what I really wanted is to add an oncclick event, something like:
onchange="this.form.submit()"
Also
output looks like this
{$employee} outputs:
<form action="" method="POST">
<select name="assign_val" >
<option value='1'>Sam</option>
<option value='2'>Joe</option>
<option value='3'>Steve</option>
</select>
Thanks everyone..
I got this working by reading page 42 on this page..
http://books.google.com/books?id=QlN84kFPPXkC&pg=PA41&lpg=PA41&dq=getmenu2+%3Coption%3E&source=bl&ots=UAoTlAkF8Y&sig=5vGqn0bZDbxbJdd_zbEdWvkVvVI&hl=en&sa=X&ei=WWgaU_ugK4-IkQexyICoDQ&ved=0CEcQ6AEwAw#v=onepage&q=getmenu2%20%3Coption%3E&f=true
working php code..
$tech=$rs->GetMenu2('wo_tech',$login,$login_id,null,null,'onchange="this.form.submit()"' );
So there you go, this is how to add onchange event to GetMenu2

How to run php when an option is selected from a select list?

I would like to have a select list that runs a php database query when an option is selected. I have the code:
<select>
<option value="available">Available</option>
<option value="sold">Sold</option>
</select>
<input type="submit" name="change status">
Say, when a user selects 'sold' I would like to run:
<?php
db_query("UPDATE {product_stock} SET stock='0' WHERE nid='$value'");
?>
I've tried
<option value="sold" <?php db_query("UPDATE {product_stock} SET stock='0' WHERE nid='$value'"); ?> >Sold</option>
but doesn't seem to work.
I don't know if I should be using
<form method="GET">...</form>
I know I can use ajax somehow but I'm really not familiar with it.
Any ideas how to do this?
Thanks
You have to use javascript! Or else you must update your database after form submit.
A possible way with the javascript library jquery would be:
$("select").change(function() {
$.post("/your/url", {option: $(this).val()}, function(return) {
//echo result if necessary
}
});
On server side you should check for $_POST['option'] and update your database after you
ESCAPED
the contents of the variable "option".
You have to send an AJAX call with jquery or plain JavaScript when the combobox got changed.
Depending on the new value, you can send various parameter and call your PHP scripts.
But the interaction between HTML and PHP like you tried will never work. The time you see the combo box in your browser, your PHP commands were already executed.
My site is build on drupal so I created a custom module and used hook_form_alter so I could just use PHP and didn't need to code in ajax.
Well, you will have to create two files one with the form and a second one with the action itself, the first will have something like this.
<form method="POST" action="ActionFile.php">
<input type="text" name="name" id="name" value="">
<input type="submit" value="find name">
</form>
and create a file called ActionFile.php that will contain the variables and the connection to the DB and the select.

IE8 fills form fields with wrong data after hitting Back button

What I need is this:
user loads the page (inputs are null)
user gives some input and submits
the inputs have their new values
user navigates back
the inputs have their previous values
My php file looks like this:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>
<form id="formTest" name="formTest" action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post" autocomplete="off">
<select id="selectTest" name="selectTest">
<option value=0 <?php if(isset($_POST['selectTest']) && $_POST['selectTest']==0){echo 'selected=\'selected\'';} ?>>Select an option...</option>
<option value=1 <?php if(isset($_POST['selectTest']) && $_POST['selectTest']==1){echo 'selected=\'selected\'';} ?>>Option 1</option>
<option value=2 <?php if(isset($_POST['selectTest']) && $_POST['selectTest']==2){echo 'selected=\'selected\'';} ?>>Option 2</option>
</select>
<br/>
<input id="inputTest" name="inputTest" type="text" value="<?php if(isset($_POST['inputTest'])){echo htmlentities($_POST['inputTest']);} ?>" />
<br/>
<input type="submit" value="OK" />
</form>
<?php
print_r($_POST);
?>
</body>
</html>
As you can see the form "remember" its data after a submit. The problem occurs at this point when the user hits the browser's Back button. Although the POST array has the values of the previous state, the browser fills the fields with the data of the next state (with the ones after the submit).
Although I could managed this problem in Chrome and Firefox with turning off the autocomplete property of the form, but this had no result in IE8.
Any suggestions would be much appreciated!
It sounds like you want the form always to display the values you echoed in your PHP? A quick-and-dirty fix is to reset the form when the page loads:
<body onload="document.forms[0].reset();">
You might need to update that onload attribute for different page structures or you could do it more elegantly if your actual application used jQuery and you give the form an ID.
I believe there is a way to turn off autocomplete/history per-field in IE also. I'd have to google that. Edit: Okay, I did... looks like you have the form attribute IE is looking for. I don't think this is actually an autocomplete issue so much as the back button is trying to recreate the last state of the page... including changes the user made, specifically filling out fields.
Here's the jQuery approach to resetting the form when the document is ready (include back button)... strangely, jQuery hasn't implemented the reset() method of a form, so the [0] gets you the raw DOM element. Add these lines to your head; substitute a local jquery on your server if available and preferred:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script>
$(function(){$("#formTest")[0].reset();});
</script>
If you run them through some sort of persistent struct (session scope comes to mind) , you can set that to a conditional on your form. So if it doesn't see the form variable (which is what post is for passing and interrogating form stuff). So the statement would replace the post isset and instead check if the struct 'session' (or some other scope) exists and if so populate. Make sense? I hope this helps.

Echo selected option

How would I echo a selected option in php?
I am using HTML to create a menu list (Buy and Sell), and I want to echo 'I want to buy the book' if someone choose "buy", or echo 'I want to sell the book' if someone choose "sell".
For the PHP to have access to the option in HTML, you're going to have to post the information from the HTML page back to the PHP.
PHP runs on the server; HTML is rendered on the client. Despite the fact that you're writing the PHP and HTML in the same file, the actions taken by the user in the HTML on the client are not accessible to the PHP in the same script, unless you set the HTML up to post back the user's data to some PHP page (which can be the same PHP page).
As said previously you will need to postback data from client (HTML) to server (php). This can be done in various ways but the most common are forms or Ajax.
<form method="post" action="">
<select name="option">
<option value="buy">Buy</option>
<option value="sell">Sell</option>
</select>
</form>
<?php
If (isset($_POST['option']))
echo 'I want to ', $_POST['option'], ' the book';
?>

Categories