Display error messages in html - php

I want to display warning messages in html. This code shows two text boxes named "company" and "name". con.php connects to the database and inserts the information. But if I enter nothing, then the values are still getting stored in the database as null. I want user to know that he shouldn't leave the fields blank by displaying some messages and also a warning should appear if the given company already exists in the database. How do I implement that?
<html>
<head>
<title>store in a database</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<h2>company Store</h2>
<form name="form1" method="post" action="con.php">
<p>company:<input type="text" name="company">
<br/>
<br/>
<br/>
Name: <input type="text" name="name" size="40">
<br/>
<br/>
<br/>
<input type="submit" value="Save">
<input type="button" onclick="window.close()" value="cancel">
</form>
</body>

While an alert message cannot be produced without JavaScript, you could take advantage of HTML5's placeholder attribute to inform the user of this message:
<input type="text" placeholder="You must enter something in this field"! name="whatever" id="whatever" />
And couple this with JavaScript:
var inputElem = document.getElementById('whatever');
var form = document.getElementsByTagName('form')[0];
form.onsubmit = function(){
if (inputElem.value = '' || inputElem.value.length < 1){
alert('You must enter some actual information');
return false;
}
};
However JavaScript can be edited by the users, via Firebug, Web Inspector, Dragonfly...or by simply creating a new html file and submitting the form to the same source from the action attribute of the form element. Therefore your form-handling script must be sanitised and checked on the server as well as the client; client-side checking is a convenience to the user (to prevent unnecessary page-reloads, submissions and so on), it is not a security feature, and should not be used, or mistaken, as such.

Best way is using Ajax if you want to do it at the same page. You need to read some tutorials on it. It's not that easy to explian here.
If reloading or redirecting to other page is ok for you, you should compare the submitted form value with the values in the database in a PHP script which is redirected from form submission (action url). If values doesn't match and not empty, store the values to database and redirect to a page like the list of companies or "company successfully created" message page. If values match with an old record or empty, redirect back to the same form page with a flag (something like form.php?error=1 etc.) and show the proper error message.
Also you can use JavaScript for immediate alerts. But you should always do the same checks at PHP side since JavaScript can be disabled in browsers.

In con.php you should do your data validation and return the markup (or redirect to page describing the error).
So, check for empty fields, and if the exists redirect the user to a page saying the fields can not be empty (and probably allow them to enter new values).
If the data entered is ok, check the database for duplicates and if they exist, redirect the user to a page saying that the company already exists (and again probably allow the user to correct the data).

