AJAX form with priority values - javascript

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?

Related

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.

How to Call Ajax from HTML/JS to start PHP Function?

I'm working on a code that will show an alert when form is submitted and then redirect back to home page. If an empty form is submitted, I want to show an error alert. I realize that I cannot call PHP from onclick, and that I need to instead call a JS function that will start my PHP function. Can someone tell me if my PHP code is on the right track, and how to initialize the AJAX function? Trying to do this WITHOUT JQuery. Thanks!
html
<form method="POST" action="contact.php">
<label for='message'>Leave a Message:</label> <br><br>
<textarea rows="15" cols="45" name="message" id="message" ></textarea>
<br><br>
<input type="submit" name='submit' value="send!" onclick="startajax()"/>
</form>
and php
<?PHP
$subject="New Message!";
$message=$_POST ["message"];
function leavemessage () {
if(!empty($_POST['message'])) {
echo '<script type="text/javascript">
function error(){
alert("Error!");
window.location.replace=(contact.html);}
</script>';
}
else
{
{mail ($email, $subject, $message, "From:".$from);}
echo '<script type="text/javascript">
function confirmation(){
alert("Message Sent!");
window.location.replace (index.html);}
</script>';
}
}
?>
You can do this with jquery ajax to complete your request like this:
HTML:
<form method="POST" id="contact-form" onsubmit="return startajax()" >
<label for='message'>Leave a Message:</label> <br><br>
<textarea rows="15" cols="45" name="message" id="message" ></textarea>
<br><br>
<input type="submit" name='submit' value="send!"/>
</form>
PHP:
<?PHP
$subject="New Message!";
$message=$_POST ["message"];
if(!empty($message)) {
//your email code here
exit(json_encode(array('error' => 0, 'errorMessage' => '')));
} else {
exit(json_encode(array('error' => 1, 'errorMessage' => 'Message is required')));
}
}
?>
Jquery:
<script>
var startajax = function(){
var url = 'contact.php';
$.ajax({
url : url,
type : "POST",
dataType : "JSON",
data : $('#contact-form').serialize(),
success : function(response) {
if (response.error == 0) { // success
$('#contact-form')[0].reset();
alert('SUCCESS MESSAGE');
} else { // error
alert(response.errorMessage);//form is invalid
}
}
})
return false;
}
</script>
Just make sure you have jquery library included to your page.
As per request, Without jQuery code below:
HTML:
<form method="POST" id="contact-form" action="contact.php" >
<label for='message'>Leave a Message:</label> <br><br>
<textarea rows="15" cols="45" name="message" id="message" ></textarea>
<?php if (isset($_GET['error'])) { ?>
<p style="color:red;">Message is required</p>
<?php } ?>
<br><br>
<input type="submit" name='submit' value="send!"/>
</form>
PHP:
<?PHP
if (isset($_POST) && !empty($_POST)) {
$subject="New Message!";
$message=$_POST ["message"];
if(!empty($message)) {
//your email code here
echo '<script>window.location.href="index.html"</script>';
} else {
echo '<script>window.location.href="index.html?error=1"</script>';
}
}
}
?>

Access session value

How to make a form style hidden if a specific session is set?
I did it that way
<form action="" method="post" <?php if ((isset($_SESSION['start']) )|| (isset($_SESSION['visitor']) )){ echo 'style="display:none;"'; } ?>>
<input type="radio" name="log" id="viso" value="vis" checked onclick="javascript:yesnoCheck();"> Visitor<br>
<input type="radio" name="log" id="uso" value="use" onclick="javascript:yesnoCheck();" > User<br>
<label name="frm" id="frm" style="display:none" ><b>Password</b></label>
<input type="password" style="display:none" name="pw" id="pw" placeholder="Enter Password" >
<input type="submit" >
</form>
<?php
if ( isset ($_POST['log'])&& $_POST['log']=="vis" )
{
$_SESSION["visitor"]="true";
unset($_SESSION["start"]);
}
else if ( isset ($_POST['log'])&& $_POST['log']=="use" )
{
if ( isset($_POST['pw']) && $_POST['pw']!="1111" )
echo "Wrong password";
else if ( isset ($_POST['pw'])&& $_POST['pw']=="1111" )
{
$_SESSION['start']="Welcome";
unset($_SESSION["visitor"]);
}
}
?>
but it's only hidden if i press on the submit button twice not from the first time
You have a simple logical flaw .You are checking for session before you set them .When user fills form and submits , your php runs this
<form action="" method="post" id="lol" <?php if ((isset($_SESSION['start']) )|| (isset($_SESSION['visitor']) )){ echo 'style="display:none;"'; } ?>>
Note that at this time no session is set so form will not have display:noneand will get displayed **even though user has entered his details correctly still when response come form will be visible.Now to fix the issue move your session check before form display code
<?php
if ( isset ($_POST['log'])&& $_POST['log']=="vis" )
{
$_SESSION["visitor"]="true";
//....more stuff
//...
} ?>
<form action="" method="post" id="lol" <?php if ((isset($_SESSION['start']) )|| (isset($_SESSION['visitor']) )){ echo 'style="display:none;"'; } ?>>

