Validating input text in php when moving pages - php

I do know how to validate a basic input(text) when submitting a form. However, I am lost as to how I am going to validate an input(text) when leaving a web page. Even with JS I couldn't get it to stay on the same page due to the "form action" attribute.
HTML Code for the input and submit
<form name="form1" action="second.php" **onsubmit="return error()"** method="post">
<input style="" name="hall" type="text"><br>
<input name="Move" style="height: 23px" type="submit" value="Move">
</form>
PHP CODE for validating
<?php
if (isset($_POST['Move'])) {
if(($_POST['hall']) != "Hallway")
{
echo "Not among available rooms";
}
?>
Also this is the JS code
<script type="text/javascript">
function error()
{
var x=document.forms["form1"]["hall"].value
if (x==null || x=="" || x!="next")
{
alert("Wrong entry. Try again!!!");
return false;
}
}
</script>

The following code is working on my server, provided the second.php page exists. (BTW I added a ; after value, but it seems to work without it).
Did you put the js script after the form? Maybe it could impact.
<html>
<script type="text/javascript">
function error()
{
var x=document.forms["form1"]["hall"].value;
if (x==null || x=="" || x!="next")
{
alert("Wrong entry. Try again!!!");
return false;
}
}
</script>
<body>
<form name="form1" action="second.php" onsubmit="return error()" method="post">
<input style="" name="hall" type="text"><br>
<input name="Move" style="height: 23px" type="submit" value="Move">
</form>
</body>
</html>

Other things I can think of:
-Do you have any JS errors on the page that would prevent this script from running? It worked on my server, as well.
-Do you have another HTML element with an identical name?
-I am assuming that the **'s were for emphasizing that area in your code. If not, of course, they would need to be removed.
The only thing that could prevent your "return false" from working is if you have some kind of JavaScript error that kills the script from running.
If you have additional code on your page, please post it and we'll take a look!

Related

AJAX XMLHttpRequest not working

I'm trying to work with ajax. I have two pages: request.html and reply.php.
request.html:
<html>
<script language="javascript">
var xht = new XMLHttpRequest();
function testAJAX()
{
xht.open("get","http://localhost:9999//a.php", true);
xht.send();
xht.onreadystatechange=function() {
if (xht.readyState==4) {
alert("Text: "+xht.responseText);
}
}
}
</script>
<form id="form1" name="form1" method="post" action="">
btn
<input name="btn" type="submit" id="btn" onClick="testAJAX();" value="Submit" />
</form>
</html>
reply.php:
<?php
echo 'hi';
?>
The problem is that I don't get a response via xht.responseText and with xht.responseXML I get null and with xht.status I get 0.
I asked the link http://localhost:9999//a.php via browser and got hi correctly.
P.S: I tried this on Chrome 29.0.1547.18 and Maxthon v4.1.1
any ideas..
You don't need to mention "http://localhost".
The main mistake is you have given the input type as Submit If it is submit the form will be submitted first the click event will not trigger. Change the input type to button.
If you want to do form submission do it in java script
The corrected code is below.
<form id="form1" name="form1" method="post" action="">
btn
<input name="btn" type="button" id="btn" onClick="testAJAX();" value="Submit" />
// change type to button
</form>
var xht = new XMLHttpRequest();
function testAJAX()
{
xht.open("get","a.php", true); /// Change to a.php
xht.send();
xht.onreadystatechange=function() {
if (xht.readyState==4) {
alert("Text: "+xht.responseText);
}
}
}
Adding to SarathPrakash's answer, I would like to point out that there is nothing wrong with specifying localhost. It will still work as long as the PHP file's address is valid.
You can also have the submit button. But you'll have to modify the form opening tag as follows:-
<form id="form1" name="form1" method="POST" action="" onsubmit="return false">
This is will stop the default behaviour of the form being submitted. Although in my opinion, it is best to avoid it altogether, and just stick with assigning the correct event handler to the onclick attribute.
Also, it is good practice to follow the correct syntax for HTML documents.
<html>
<head>
<title> Your title here </title>
<script type="text/javascript"> Your script here </script>
</head>
<body>
Your main document text here. Forms, tables etc.
</body>
</html>
For a simple tutorial, you could try this.

Issue with javascript validation in netbeans

I am new to Netbeans. I have created a simple php project. It consists of a form and I've written a separate Javascript file to validate its fields. I tried running the project outside netbeans, it works fine. I recently imported the project to netbeans but javascript doesn't seem to work well. When I try opening the page(form page) in the browser, the entire javascript file appears on the page.
I do not know where I'm going wrong. As I'm new to netbeans I am unable to rectify it. Kindly help.
My Javascript file is named Validation.js and is in the js folder.
function ValidateForm(theForm)
{
//returns true/false after validation
}
My php file looks similar to this.
<?php include "js/Validation.js";
//if validation returns true
if(isset($_POST))
{
if(isset ($_POST['bt_save']) && $_POST['bt_save'] == 'Submit')
{
//code to insert fields into database after validation
}
}
?>
<form method="post" name="form1" id="form1" onsubmit="return ValidateForm(this);">
<!--form elements-->
<input type="submit" name="bt_save" value="Submit"/>
</form>
Thanks in advance!
Your include is wrong, if you use php include it just loads the page.
Try using <script type="text/javascript" src="js/Validation.js"></script>. instead of include "js/Validation.js".
So your new file would be something like.
<?php
//if validation returns true
if(isset($_POST))
{
if(isset ($_POST['bt_save']) && $_POST['bt_save'] == 'Submit')
{
//code to insert fields into database after validation
}
}
?>
<form method="post" name="form1" id="form1" onsubmit="return ValidateForm(this);">
<!--form elements-->
<input type="submit" name="bt_save" value="Submit"/>
</form>
<script type="text/javascript" src="js/Validation.js"></script>

Why are these <form>'s not recognized by FF and Chrome?

I have the following forms that are rendered by some PHP logic. The forms render fine; you can see the text inputs and submit button and all.
In IE the forms work as expected. The first form goes to 'index.php?subscribe=go' and the second to 'index.php?unsub=go', but in FF and Chrome, clicking the submit button reloads the page (does not go to form action). I have not checked other browsers.
I found in Firebug that the <form> tag doesn't even exist on the page in Firefox. This is very strange; check it out:
else
{
echo '<div class="subs_main">';
if (isset($_GET['subscribe']))
{
if ($_GET['subscribe'] != 'go')
{?>
Subscribe to <b>Bella Blog</b> for specials, sales, news and more!
<br />
<form action="index.php?subscribe=go" method="post" name="subscribe_form" onsubmit="return checkForm();">
Name: <input type="text" name="name" size="15" />
<br />
Email: <input type="email" name="email" size="20" />
<br />
<input type="submit" value="subscribe!" name="submit" />
</form>
<p class="unsub">You can unsubscribe at any time</p>
<?php
}
else
{
// subscribe user
}
}
elseif (isset($_GET['unsub']))
{
if ($_GET['unsub'] != 'go')
{?>
Sorry to see you go! You can re-subscribe at any time!
<br />
<form onsubmit="return checkForm2()" name="unsub_form" method="post" action="index.php?unsub=go">
Email: <input type="email" name="email" size="20" />
<br />
<input type="submit" value="unsubscribe" name="submit" />
</form>
<?php
}
else
{
// process unsubscription HERE
}
}
echo '</div>';
}
This is the JS for form validation (negligible I think because it works in IE and I get the same result when commenting this script out):
<script type="text/javascript" language="javascript">
function checkForm()
{
var regex = /^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/;
var form = document.forms.subscribe_form;
var name = form.name.value;
var email = form.email.value;
if (name == '' || email == '')
{
alert('You must enter both your name and email address!');
return false;
}
else if (!email.match(regex))
{
alert('You must enter a valid email!');
return false;
}
return true;
}
function checkForm2()
{
var form = document.forms.unsub_form;
var email = form.email.value;
if (email == '')
{
alert('You must enter an email address!');
return false;
}
return true;
}
</script>
If you use POST method into your forms all parameters should be passed through INPUT html elements (i.e. action="index.php?subscribe=go" and action="index.php?unsub=go" are wrong).
The <form> tag doesn't exist? Unless you have code that tailors the output to the USER_AGENT, any browser that passes a given set of GET/POST input to the page should receive identical output. It's possible, of course, that they'll render the page and respond to events in (potentially significantly) different ways, but the source code should be identical.
Post the page source and we can look and see what the issue might be.
This was an outlandish WAMP issue. I had some other PHP code in the file that generated a WAMP error (but no error on the live site) that I've been ignoring because it is meaningless. 'Undefined index' is what it's called and the error appears when you call a PHP variable using $_POST[example] instead of $_POST['example']. Most ridiculous.
So WAMP spit out a bunch of HTML (error <table>s) that got mixed up with the other form on my page. IE can handle the messed up form being there and my form (shown in question) worked normally, while FF/Chrome cannot.
Hope this helps someone.

Calling a PHP function from an HTML form in the same file

I'm trying to execute a PHP function in the same page after the user enters a text and presses a submit button.
The first I think of is using forms. When the user submits a form, a PHP function will be executed in the same page. The user will not be directed to another page. The processing will be done and displayed in the same page (without reloading).
Here is what I reach to:
In the test.php file:
<form action="test.php" method="post">
<input type="text" name="user" placeholder="enter a text" />
<input type="submit" value="submit" onclick="test()" />
</form>
The PHP code [ test() function ] is in the same file also:
<?php
function test() {
echo $_POST["user"]; // Just an example of processing
}
?>
However, I still getting a problem! Does anyone have an idea?
This cannot be done in the fashion you are talking about. PHP is server-side while the form exists on the client-side. You will need to look into using JavaScript and/or Ajax if you don't want to refresh the page.
test.php
<form action="javascript:void(0);" method="post">
<input type="text" name="user" placeholder="enter a text" />
<input type="submit" value="submit" />
</form>
<script type="text/javascript">
$("form").submit(function(){
var str = $(this).serialize();
$.ajax('getResult.php', str, function(result){
alert(result); // The result variable will contain any text echoed by getResult.php
}
return(false);
});
</script>
It will call getResult.php and pass the serialized form to it so the PHP can read those values. Anything getResult.php echos will be returned to the JavaScript function in the result variable back on test.php and (in this case) shown in an alert box.
getResult.php
<?php
echo "The name you typed is: " . $_REQUEST['user'];
?>
NOTE
This example uses jQuery, a third-party JavaScript wrapper. I suggest you first develop a better understanding of how these web technologies work together before complicating things for yourself further.
You have a big misunderstanding of how the web works.
Basically, things happen this way:
User (well, the browser) requests test.php from your server
On the server, test.php runs, everything inside is executed, and a resulting HTML page (which includes your form) will be sent back to browser
The browser displays the form, the user can interact with it.
The user submits the form (to the URL defined in action, which is the same file in this case), so everything starts from the beginning (except the data in the form will also be sent). New request to the server, PHP runs, etc. That means the page will be refreshed.
You were trying to invoke test() from your onclick attribute. This technique is used to run a client-side script, which is in most cases Javascript (code will run on the user's browser). That has nothing to do with PHP, which is server-side, resides on your server and will only run if a request comes in. Please read Client-side Versus Server-side Coding for example.
If you want to do something without causing a page refresh, you have to use Javascript to send a request in the background to the server, let PHP do what it needs to do, and receive an answer from it. This technique is basically called AJAX, and you can find lots of great resources on it using Google (like Mozilla's amazing tutorial).
Here is a full php script to do what you're describing, though pointless. You need to read up on server-side vs. client-side. PHP can't run on the client-side, you have to use javascript to interact with the server, or put up with a page refresh. If you can't understand that, there is no way you'll be able to use my code (or anyone else's) to your benefit.
The following code performs AJAX call without jQuery, and calls the same script to stream XML to the AJAX. It then inserts your username and a <br/> in a div below the user box.
Please go back to learning the basics before trying to pursue something as advanced as AJAX. You'll only be confusing yourself in the end and potentially wasting other people's money.
<?php
function test() {
header("Content-Type: text/xml");
echo "<?xml version=\"1.0\" standalone=\"yes\"?><user>".$_GET["user"]."</user>"; //output an xml document.
}
if(isset($_GET["user"])){
test();
} else {
?><html>
<head>
<title>Test</title>
<script type="text/javascript">
function do_ajax() {
if(window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
} else {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var xmlDoc = xmlhttp.responseXML;
data=xmlDoc.getElementsByTagName("user")[0].childNodes[0].nodeValue;
mydiv = document.getElementById("Test");
mydiv.appendChild(document.createTextNode(data));
mydiv.appendChild(document.createElement("br"));
}
}
xmlhttp.open("GET","<?php echo $_SERVER["PHP_SELF"]; ?>?user="+document.getElementById('username').value,true);
xmlhttp.send();
}
</script>
</head>
<body>
<form action="test.php" method="post">
<input type="text" name="user" placeholder="enter a text" id="username"/>
<input type="button" value="submit" onclick="do_ajax()" />
</form>
<div id="Test"></div>
</body>
</html><?php } ?>
Without reloading, using HTML and PHP only it is not possible, but this can be very similar to what you want, but you have to reload:
<?php
function test() {
echo $_POST["user"];
}
if (isset($_POST[])) { // If it is the first time, it does nothing
test();
}
?>
<form action="test.php" method="post">
<input type="text" name="user" placeholder="enter a text" />
<input type="submit" value="submit" onclick="test()" />
</form>
Use SAJAX or switch to JavaScript
Sajax is an open source tool to make
programming websites using the Ajax
framework — also known as
XMLHTTPRequest or remote scripting —
as easy as possible. Sajax makes it
easy to call PHP, Perl or Python
functions from your webpages via
JavaScript without performing a
browser refresh.
That's now how PHP works. test() will execute when the page is loaded, not when the submit button is clicked.
To do this sort of thing, you have to have the onclick attribute do an AJAX call to a PHP file.
in case you don't want to use Ajax , and want your page to reload .
<?php
if(isset($_POST['user']) {
echo $_POST["user"]; //just an example of processing
}
?>
Take a look at this example:
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<?php
// define variables and set to empty values
$name = $email = $gender = $comment = $website = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = test_input($_POST["name"]);
$email = test_input($_POST["email"]);
$website = test_input($_POST["website"]);
$comment = test_input($_POST["comment"]);
$gender = test_input($_POST["gender"]);
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<h2>PHP Form Validation Example</h2>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="name">
<br><br>
E-mail: <input type="text" name="email">
<br><br>
Website: <input type="text" name="website">
<br><br>
Comment: <textarea name="comment" rows="5" cols="40"></textarea>
<br><br>
Gender:
<input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
<?php
echo "<h2>Your Input:</h2>";
echo $name;
echo "<br>";
echo $email;
echo "<br>";
echo $website;
echo "<br>";
echo $comment;
echo "<br>";
echo $gender;
?>
</body>
</html>
You can submit the form without refreshing the page, but to my knowledge it is impossible without using a JavaScript/Ajax call to a PHP script on your server. The following example uses the jQuery JavaScript library.
HTML
<form method = 'post' action = '' id = 'theForm'>
...
</form>
JavaScript
$(function() {
$("#theForm").submit(function() {
var data = "a=5&b=6&c=7";
$.ajax({
url: "path/to/php/file.php",
data: data,
success: function(html) {
.. anything you want to do upon success here ..
alert(html); // alert the output from the PHP Script
}
});
return false;
});
});
Upon submission, the anonymous Javascript function will be called, which simply sends a request to your PHP file (which will need to be in a separate file, btw). The data above needs to be a URL-encoded query string that you want to send to the PHP file (basically all of the current values of the form fields). These will appear to your server-side PHP script in the $_GET super global. An example is below.
var data = "a=5&b=6&c=7";
If that is your data string, then the PHP script will see this as:
echo($_GET['a']); // 5
echo($_GET['b']); // 6
echo($_GET['c']); // 7
You, however, will need to construct the data from the form fields as they exist for your form, such as:
var data = "user=" + $("#user").val();
(You will need to tag each form field with an 'id', the above id is 'user'.)
After the PHP script runs, the success function is called, and any and all output produced by the PHP script will be stored in the variable html.
...
success: function(html) {
alert(html);
}
...
This is the better way that I use to create submit without loading in a form.
You can use some CSS to stylise the iframe the way you want.
A php result will be loaded into the iframe.
<form method="post" action="test.php" target="view">
<input type="text" name="anyname" palceholder="Enter your name"/>
<input type="submit" name="submit" value="submit"/>
</form>
<iframe name="view" frameborder="0" style="width:100%">
</iframe>

Combing JS and PHP on one button. Is it possible?

Hiya:
i know some people would be so tired of my questions, but I'm working on a uni project and need to get it done as soon as possible. This question is about using JS on a button(button) and sending a php_my_sql update on the same button. The problem is JS uses button, right? but PHP uses button(submit). How can I get these two to work on one of these buttons, cuz there has to be only one button.
this is my code for JS
<script type="text/javascript">
function formAction(){
var x=document.getElementById("collect")
x.remove(x.selectedIndex)
}
</script>
HTML
<form method="post">
<select id="collect" name="Select1" style="width: 193px">
<option>guns</option>
<option>knife</option>
</select> <input type="**submit/button**" onclick="formAction()" name="Collect" value="Collect" /></form>
PHP
<?
if (isset($_POST['Collect'])) {
mysql_query("UPDATE Player SET score = score+10
WHERE name = 'Rob Jackson' AND rank = 'Lieutenant'");
}
?>
This can be a way
Submit the form through JS after removing parameter
<script type="text/javascript">
function formAction(){
var x=document.getElementById("collect")
x.remove(x.selectedIndex);
document.forms[0].submit();
}
</script>
Input type button
<input type="button" onclick="formAction()" name="Collect" value="Collect" />
Embed jQuery and use $.post() to send an AJAX request.
JavaScript can interact with the button whilst the user is navigating the page and entering data into the form. The instant the user pushes the submit button and the request for the form submission is sent JS no longer has control. The request is sent to the form's action (most likely a PHP file) which processes the request and gives an answer back.
If you really need to combine the two, look into AJAX.
<?php print_r($_POST); ?>
<script type="text/javascript">
function formAction(){
var x=document.getElementById("collect");
x.remove(x.selectedIndex);
submit_form();
}
function submit_form() {
document.form1.submit();
}
</script>
<form method="post" name='form1'>
<input type='hidden' name='Collect'/>
<select id="collect" name="Select1" style="width: 193px">
<option>guns</option>
<option>knife</option>
</select> <input type="button" onclick="formAction()" name="Collect" value="Collect" /></form>
<?
if (isset($_POST['Collect'])) {
//do whatever update you want
}
?>
Simple Solution
Make this modification in the form tag
<form method="post" onsubmit="return formAction()">
In JavaScript function add a line "return true;" at the end of the function.
Voila ..!!! you are done..!!
Enjoy..!!

Categories