You can not do it only with HTML.
You need to add a form validation (to prevent empty strings), HTML5 form validation can do that for you (check http://www.broken-links.com/2011/03/28/html5-form-validation/), but not all browser support it, so you will need to use JavaScript to validate the form.
There are JavaScript libraries that will take an old browser and make it behave like a browser that support HTML5 (check http://www.matiasmancini.com.ar/jquery-plugin-ajax-form-validation-html5.html).
You will also need to retrieve the companies already in your database and check them against the user input and alert him if needed.
On top of that you will need to validate the data in your PHP before inserting it to the database (check for empty string for example).

Related

Prevent browser form-resubmission alert

How can I avoid the the browser form-resubmission alert?
This question seems to have been discussed a lot here on SO, for example:
Preventing form resubmission
Prevent Back button from showing POST confirmation alert
Never ever respond with a body to a POST-request
What I do not get from the previous discussion, is how I can use the posted data and incorporate it into the html. The previous links discuss how to use the php header function to send a get request to itself. But when sending this get request, the posted data will no longer be available to the new page, (since we cannot use the php post method..)
I would like to do this without using the php or javascript session storage technique (or saving the posted data to a temporary mySQL database).
For a simple example:
<html>
<body>
<form action="post.php" method="post">
User name: <input type="text" name="user"><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
where post.php is:
<html>
<body>
<?php
echo "<p>".$_POST['user']."</p>";
?>
</body>
</html>
Pressing CTRL-R in google chrome on the second page brings up the alert.
Do a redirect from post.php. Save data in session or in database and retrieve from redirect page.
Example Scenario:
Submit the form
Save the user record to db, get the id of the new record e.g. in $id
redirect using header, something like:
header('Location: result.php?user_id='.$id);
get the user record from db, with the provided id and show it to the
user.
Use this:
<script>
if(window.history.replaceState)
{
window.history.replaceState(null,null,window.location.href);
}
</script>
you may rewrite the browser history object
history.replaceState("", "", "/the/result/page");
See this

how to enable the submit button in real time depending on text validation?

I have a HTML form in list.php that submits the data from text box ("item" in below code) to check.php. This check.php validates the text entered to be not empty or white spaces only. After validation, it redirects to list.php for the entered text to be displayed. list.php is below. I want the "add" button to be enabled only when valid text is entered in the text box. I would like this feature to be done with php and probably not with javascript.
I can use "disabled=\"disabled\" in the form, but this does not work in real-time disabling depending on validation.
<form action="check.php" method="post">
<input name="item" type="text" size="25" autofocus="autofocus" />
<input type="submit" value="Add" id="add" />
</form>
You say:
I would like this feature to be done with php and probably not with javascript.
Unfortunately, if you want "real-time" then you're gonna need JavaScript. You'll need it to make AJAX calls to your PHP code to check for validation.
So either A) you don't validate in "real-time" at all, or B) You use JavaScript in one shape or another.
Let's say you opt for B), to use JavaScript, and presuming ALL you need to do is check for an empty string or whitespace, then you can do all of this client-side in JavaScript and not require a server call at all, also making it truly "real-time".
And so, here is my solution, using JavaScript (jQuery) without relying on server calls. This may not be suitable for your current implementation, but just in case it is, this might be helpful.
JSFiddle:
http://jsfiddle.net/VKfrw/1/
JavaScript:
function hasWhiteSpaceOrEmpty(s)
{
return s == "" || s.indexOf(' ') >= 0;
}
function validateInput()
{
var inputVal = $("#myInput").val();
if(hasWhiteSpaceOrEmpty(inputVal))
{
//This has whitespace or is empty, disable the button
$("#add").attr("disabled", "disabled");
}
else
{
//not empty or whitespace
$("#add").removeAttr("disabled");
}
}
$(document).ready(function() {
$("#myInput").keyup(validateInput);
});
HTML:
<!-- give this guy an ID -->
<input id="myInput" name="item" type="text" size="25" autofocus="autofocus" />
This implementation uses jQuery.
As mentioned, if you want this done in real time some javascript will be needed.
However I think this problem is actually more suited to javascript in general. PHP validation can be useful if you need to cross reference for data with data in your database.
eg. In a sign up form, checking a user is not already registered with the entered email address.
But in your case, depending on what you mean by "valid text" it is probably easier and better to use javascript.
There are some great jQuery plugins which make javascript validation really simple.
http://docs.jquery.com/Plugins/Validation/validate

Required field display error message on form

I have a form that I need to have required fields filled out. I know to use the code below to verify if the field is blank:
<?php
if (!empty($_POST['client_name'])) {
echo '<p style="color:red;">'"Client Name is required!"'</p>';
}
?>
My question is, how do I get the error message to display on the form page, saving all the data already entered in the form. Example: I fill out all 15 fields on the form, excluding the required field. When I hit the submit button, if the required field is empty, I want to stay on that form page, without losing any of the info I put into the fields, and I want to display a message next to the required field box, saying "This is a required field.
I am not sure on the code to do that, or where to put it. On the form, or on the script that executes the form?
use client side javascript validation first, then php server side validation.
Why you use !empty you can use empty for best result like
<?php
if (empty($_POST['client_name'])) {
echo '<p style="color:red;">'"Client Name is required!"'</p>';
}
?>
Actually you should be first set HTML5 validation like
<input type="text" name="abc" required="">
You can set custom error message for required field like
<input type="text" name="abc" required="" oninvalid="this.setCustomValidity('Please Select This')">
Then you can use JS or jQuery validation and then user Server side Validation like PHP or ASP or others.
Thanks.
Without knowing the structure of your pages, it's hard to give an exact answer, but here's a general process flow that should help:
Form is submitted to processor
Processor validates inputs
if inputs are good, processor redirects to next page
if inputs are not good, processor should send error text and form data back to the routine that builds/displays the form.
IMHO, the processor should not echo anything. All display should be handled by the script that builds the form.
Without coding it for you, that's the best answer I can give :-)

Remember form value when return back to submit due to some error

After filling the form when submit, accidentally due to some filling error ,the form is not submit and return to back,in this condition the value of all text box is blank. i want to stable value of all fields in this condition . I'm using php with smarty framework. Please reply with solution as soon as possible.
Thanks.
If the form is submitted to the page that contains it then you will have access to the submitted values, and can use them to populate your form. For example, if you are submitting the form via POST:
<input name="something" value="<?=$_POST['something']?>" />
If you are submitting the form to a different script, you could send the values back to the page with the form as URL parameters, or you could use temporary session variables, and unset them when the input passes whatever validation you are using:
$_SESSION["temp_something"] = $_POST["something"]; //In form processing script
Then in your form:
<input name="something" value="<?=$_SESSION['temp_something']?>" /> <!--In form-->
You can fill the form fields, on the second round, by filling the content inside the value attributes of html tags, like so:
<input type="text" value="<?php echo $_REQUEST['test']; ?>" name="test">
Pay attention: this is a fast and simple solution. It gives you an idea. In good web programming practice you should sanitize the form data received by client in order to avoid security issues.

Get POST response from a url and print response to page?

I'm trying to get a POST response from a url and I can not get the response to print to my html page instead it just redirects me to the url in the action with the response.
Is there a way to grab the response with html? php?
Code of html page i'm using
<html><head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<form
method="post"
action="http://poster.decaptcher.com/"
enctype="multipart/form-data">
<input type="hidden" name="function" value="login">
<input type="text" name="username" value="client">
<input type="text" name="password" value="qwerty">
<input type="file" name="upload">
<input type="text" name="upload_to" value="0">
<input type="text" name="upload_type" value="0">
<input type="submit" value="Send">
</form>
</head><body></body></html>
Note: The url in the action will only show the response and nothing else is shown on the page.
Let's see if I can give this a try, because you seem to be a bit confused about how an HTML form works.
First and foremost, your website looks like so, correct?
<html><head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<form
method="post"
action="http://poster.decaptcher.com/"
enctype="multipart/form-data">
<input type="hidden" name="function" value="login">
<input type="text" name="username" value="client">
<input type="text" name="password" value="qwerty">
<input type="file" name="upload">
<input type="text" name="upload_to" value="0">
<input type="text" name="upload_type" value="0">
<input type="submit" value="Send">
</form>
</head><body></body></html>
One thing to point out before we explain an HTML form, is that you have your form in the <head> of the webpage. Any element which is supposed to be seen by the user (or anything that you want to appear within the browser's main viewing area) should be in the <body>. Failure to do this puts the browser into a "quirks mode", where it actually doesn't know what you're talking about and it makes its best guess to try and build the website that it thinks you wanted. Mind you that modern browsers are very good guessers, but you should still re-write it as:
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
</head>
<body>
<form
method="post"
action="http://poster.decaptcher.com/"
enctype="multipart/form-data">
<input type="hidden" name="function" value="login">
<input type="text" name="username" value="client">
<input type="text" name="password" value="qwerty">
<input type="file" name="upload">
<input type="text" name="upload_to" value="0">
<input type="text" name="upload_type" value="0">
<input type="submit" value="Send">
</form>
</body>
</html>
As far as explaining the <form> tag... When you submit a form in HTML, it actually loads the other website. It doesn't secretly send data in the background, it will take you away from the page you're viewing and take you to the page that you are sending the data to. At first this may sound silly. Why should it take you away from the page you're viewing just to send the data to another website? If you wanted to be redirected after sending the data, you'd redirect them there after sending the data.
The reason it's done this way is to greatly simplify the HTTP protocol. Whenever you load any website, you send and HTTP request. This request contains butt-loads of information. Among this information is:
Your IP address
What browser you're using
The page you were last visiting
How you accessed this page (clicked a link or typed the URL into the address bar)
The page you want to view (is it index.html or mysite.html?)
Any cookies related to that server
Any POST information (extra information which the server may or may not have asked for)
Every time the server receives one of these requests, it looks at all of the information and decides what to do. Usually a server will just look at the page you want to view and send it to you. Sometimes the page you want to view will need some extra work before it's ready to show, though. For instance, if a page ends in .php then it will search through the page for <?php, and everything after that point will be executed as a script. Only the output of the script is sent to the person who requested the page, not the script itself.
If you were to send your POST information to a website, wait 10 minutes, THEN go to the website, it would have no way of remembering that it was you who sent the post information before or what information you sent. Web servers have a very short attention span. For that reason if you sent a form to log into a website, then waited 10 minutes, then tried to view a member's only page- it would forget that you were logged in. For this reason it sends you the page as you're submitting the form. It does it while it still remembers that you're logged in, before it has a chance to forget. There's a good chance that the page it sends you will include a cookie which you can use to remind the server you were logged in next time you request a page.
If this made sense, then you should understand what happens when you submit a form. It doesn't just take your information and give it to the server. It sends that information to the server as part of an entire request, then the server sends you back a webpage and your browser displays that webpage. There is really only one way to send data to a server without redirecting you to that server afterwards. There are multiple ways to do this trick, however. You have to send a "dummy request", requesting a webpage with certain POST data, but ignoring the webpage that's returned.
In your example, you wanted to send data to http://poster.decaptcher.com. To do this without redirecting the user to http://poster.decaptcher.com, your easiest solution would be to use javascript and AJAX. Javascript has certain functions that allow you to send an HTTP request without reloading the page, then you let the javascript determine what to do with the page that's returned.
This is generally used when you want to reload a part of a webpage without reloading the whole thing. For instance, if you have a chat program and you want to update the chat window without refreshing the entire page. The javascript would request a webpage which contains ONLY the new lines of chat, minus any <html>, <head>, or <body> tags. It then takes those lines and displays them in the chat window.
You can, however, use AJAX to request a page and then ignore what's returned instead of display it on the page. By doing this you will have sent the POST data but not redirect the user.
Another option is to send the request to a third website, which can then send its own dummy request. For instance, submit the form to a PHP page that you own. The PHP script can then tell your server to send a dummy request to http://poster.decaptcher.com and ignore the response, then you can send them a webpage containing whatever you want.
Now that I've described both of these processes in adequate detail, I'll leave it as an exercise to the reader to figure out exactly how to do these. =)
The page refresh on submitted form is the default behavior of HTML.
For people who need to display the response into the same page without refresh, they will want to use Ajax. Here is how it could be done with jQuery:
$('#the_form').submit(function (e) {
e.preventDefault();
the_form = $(this);
$('#response_container').load(
the_form.attr('action')
, the_form.serialize()
);
})
the action defines the redirect to that page. If you want to catch the response, make your own script and place it in between the two. This is a bad way of doing it though. We developers call it hack coding. lol.
Not quite sure what you want to do. If you want to show the POST content on the page, just do this:
print_r($_POST);
If you want to see what is getting POSTed to the action URL, and you don't have access to that URL, just use the HTTP Headers plugin for Firefox.
action should go to a PHP file belonging to you! ie - action="/ProcessMyForm.php"
On that file, simply use $_POST and those form elements are in there, indexed by name, in an associative array.
Also - it may have been accidental, but post parameters dont go up in the URL like get, they are "behind the scenes" (invisible to the user) and also capable of being far larger.
PS - if you want to go to that other site afterwards, use header("Redirect: other-website-here.com")
First of all, mention your question specifically. If you want to fetch data from a URL than you can't use the form method="post". If you want to fetch data from URL, you have to use method "get". Calling print_r($_GET) can be used to retrieve data from HTML page to controller page.

Categories