How to give action on php pages

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.

Two form on a single page : How to identify which form validate using jquery ajax function

I have a html page which contains
a form with fields for sign up (registration / new member)
a form for sign in (login for already member)
The sign in form is :
<form class="dialog-form">
<div class="form-group">
<label>E-mail</label>
<input type="text" placeholder="email#domain.com" class="form-control">
</div>
<div class="form-group">
<label>PAssword</label>
<input type="password" placeholder="My PAssword" class="form-control">
</div>
<input type="submit" name="sign_in" value="Connexion" class="btn btn-primary">
</form>
The sign up form is :
<form class="dialog-form" action="bat/user_validation.php" method="post">
<div class="form-group">
<label>E-mail</label>
<input type="text" placeholder="email#domain.com" class="form-control">
</div>
<div class="form-group">
<label>Password</label>
<input type="password" placeholder="My secret password" class="form-control">
</div>
<div class="form-group">
<label>Repeat Password</label>
<input type="password" placeholder="Type your password again" class="form-control">
</div>
<input type="submit" name="sign_up" value="Inscription" class="btn btn-primary">
</form>
One the other side, I have a php script file which contains function to check and insert a userid.
function getPassword($utilisateur) {
try {
$dbh = new PDO(DSN, USER, PASS);
$uid = $utilisateur;
$sql = "SELECT password FROM cc_users WHERE uid =:uid";
$sth = $dbh->prepare($sql);
$sth->execute(array(':uid'=>$uid));
$result = $sth->fetchAll();
return (count($result) == 1) ;
} catch (PDOException $e) {
print "Erreur ! : " . $e->getMessage() . "<br/>";
die();
}
}
function setPassword($uid, $pass) {
$dbh = new PDO(DSN, USER, PASS);
$sql = "UPDATE cc_users SET password =:pass where uid =:uid";
$sth = $dbh->prepare($sql);
$sth->execute(array(':pass'=>$pass ,':uid'=>$uid));
echo $count = $sth->rowCount();
return $dbh->exec($sql);
}
function newPassword($utilisateur, $pass) {
$crypt = crypt($pass);
return setPassword($utilisateur, $crypt);
}
function checkPassword($utilisateur, $pass) {
if (empty($pass)) return FALSE;
$interne = getPassword($utilisateur);
$crypt = crypt($pass, $interne);
return ($interne === $crypt);
}
print_r($_POST);
My questions are :
How I can check on which form the user is coming?
How can I do an $.ajax call for checking the form? If yes how?
Thanks
HTML:
Form 1:
<form id="form1">
<input type="submit" value="submit" />
</form>
Form 2:
<form id="form2">
<input type="submit" value="submit" />
</form>
jQuery:
$('form').on('submit', function () {
console.log($(this).attr('id')); // Logs the id of the submitted form
});
Give name for <form>
<form class="dialog-form" name="signin">
<form class="dialog-form" action="bat/user_validation.php" method="post" name="signup">
You can check $_POST global to see if it contains the name of your <input type="submit" />. It will contain either sign_up or sign_in, depending on what button did the user press.
For example:
if(isset($_POST['sign_up']){
$signingUp = true;
}
If you want to submit the form using jQuery ajax, you can use the following code snippet:
$.post('bat/user_validation.php', $('form.dialog-form').serialize());
Though the selector should be more concrete, probably including a form ID to distinguish between the two forms.

Categories

Resources