How to give action on php pages - javascript

I have made two pages. I have used php form validation in my first page, i.e., form.php and I have to give action on second page i.e., data_ins.php. Please let me know how will it possible with my coding.
Here are my pages:
form.php
<?php $fnameErr = $lnameErr = "";
$fname = $lname= ""; if($_SERVER["REQUEST_METHOD"] == "POST") {
if(empty($_POST['fname']))
{
$fnameErr = "First Name is required";
}
else
{
$fname= formVal($_POST['fname']);
}
if(empty($_POST['lname']))
{
$lnameErr = "Last Name is required";
}
else
{
$lname= formVal($_POST['lname']);
} }
function formVal($data)
{
$data = trim($data);
$data = stripcslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?> <!DOCTYPE html> <html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
First Name:
<input type="text" name="fname"> <span style="color:red;"><?php echo $fnameErr ?></span> <br>
Last Name:
<input type="text" name="lname"> <span style="color:red;"><?php echo $lnameErr ?></span> <br>
<input type="submit" name="submit">
</form>
</body> </html>
data_ins.php
<?php $conn = mysqli_connect("localhost","root","","test_db");
$sql = "insert into records (FirstName, LastName) values ('$fname', $lname)";
if($result=mysqli_query($conn, $sql))
{
echo "Data Inserted Successfull";
}
else
{
echo "Invalid";
}
mysqli_error($conn); ?>

Personally, I think you may of made it harder than you needed to.
Here is what I'd do with the PHP side:
if (isset($_POST['submit']))
{
if (!empty($_POST['fname']))
{
if (!empty($_POST['lname']))
{
// Add Database insert code here..
} else {
echo "Last name is required";
}
} else {
echo "First name is required";
}
}
As for the form, you don't need to add the PHP self (just add the method) like so:
<form method="POST" action="">
First Name: <input type="text" name="fname"><br>
Last Name: <input type="text" name="lname"><br>
<input type="submit" name="submit">
</form>
Hope this helps more so than your initial idea of doing it.
PLEASE NOTE: I haven't added the $data trim etc in but you'd add these in firstly where // do code note is.

1.change your form like this
`<form method="POST" action="location of your data_ins.php">`
2.in your data_ins.php must have database config code or include it.
3.get your all form value in data_ins.php pass to insert query
<form method="POST" action="">
First Name: <input type="text" name="fname"><br>
Last Name: <input type="text" name="lname"><br>
<input type="submit" name="submit">
</form>

Besides your code, your method (as question is not about it).
To execute other .php file you can use PHP statements:
require
include
include_once
In your case require should be the one to use, like: require 'data_ins.php'; after validation.

Related

PHP in JavaScript brokes all scripts

When I'm using PHP in JavaScript, then all scripts don't work...
Even if I use php in comment.
<script>
//var variable = <?php echo json_encode($_SESSION['abc']); ?>;
</script>
This comment above destroy all scripts in <script></script> tags.
When I'll delete this line with the comment, then every script will work.
The same thing is when I just want to use PHP in JavaScript (without comment).
Could You help me ?
Here is code which was cut by me (to give You only necessary part of code), please help :) :
<?php
session_start();
if (isset($_POST['login']) && isset($_POST['password']) && isset($_POST['email']))
{
$validation = true;
$firstName = $_SESSION['firstName'];
$lastName = $_SESSION['lastName'];
$street = $_SESSION['street'];
$phone = $_SESSION['phone'];
$login = $_POST['login'];
$password = $_POST['password'];
$email = $_POST['email'];
require_once "connect.php";
mysqli_report(MYSQLI_REPORT_STRICT);
try
{
$connection = new mysqli($host, $db_user, $db_password, $db_name);
if($connection->connect_errno!=0)
{
throw new Exception(mysqli_connect_errno());
}
else
{
if ($validation == true) // when validation process will be successfuly done - i cut validation process
{
if($connection->query("INSERT INTO users values (NULL, '$firstName', '$lastName', '$street', '$phone', '$login', '$password', '$email')"))
{
$_SESSION['abc'] = "done";
//here is also header(location) to login page
}
else
{
throw new Exception($connection->error);
}
}
$connection->close();
}
}
catch(Exception $e)
{
echo '<div class="error">error. sorry, please to register in other term</div>';
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<script>
//there are other functions for local/session storage
function deleteSessionData()
{
var variable = "<?php echo $_SESSION['abc']; ?>";
if(variable == "done")
{
sessionStorage.removeItem('firstName');
sessionStorage.removeItem('lastName');
sessionStorage.removeItem('street');
sessionStorage.removeItem('phone');
sessionStorage.removeItem('login');
sessionStorage.removeItem('password');
sessionStorage.removeItem('email');
}
}
</script>
</head>
<body>
<form id="myForm" method="post">
<label for="login">Login: </label>
<input type="text" id="login" name="login">
<label for="password">Password: </label>
<input type="text" id="password" name="password">
<label for="email">E-mail:</label>
<input type="email" id="email" name="email">
<button onclick="java script: document.getElementById('myForm').submit();deleteSessionData();">Register</button>
</form>
</div>
</body>
</html>
you need to comment the php too
//var variable = <?php // echo json_encode($_SESSION['abc']); ?>;
I wouldn't inject PHP into javascript like this without sanitation though.

PHP form request with javascript form validation

So i have a javascript that performs a simple form validation on
<form method="get" name="formPG" onsubmit="return (validateForm());" action="filter.php">
<p>Noun <input id="iNoun" name="fNoun" type="text" /></p>
<p><br />
Pronoun <input id="iPronoun" name="fPronoun" type="text" /></p>
<p><br />
Verb <input id="iVerb" name="fVerb" type="text" /></p>
<p><br />
Adverb <input id="iAdverb" name="fAdverb" type="text" /></p>
<p><br />
Adjective <input id="iAdjective" name="fAdjective" type="text" /></p>
<p><br />
Silly Word <input id="iSillyWord" name="fSillyWord" type="text" /></p>
<p><br />
Magic Spell <input id="iMagic" name="fMagic" type="text" /></p>
<p><br />
<input type="submit" value="submit" /></p>
</form>
The javascript says "hey this is filled in" or "hey this isn't filled in, please fill this in".
Now, I have a PHP file that collects the information from the HTML tags
<?php
require "start.php"
?>
<div class="work"><</div>
<?php
if(!empty($_GET['fNoun']) && !empty($_GET['fPronoun']) && !empty($_GET['fVerb']) && !empty($_GET['fAdverb']) && !empty($_GET['fAdjective']) && !empty($_GET['fSillyWord']) && !empty($_GET['fMagic']))
{
$noun = filter_input(INPUT_GET, 'fNoun', FILTER_SANITIZE_STRING);
$pronoun = filter_input(INPUT_GET, 'fPronoun', FILTER_SANITIZE_STRING);
$verb = filter_input(INPUT_GET, 'fVerb', FILTER_SANITIZE_STRING);
$adverb = filter_input(INPUT_GET, 'fAdverb', FILTER_SANITIZE_STRING);
$adjective = filter_input(INPUT_GET, 'fAdjective', FILTER_SANITIZE_STRING);
$sillyword = filter_input(INPUT_GET, 'fSillyWord', FILTER_SANITIZE_STRING);
$magic = filter_input(INPUT_GET, 'fMagic', FILTER_SANITIZE_STRING);
echo "There was once a $adjective magician who roamed the wild terrains of $adverb <br>The magician $noun cast the mighty spell $magic around the $sillyword <br>$pronoun knew there was only one way to win the war - $verb";
}
else
{
echo "parameters not provided."
}
?>
<?php
require "end.php"
?>
The problem I am running into is it collects the information (which you can see it in the URL) however, it doesn't echo out the information to the screen.
Could it be a weird interaction with PHP and JavaScript?
Here is one option, you will want to first check what filter_input returns and then you can assign that to a variable and display it, below is a simple example, derived from what w3schools provides here: https://www.w3schools.com/php/showphp.asp?filename=demo_func_filter_input . The example below validates an email from a form and if filter input does not return false it will print a message saying 'This email: is a valid Email'
Example:
<!DOCTYPE html>
<html>
<body>
<form method="get" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
E-mail: <input type="text" name="email">
<input type="submit" name="submit" value="Submit">
</form>
<?php
if (isset($_GET["email"])) {
if (!filter_input(INPUT_GET, "email", FILTER_VALIDATE_EMAIL) === false) {
$email = filter_input(INPUT_GET, "email", FILTER_VALIDATE_EMAIL);
echo("This email: ".$email." is a valid Email");
} else {
echo("Email is not valid");
}
}
?>
</body>
</html>
Hope this helps.

AJAX form with priority values

I want to create form with priority values, first check vlaue of recaptcha if is correct (not spammer) then do process for example:
if(isset($_POST['g-recaptcha-response']))
{
$captcha=$_POST['g-recaptcha-response'];
}
if(!$captcha)
{
echo "enter captcha";
}
$response=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=*******&response=".$captcha."&remoteip=".$_SERVER['REMOTE_ADDR']);
if($response.success==TRUE){
$name = $_POST['name'];
if($name == "hello"){
echo 'correct';
}
else {
echo 'incorrect';
}
}
if($response.success==false)
{
die("spammer!");
}
and HTML code like:
<form id="form" method="POST" action="">
<input id="name" name="name" type="text"/>
<div class="g-recaptcha-response" data-sitekey="******"></div>
<input id="button" type="submit" value="send" />
</form>
<div id="formresult"></div>
<div id="formresult"></div> is for ajax answer
I wrote some script code but not worked and I prefer ask without paste that code in here. how could I do that?

Undefined index: formSubmit [duplicate]

This question already has answers here:
"Notice: Undefined variable", "Notice: Undefined index", "Warning: Undefined array key", and "Notice: Undefined offset" using PHP
(29 answers)
Closed 7 years ago.
I'm building a form to be used to input data into a database. I have the basic form and validation built (I think). When I try testing it on my server/domain I keep getting the error undefined Index: Form Submit. I'm certain it's something minor, but I can't find my error. An extra set of eyes looking at this would be greatly appreciated.
<!DOCTYPE HTML>
<html lang = "en">
<head>
<link rel="stylesheet" type="text/css" href="mystylesheet.css">
<title>Tech Order Department.html</title>
<meta charset = "UTF-8" />
</head>
<body>
<!--Designing my form-->
<h2>New Projects</h2>
<br>
<?php
if($_POST['formSubmit'] == "Submit")
{
$varMovie = $_POST['formProject'];
$varMovie = $_POST['formClient'];
$varMovie = $_POST['formLastName'];
$varMovie = $_POST['formDateReceived'];
}
?>
<form action="myform.php" method="post">
Project:<br>
<input type="text" name="Project">
<br>
Client:<br>
<input type="text" name="Client">
<br>
Last Name:<br>
<input type="text" name="LastName">
<br>
Date Received:<br>
<input type="text" name="DateReceived">
<br><br>
<input type="submit" name="formSubmit" value="Submit">
</form>
<?php
if($_POST['formSubmit'] == "Submit")
{
$errorMessage = "";
if(empty($_POST['formProject']))
{
$errorMessage .= "<li>You forgot to enter a project name!</li>";
}
if(empty($_POST['formClient']))
{
$errorMessage .= "<li>You forgot to enter a client name!</li>";
}
if(empty($_POST['formLastName']))
{
$errorMessage .= "<li>You forgot to enter the tech writer name!</li>";
}
if(empty($_POST['formDateReceived']))
{
$errorMessage .= "<li>You forgot to enter the date received!</li>";
}
$varMovie = $_POST['formProject'];
$varName = $_POST['formClient'];
$varMovie = $_POST['formLastName'];
$varMovie = $_POST['formDateReceived'];
if(!empty($errorMessage))
{
echo("<p>There was an error with your form:</p>\n");
echo("<ul>" . $errorMessage . "</ul>\n");
}
}
?>
</body>
</html>
You should change :
if($_POST['formSubmit'] == "Submit")
To :
if(isset($_POST['formSubmit']) && $_POST['formSubmit'] == "Submit")
When you're using form, you should ALWAYS verify at least once posted that your fields are set.
For example :
We have this quick form :
<form action="action_page.php" method="POST">
First name:<br>
<input type="text" name="firstname" value="">
<br>
Last name:<br>
<input type="text" name="lastname" value="">
<br><br>
<input type="submit" value="Submit">
</form>
First note that on the I've put two attributes :
action : Which is where the form will be send
method : Which is how the form will be send
There are two inputs "firstname","lastname" and a button submit.
Let's say that on the "action_page.php" you want to display : "Hello, firstname lastname".
You could just do the following :
<?php
echo 'Hello, '.$_POST['firstname'].' '.$_POST['lastname'];
?>
And that will print out what you want.
But in the case where those fields would be empty that would create "Undefined Index"...
So to be sure that you won't be using variables that doesn't exist you should do the following :
<?php
//First we create an array that will errors if they occurs
$error = array();
//Then we test if firstname exist
if(isset($_POST['firstname'])) {
//if it does we can assign him.
$firstname = $_POST['firstname'];
}else{
//if it doesn't that's an error.
$error[] = 'Please enter your firstname';
}
//Then we test if lastname exist
if (isset($_POST['lastname'])) {
//if it does we can assign him.
$lastname = $_POST['lastname'];
}else{
//if it doesn't that's an error.
$error[] = 'Please enter your lastname';
}
//In the end we check if we have any error stocked:
if(empty($error)) {
//if it's empty we have all our required data to display our echo
echo 'Hello, '.$firstname.' '.$lastname;
}else{
//else let's show the error
print_r($error);
}
?>
This way we handle any possible "Undefined Index" before they occur and we are sure that our data will return something or at least have an error related.
For check if there was a POST action :-
if (!empty($_POST))
or
if ($_SERVER['REQUEST_METHOD'] == 'POST')
Updated your code , check this
<!DOCTYPE HTML>
<html lang = "en">
<head>
<link rel="stylesheet" type="text/css" href="mystylesheet.css">
<title>Tech Order Department.html</title>
<meta charset = "UTF-8" />
</head>
<body>
<h2>New Projects</h2>
<?php
if ($_POST['formSubmit'] == "Submit") {
$varMovie = $_POST['formProject'];
$varMovie = $_POST['formClient'];
$varMovie = $_POST['formLastName'];
$varMovie = $_POST['formDateReceived'];
}
?>
<form action="myform.php" method="post">
Project:<br>
<input type="text" name="Project">
<br>
Client:<br>
<input type="text" name="Client">
<br>
Last Name:<br>
<input type="text" name="LastName">
<br>
Date Received:<br>
<input type="text" name="DateReceived">
<br><br>
<input type="submit" name="formSubmit" value="Submit">
</form>
<?php
if(isset($_POST['formSubmit']) && $_POST['formSubmit'] == "Submit") {
$errorMessage = "";
if (empty($_POST['formProject'])) {
$errorMessage .= "<li>You forgot to enter a project name!</li>";
}
if (empty($_POST['formClient'])) {
$errorMessage .= "<li>You forgot to enter a client name!</li>";
}
if (empty($_POST['formLastName'])) {
$errorMessage .= "<li>You forgot to enter the tech writer name!</li>";
}
if (empty($_POST['formDateReceived'])) {
$errorMessage .= "<li>You forgot to enter the date received!</li>";
}
$varMovie = $_POST['formProject'];
$varName = $_POST['formClient'];
$varMovie = $_POST['formLastName'];
$varMovie = $_POST['formDateReceived'];
if (!empty($errorMessage)) {
echo("<p>There was an error with your form:</p>\n");
echo("<ul>" . $errorMessage . "</ul>\n");
}
}
?>
</body>
</html>

Send PHP errors back to index

So I have an index.php and a r.php. R.php is the registration part. And index.php is the actual form. My question is how can I have errors from r.php be send back to index.php if they exist. So instead of displaying errors on r.php I want them on index.php and prevent the form from advancing.
Here's the index.php
<!DOCTYPE html>
<html>
<body>
<form method="post" action="r.php">
<input type="text" name="name" placeholder="Name">
<input type="submit">
</form>
</body>
Its all very simple. Now here's r.php
<?php
$name = $_POST['name'];
if ($name < 3){
//display error
}
else {
//proceed
}
?>
Should I do this with JS? Or this there a better way.
One way is to use sessions:
<?php session_start(); ?>
<!DOCTYPE html>
<html>
<body>
<?php echo isset($_SESSION['message']) ? $_SESSION['message'] : ''; ?>
<form method="post" action="r.php">
<input type="text" name="name" placeholder="Name">
<input type="submit">
</form>
</body>
<?php
session_start();
unset($_SESSION['message']);
$name = $_POST['name'];
if ($name < 3){ // you probably want strlen($name) < 3
$_SESSION['message'] = 'error';
header('Location: index.php');
exit;
}
else {
//proceed
}
?>
Other than sessions you could redirect back with a query string and use that:
header('Location: index.php?message=' . urlencode('some kind of error');
Then:
<?php echo isset($_GET['message']) ? $_GET['message'] : ''; ?>
Using a single script for this would be easier, just put this all in one file, and check to see if the form has been submitted. If the form has been submitted, you an just include the variables you want straight away.
This is pretty crude, but it gives you an idea of where you can go with this:
<?php
if (isset($_POST['name'])) {
// Begin processing form stuff
$name = $_POST['name'];
// Initialise error variable
$error = null;
if ($name < 3) {
// Display error, for example:
$error = 'Name is less than 3';
} else {
// Proceed
}
}
?>
<!DOCTYPE html>
<html>
<body>
<?php if ( ! empty($error)) { ?>
<p><?php echo $error; ?></p>
<?php } ?>
<form method="post" action="r.php">
<input type="text" name="name" placeholder="Name">
<input type="submit">
</form>
</body>
</html>
<!DOCTYPE html>
<html>
<?php
$msg = '';
if(isset($_GET['e'])
{
$msg = "Error! Input not valid.";
}
?>
<body>
<?php
if($msg!='')
{
echo "<font color='red'>".$msg."</font>";
}
?>
<form method="post" action="r.php">
<input type="text" name="name" placeholder="Name">
<input type="submit">
</form>
</body>
Just pass a variable e using GET request to the index page if an error is found.
<?php
$name = $_POST['name'];
if ($name < 3){
header("Location: index.php?e=error");
}
else {
//proceed
}
?>
GET request will send the variable e using the URL, and if e is found to be having a value, it means there was an error in r.php
Use javascript for simple form validation. In case you require some security stuff or db stuff, you can use session/cookie or use header function to go back.

Categories

Resources