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']
Related
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
I'm facing problem in inserting HTML label to database and found no way to do so. My code is as under
<html>
<body>
<form name = "myForm" >
<label name = 'q1'>Question 01: what Jorge do according to the story</label>
</form>
<?php
require "connection.php";
$qst = $_POST['q1'];
mysql_query("insert into xxx values('$qst')") or die(mysql_error);
?>
any help will be appreciated please.
You have a slew of problems here. First let's talk about the things that are actually preventing this from working.
First, you need to set the method property of the <form> element to POST to have the form perform a POST action upon submittal instead of the default GET action.
<form name="myForm" method="post">
Note, that it is usually considered good form to also specify the action property of the form, though in this case the default behavior of posting to the currnet URI just happens to work for you.
Second, you need to actually create an input field in the form. This is where the data that is posted is input:
<label for="q1">Question 01: what Jorge do according to the story?</label>
<input type="text" name="q1" />
Third, You need a submit button to actually make the form POST:
<input name="submit" type="submit" value="submit" />
Now, let's talk about the stuff that should be fixed that doesn't actually prevent this from working, but just represents good programming practice.
First, you should not be using mysql_* functions. They are deprecated. I would suggest mysqli or PDO as widely used alternatives.
Second, you have a significant vulnerability to SQL injection. You should NEVER use user input data without validating and sanitizing it. This means you should probably check to see if a value was even POSTed (not an empty string) before trying to do the insert and then you need to escape the value before using it in SQL, or better yet, learn how to use parametrized prepared statements which prevents the need for input escaping.
Third, I would recommend getting in the habit of putting your code logic at the beginning of your script (before HTML) output. In your case this means moving the logic where you read in the PST content and perform the database insert before the HTML. WHy? Because this allow you to do things like conditionally print out error messages if the user did not provide input or to otherwise change the page in response to the POST. This also help build a good habit in that, when you start doing more complex things in PHP, you might need to do things like redirect users from one page to another, or totally separate out the logic form the display into separate files. This is not possible with code stuck at the end of the HTML output.
$_POST variables do not correspond to label elements, they correspond to input elements. The key to your post array is the name of your input element.
<input type="text" name="mytext" />
After post will be $_POST['mytext']
However, you're vulnerable to SQL Injection. You should not be using mysql_query() but rather PDO or Mysqli with prepared statements, but if you insist on using it, escape it first with mysql_real_escape_string()
$qst = mysql_real_escape_string($_POST['q1']);
mysql_query("insert into xxx values('$qst')") or die(mysql_error);
Fred made a good point in the comments though. This bit of code is going to execute the first time you load the page before the form is submitted and throw an error (or warning) because $_POST['q1'] doesn't exist yet. You'll want to make sure it does exist before doing things with it.
if(!empty($_POST['q1'])){
$qst = mysql_real_escape_string($_POST['q1']);
mysql_query("insert into xxx values('$qst')") or die(mysql_error);
}
Further, you need to tell the form where to submit to and what method to use:
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<label for = 'q1'>Question 01: what Jorge do according to the story</label>
<input type='text' name='q1' value='' />
</form>
BTW, label does not have a name attribute, it has a "for" attribute.
Also, <form> elements use "GET" by default and submit to the current page if an action is not set, so it's technically not necessary to even have the action set in this case, but it's good practice.
You need add input field for your form and change form sumbit method. By default it's "GET", so you can't have input value in $_POST.
Or you can get input value from $_GET.
<html>
<body>
<form name = "myForm" method="post">
<label for = 'inp'>Question 01: what Jorge do according to the story</label>
<input type="text" name="q1" id="inp" />
<input type="submit" value="Submit">
</form>
<?php
require "connection.php";
$qst = $_POST['q1'];
mysql_query("insert into xxx values('$qst')") or die(mysql_error);
?>
And also you need to have sumbit input field to submit form or can sumbit it with js or on keyup enter key.
<input type="submit" value="Submit">
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.
Is there a difference if a parameter of a POST-form is placed in the query string:
<form action="mysite.com/index.php?myparam=myvalue">
...more inputs here
</form>
and placing it as a hidden input?
<form action="mysite.com/index.php">
<input type="hidden" value="myvalue">
...more inputs here
</form>
I'm using Joomla, but it's totally unrelated actually. I see that there's a bit of "here and there" in their tutorials, but does it actually matter? What are the implications if I use either one?
NOTE: I forgot to place action=post in the forms which has changed the question totally. however, with the arrival of interesting answers which answered more than just my question, I decided to leave them as is.
Yes, there is a difference, technically and conceptually. The way that difference affects you depends on the application server that handles the request (well, and on your preferences, of course).
Technical difference:
In most application servers, the source of a parameter (URL or FORM) determines where they end up. In PHP, url parameters go in the $_GET and form fields in the $_POST superglobals, respectively. If you don't care about the technical difference, there is a $_REQUEST superglobal for your convenience.
Conceptional difference:
It is most logical to make a difference between two types of request parameters:
Such that are required to render a page, i.e. they don't change anything in the database if you send the request again.
Such that change the database, i.e. are destructive (they are the reason why browsers ask if you are okay with posting a page again if you hit refresh).
The former ones are called idempotent and should be transferred via GET. A good example would be a search string or a record ID. No matter how often your hit refresh, the database stays untouched.
The other kind of parameter is data that should be stored in the DB. It would be destructive in the sense that it actually changes database contents. These parameters should be transferred via POST.
By the way, this is also a good way to decide if your form should be method="GET" or method="POST": Whenever form input is idempotent on the database, use a GET form. For example a user search form should be GET, a user preferences form should be POST.
Now you could argue that in your case the record ID is idempotent, but the other bits of information in your form are not. In this case I find it most idiomatic to use
<form action="mysite.com/index.php?id=1234" method="POST">
<!-- ...more inputs here -->
</form>
since a GET mysite.com/index.php?id=1234 would request that very record.
There is no need to do it that way, though - of course you can post the ID as a hidden input.
Two things you should be aware of, though:
In this case the HTTP server logs would not show evidence of which record the user posted to (if you care for that).
This kind of separation only works for POST forms. GET forms ignore the parameters in action attribute, you must specify all of them in as hidden input fields.
for the POST form there is no difference.
for the GET form the entirely new query string would be composed of the form fields, eliminating all existing values - so, never use query string for the GET forms, use hidden fields instead.
There IS a difference because the GET parameters passed to the action attribute are dismissed. You should use hidden fields.
If you specify the method attribute in your form and set its value to "POST", then you will have to parse both the GET and POST parameters.
I used the following file to test (name it "testget.php"):
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Test GET</title>
</head>
<body>
<p>
<?php
if( ! empty( $_GET ) )
{
print_r( $_GET );
}
if( ! empty( $_POST ) )
{
print_r( $_POST );
}
?>
</p>
<p>No method attribute</p>
<form action="testget.php?foo=bar">
<input type="hidden" name="bar" value="foo" />
<input type="submit" value="Submit" />
</form>
<p>method="get"</p>
<form action="testget.php?foo=bar" method="get">
<input type="hidden" name="bar" value="foo" />
<input type="submit" value="Submit" />
</form>
<p>method="post"</p>
<form action="testget.php?foo=bar" method="post">
<input type="hidden" name="bar" value="foo" />
<input type="submit" value="Submit" />
</form>
</body>
</html>
Output:
No method attribute:Array ( [bar] => foo )
method="get":Array ( [bar] => foo )
method="post": Array ( [foo] => bar ) Array ( [bar] => foo )
How can I submit a form to itself without clearing the data in the fields using HTML, javascript and PHP?
You could take different approaches (e.g. cookies, jquery, etc...), however HTML + a line in PHP are more than enough in this case. Try this example code:
<form name="test" method="post">
Your Name: <input type="text" name="YourName" <?php if (isset($_POST['YourName'])) echo 'value="'.$_POST['YourName'].'"';?> >
<input type="submit" value="Submit">
</form>
In the code above if something has been posted to the receiving page (that can be the same page, such as in your case), then the posted value is printed out in the corresponding field. You can use this approach for all the fields composing your form.
If you want, you can also use similarly the $_GET method in the form.
If you use the traditional form submit, you need to save the parameters and rewrite the form input elements when you write the form the next time. But a better way is to use AJAX -- then the field data is sent without a form submission, and the input elements retain their data. See this link: http://www.w3schools.com/ajax/default.asp