Transferring control from jquery to php - php

I'm using jquery for registration form. But after email and password are entered and submit button is pressed control doesn't get transferred to php as I expected. I m not fully aware with jquery, just want to add this functionality on registration page.
How can this be done.
<?php
include "config.php";
if( isset($_POST['submit']) ){
$email = $_POST['email'];
$pass = $_POST['password'];
if( $email=="" || $pass==''){
echo "Fields Left Blank","Some Fields were left blank. Please fill up all fields.";
exit;
}
if( !$LS->validEmail($email) ){
echo "E-Mail Is Not Valid", "The E-Mail you gave is not valid";
exit;
}
$createAccount = $LS->register($email, $pass);
if($createAccount === "exists"){
echo "User Exists.";
}elseif($createAccount === true){
header("Location: /rootTesting/dashboardInitial.php", true, 302);
die();
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="js/jquery.easing.1.3.js.js"> </script>
<script type="text/javascript">
$(function()
{
$("ul li:first").show();
var ck_email = /^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i
var ck_password = /^[A-Za-z0-9!##$%^&*()_]{3,20}$/;
$('#email').keyup(function()
{
var email=$(this).val();
if (!ck_email.test(email))
{
$(this).next().show().html("Enter valid email");
}
else
{
$(this).next().hide();
$("li").next("li.password").slideDown({duration: 'slow',easing: 'easeOutElastic'});
}
});
$('#password').keyup(function()
{
var password=$(this).val();
if (!ck_password.test(password))
{
$(this).next().show().html("");
}
else
{
$(this).next().hide();
$("li").next("li.submit").slideDown({duration: 'slow',easing: 'easeOutElastic'});
}
});
$('#submit').click(function()
{
var email=$("#email").val();
var password=$("#password").val();
if(ck_email.test(email) && ck_password.test(password) )
{
$("#form").show().html("<h1>Thank you!</h1>");
}
else
{
}
return false;
});
})
</script>
</head>
<body>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<ul>
<li class="email">
<label>Email: </label><br/>
<input type="text" name="email" id="email" />
</li>
<li class="password">
<label>Password: </label><br/>
<input type="password" name="password" id="password" />
</li>
<li class="submit">
<input type="submit" value=" Register " id='submit'/>
</li>
</ul>
</form>
</body>
</html>

Just give a name attribute to your submit button and make sure to make it's value submit. So it becomes:
<input type="submit" value=" Register " id='submit' name='submit'/>
PHP sends the data by name not by id.

Try with
$('form[name=foo]').submit(function(){
var email=$("#email").val();
var password=$("#password").val();
if(!ck_email.test(email) || !ck_password.test(password) ) {
return false;
// errors found
}
});
<form method="post" name="foo">
<ul>
<li class="email">
<label>Email: </label><br/>
<input type="text" name="email" id="email" />
</li>
<li class="password">
<label>Password: </label><br/>
<input type="password" name="password" id="password" />
</li>
<li class="submit">
<input type="submit" value=" Register " id='submit'/>
</li>
</ul>
</form>

You have missed out the name to the button.
Since you are checking the $_POST['submit'], You need to modify your button HTML as
<input type="submit" name="submit" value="Register" id="submit"/>

Related

Simply insert data into a DB

I'm pretty new to php and have been trying to create a site using it. I have created a login page and am trying to provide the option to create a new user by inserting a username & pass into the DB. I feel like this is something simple that I'm missing but i'm not sure so hopefully someone can help :)
php ~
<?php
session_start();
unset($_SESSION["currentUser"]);
unset($_SESSION["currentUserID"]);
if (isset($_POST["action"]) && $_POST["action"]=="create") {
$formUserC=$_POST["name"];
$formPassC=$_POST["pword"];
include("dbConnect.php");
$dbQuery=$db->prepare("select * from users");
$newAcc = "INSERT INTO users (username, password) VALUES ('$formUserC', '$formPassC')";
if($newAcc){
echo "<p>Your account was successfully created.";
}
else{
echo "<p>Error</p>";
}
}
if (isset($_POST["action"]) && $_POST["action"]=="login") {
$formUser=$_POST["username"];
$formPass=$_POST["password"];
include("dbConnect.php");
$dbQuery=$db->prepare("select * from users where username=:formUser");
$dbParams = array('formUser'=>$formUser);
$dbQuery->execute($dbParams);
$dbRow=$dbQuery->fetch(PDO::FETCH_ASSOC);
if ($dbRow["username"]==$formUser) {
if ($dbRow["password"]==$formPass) {
$_SESSION["currentUser"]=$formUser;
$_SESSION["currentUserID"]=$dbRow["id"];
if (isset($_SESSION["homePage"]))
header("Location: addToBasket.php");
else header("Location: homePage.html");
}
else {
header("Location: login.php?failCode=2");
}
} else {
header("Location: login.php?failCode=1");
}
} else {
?>
html (mostly) ~
<html >
<head>
<meta charset="UTF-8">
<title>Flat HTML5/CSS3 Login Form</title>
<link rel="stylesheet" href="css/loginstyle.css">
</head>
<body>
<div class="login-page">
<div class="form">
<form class="register-form" name="create" method="post" action="login.php">
<input type="text" name="name" placeholder="name"/>
<input type="password" name="pword" placeholder="pword"/>
<input type="hidden" name="action" value="create">
<input type="submit" value="create"/>
<p class="message">Already registered? Sign In</p>
</form>
<form name="login" method="post" action="login.php">
<input type="text" name="username" placeholder="username"/>
<input type="password" name="password" placeholder="password"/>
<input type="hidden" name="action" value="login">
<input type="submit" value="login"/>
<p class="message">Not registered? Create an account</p>
</form>
<?php
if (isset($_GET["failCode"])) {
if ($_GET["failCode"]==1)
echo "<h3 style='color:red;'>Invalid username entered</h3>";
if ($_GET["failCode"]==2)
echo "<h3 style='color:red;'>Invalid password entered</h3>";
}
?>
</div>
</div>
<script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
<script src="js/loginindex.js"></script>
</body>
</html>
<?php
}
?>
P.S. some of it's code I nabbed from others. Thanks in advance.

Multiple arrays to a JSON array to PHP via AJAX

I have a form
<form id="ajax-form" onsubmit="return false;">
<p class="legend">All fields marked with an asterisk are required.</p>
<fieldset>
<legend>User Details</legend>
<div><label for="post[uname]">Username <em>*</em></label> <input id="post[uname]" type="text" name="uname" value="" /></div>
<p class='note' id='err[Name]'></p>
</fieldset>
<div class="buttonrow">
<input type="submit" value="Submit This Form via AJAX" class="button" />
<input type="button" value="Start Again" class="button" />
Refresh this Page
</div>
</form>
I have two arrays post and err. I'm trying to send them to php and then in php it will json_encode the array and print it on the screen like so:
{
"err": {
"uname": "Please enter a user name"
}
"post": {
"uname": ""
}
}
or this is if the user did enter a name:
{
"post": {
"uname": "Bob Ross"
}
}
There could be multiple fields for post and err but it should still follow the same suite.
How do I send the data to php, I understand it's some sort of serializeArray but it doesn't format it properly when I do:
JSON.stringify($("#ajax-form").serializeArray())
A jsfiddle to full html:
https://jsfiddle.net/dzv8ttjn/1/
Your best bet is to call .serialize(); on the form which will give you something like: user-name=some%20name&email=some%20emale&gender=Female&interests=Software
Send that to the PHP script, and have the script create the format of the response while looping over the $_POST array. Something like the below would work:
(note that I've changed your id's to be more sensible and updated the jQuery version used)
<?php
if(count($_POST)>0){
$response = ['err'=>[], 'post'=>[]];
foreach($_POST as $key => $value)
{
$response['post'][$key]=$value;
if(trim($value) == '') $response['err'][$key]='Please enter a '.$key;
}
echo json_encode($response);
exit;
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title> Lab4: Form Validation with AJAX,JQuery,JSON and PHP</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>
<script type="text/javascript">
$("#ajax-form").on('submit', function(event) {
event.preventDefault();
var dataString = $(this).serialize();
$.ajax({
type: "POST",
// url: "page.php", // add this line to send to some page other than the this one
data: dataString,
success: function(response) {
if (response) {
alert('test worked');
}
},
error: function(xhr, status, error) {
console.log(xhr);
}
});
});
</script>
</head>
<body>
<div id="wrapper">
<h2>Form Validation with AJAX,JQuery,JSON and PHP</h2>
<div class="form-container">
<span id="ajax-message"></span>
<form id="ajax-form" onsubmit="return false;">
<p class="legend">All fields marked with an asterisk are required.</p>
<fieldset>
<legend>User Details</legend>
<div>
<label for="uname">Username <em>*</em></label>
<input id="uname" type="text" name="user-name" value="" />
<p class='note' id='name-error'></p>
</div>
<div>
<label for="password">Email Address <em>*</em></label>
<input id="password" type="text" name="email" value="" />
<p class='note' id='password-error'></p>
</div>
<div>
<label for="post[gender]">Gender <em>*</em></label>
<input type="radio" name="gender" value="Male" class="form-check-input" id="Male" required> Male
<input type="radio" name="gender" value="Female" class="form-check-input" id="Female" required> Female
<p class='note' id='gender-error'></p>
</div>
<div>
<label for="interests">Interests<em>*</em></label>
<input type="checkbox" name="interests" value="Music" class="form-check-input" id="Music"> Music
<input type="checkbox" name="interests" value="Software" class="form-check-input" id="Software"> Software
<input type="checkbox" name="interests" value="Hardware" class="form-check-input" id="Hardware"> Hardware</div>
</fieldset>
<div class="buttonrow">
<input type="submit" value="Submit This Form via AJAX" class="button" />
<input type="button" value="Start Again" class="button" />
Refresh this Page
</div>
</form>
</div>
<h3>JSON Array</h3>
<pre id='debug'></pre>
</div>
</body>
</html>

PHP/HTML5: Assign Latitude Longitude to variables

I'm new to PHP/HTML5. I found the following HTML5 example to get device latitude and longitude. But it's just an example by showing the lat/long upon a button click.
Problem:
What I need is, when user submit a form, I will INSERT the value into MySQL.
At this moment, I wanted to get the device lat/long and assign as variables so I can use the variables to INSERT into MySQL at the same time. I have ready table in my DB for both lat and long.
Please give me some hint, guide, tips to me to achieve what I need. Help will be very much appreciated. Thank you.
The code:
<!DOCTYPE html>
<html>
<body>
<p id="demo">Click the button to get your coordinates:</p>
<button onclick="getLocation()">Try It</button>
<script>
var x=document.getElementById("demo");
function getLocation()
{
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(showPosition);
}
else{x.innerHTML="Geolocation is not supported by this browser.";}
}
function showPosition(position)
{
x.innerHTML="Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
}
</script>
</body>
</html>
The form:
<form id="form1" name="form1" method="post" action="';
echo $_SERVER['PHP_SELF'];
echo '">
<p>Please complete this form and I will contact you as soon as possible. Thank you.</p>
<p>
<label for="name">Your Name</label>
<input type="text" name="name" id="name" />
<label for="phone">Contact Number</label>
<input type="text" name="phone" id="phone" />
<label for="message">Message to Owner</label>
<textarea name="message" id="message" cols="45" rows="5"></textarea>
<input type="submit" name="submit" id="submit" value="Submit Info" />
</p>
</form>
New Simpler Form Example with suggested code
<!DOCTYPE html>
<html>
<head>
<title>FurkidTag.com</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.0/jquery.mobile-1.4.0.min.css">
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.0/jquery.mobile-1.4.0.min.js"></script>
<title>Sample Form</title>
</head>
<body>
<script>
$(function() {
$("input[name='latitude']").val(position.coords.latitude);
$("input[name='longitude']").val(position.coords.longitude)
});
</script>
<?php
if(isset($_POST['submit']))
{
$name = $_POST['name'];
$lat = $_POST['latitude'];
$lon = $_POST['longitude'];
echo "User Has submitted the form and entered this name : <b> $name </b>";
echo "<br>Latitude: $lat.";
echo "<br>Longitude: $lon.";
}
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type='hidden' value='' name='latitude'/>
<input type='hidden' value='' name='longitude'/>
<input type="text" name="name"><br>
<input type="submit" name="submit" value="Submit Form"><br>
</form>
</body>
</html>
You'll need to use AJAX to pass the values to PHP in another page, in this example I'm using Jquery to make the ajax request
$(function() {
$.get('getPosition.php', {
Latitude: position.coords.latitude,
Longitude: position.coords.longitude
}
});
In your getPosition.php you have to get the values like:
$latitude = (isset($_GET['latitude']) && is_numeric($_GET['latitude']) ? $_GET['latitude'] : NULL;
$longitude = (isset($_GET['longitude']) && is_numeric($_GET['longitude']) ? $_GET['longitude'] : NULL;
And make your sql stuff
UPDATE
To bind the value to your input form
$(function() {
$("input[name='latitude']").val(position.coords.latitude);
$("input[name='longitude']").val(position.coords.longitude)
});
In your form add two imput type hidden
<input type='hidden' value='' name='latitude'/>
<input type='hidden' value='' name='longitude'/>
UPDATE 2
<?php
if (isset($_POST['submit'])) {
$name = $_POST['name'];
$lat = $_POST['latitude'];
$lon = $_POST['longitude'];
echo "User Has submitted the form and entered this name : <b> $name </b>";
echo "<br>Latitude: $lat.";
echo "<br>Longitude: $lon.";
}
?>
<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
var x = document.getElementById("demo");
function getLocation()
{
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(bindPosition);
}
else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function bindPosition(position) {
$("input[name='latitude']").val(position.coords.latitude);
$("input[name='longitude']").val(position.coords.longitude);
}
</script>
</head>
<body onload="getLocation()">
<form id="form1" name="form1" method="post" action="">
<p>Please complete this form and I will contact you as soon as possible. Thank you.</p>
<p>
<label for="name">Your Name</label>
<input type="text" name="name" id="name" />
<label for="phone">Contact Number</label>
<input type="text" name="phone" id="phone" />
<label for="message">Message to Owner</label>
<textarea name="message" id="message" cols="45" rows="5"></textarea>
<input type='hidden' value='' name='latitude'/>
<input type='hidden' value='' name='longitude'/>
<input type="submit" name="submit" id="submit" value="Submit Info" />
</p>
</form>
</body>
</html>

Validation on my form? "Please fill in required fields" [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
I have a username form. Which have 2 fields, username and password.
Basically I want it so if the user has not entered the fields and pressed 'submit' an error displays like
"Please enter the required fields"
I know it's possible with JavaScript or PHP but unsure how to do it.
Here is the code of the user and password form:
<div id="sessionContainer" class="clearfix">
<div class="content">
<form action="goto.php" class=" sign-in" method="post">
<div style="margin:0;padding:0"></div>
<h3>Enter Details</h3>
<p><font size="-1">Please enter your details</font></p><br>
<div class="clearfix">
<label for="">Username or email address</label><br>
<input class="xlarge" id="email" name="email" tabindex="1" type="text" value="" />
</div>
<div class="clearfix">
<label for=""><br>
Password</label><br>
<input class="xlarge" id="password" name="password" tabindex="2" type="password" value="" />
</div>
<p class="remember"> </p>
<p class="remember">
<button class="btn btn-m btn-blue" id="signin_submit" name="commit" type="submit" tabindex=5>Sign in</button>
</p>
Thanks
<?php if(!isset($_POST['email']) || !isset($_POST['password'])
This code will check if either of those fields has a value. If it does not, you can output an error message. The code in the whole context is as follows:
<?php if(!isset($_POST['email']) || !isset($_POST['password']): ?>
<div>Please fill in all fields!</div>
<?php endif; ?>
This is my answer...in clasic javascript xD:
<html>
<head>
<script type="text/javascript">
function validar()
{
var right = 1;
if(document.getElementById('email').value.length==0)
{
right = 0;
document.getElementById('emptymail').innerHTML = "Empty Mail o Username";
}
if(document.getElementById('password').value.length==0)
{
right = 0;
document.getElementById('emptypass').innerHTML = "Empty Password";
}
if(right == 1)
{
document.forms["formu"].submit();
}
}
</script>
</head>
<body>
<form action="goto.php" class=" sign-in" method="post" name="formu" id="formu">
<div style="margin:0;padding:0"></div>
<h3>Enter Details</h3>
<p><font size="-1">Please enter your details</font></p><br>
<div class="clearfix">
<label for="">Username or email address</label><br>
<input class="xlarge" id="email" name="email" tabindex="1" type="text" value="" /><div id="emptymail"></div>
</div>
<div class="clearfix">
<label for=""><br>
Password</label><br>
<input class="xlarge" id="password" name="password" tabindex="2" type="password" value="" /><div id="emptypass"></div>
</div>
<p class="remember"> </p>
<p class="remember">
<button class="btn btn-m btn-blue" id="signin_submit" name="commit" type="button" tabindex=5 onclick="validar();">Sign in</button>
</p>
</form>
</body>
</html>
Saludos ;)
HTML only solution using the required attribute (works only in newer browsers):
<input required="required" />
An example how to do a jscript based solution can be found here, here or this one with a little jquery help.
Use jQuery Validate for validations
Download it from here and call it. and then add this code
rules:
{
email:
{
required: true
}
},
messages:
{
email:
{
required: "Please enter your email."
}
}
OR simply Use HTML 5 validations
<input id="email" name="email" type="text" value="" required />
To do it using JavaScript, you are looking for the OnSubmit attribute of your form
There are numerous things you can do if the function you called with OnSubmit fails (returns false), but as an example this code will show a popup box
<script>
function checkForm()
{
if (document.getElementById('email').value.length==0 || document.getElementById('password').value.length==0)
(
alert("fill in required fields")
return false;
)
return true;
}
<script>
Then in your form tag you put
<form onsubmit="return checkForm()" ...
var $form = $('form'),
$user = $('#email),
$pass = $('#password');
$form.on('submit', function(e) {
e.preventDefault(); // stop the default behavior
if ($user.text().length === 0) {
$user.addClass('error'); // do something with the error class or add attribute 'required'
} else if ($pass.text().length === 0) {
// do something else
} else if ($user.text().length > 0 && $pass.text().length > 0) {
// post the form
$.ajax({
url: //URL where you send,
data: $form.serialize(),
success: function(e) { // do something },
error: function(e) { // do something }
});
}
}

How to call javascript function in php code?

on my login form, i am putting server side validations and if error occurs i want to display those error just below the validated control. Now for this, i am trying to call javascript function to show validation message in php code but not able to call.
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
if($_POST['txtUsername']=='')
{
//here i want to call javascript function to display message
}
}
?>
<form action="login.php" method="POST">
Username <input type="text" size="30" name="txtUsername" id="user" /><br />
Password <input type="password" size="30" name="txtPassword" id="pass" /><br />
<input type="submit" value="Login" name="loginSubmit"/>
</form>
<script type="text/javascript">
function showMessage(value)
{
document.getElementById(value).innerHTML= value+"can not be empty.";
}
</script>
Please tell me how to display server side validation just below the validated control in form.
use this
if($_POST['txtUsername']=='')
{
echo '<script> showMessage("txtUsername"); </script>';
}
Something like this
<html>
<head>
<script type="text/javascript">
function showMessage(value)
{
document.getElementById(value).innerHTML= value+"can not be empty.";
}
</script>
</head>
<body>
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
if($_POST['txtUsername']=='')
{
echo '<script> showMessage("txtUsername"); </script>';
}
}
?>
<form action="login.php" method="POST">
Username <input type="text" size="30" name="txtUsername" id="txtUsername" /><br />
Password <input type="password" size="30" name="txtPassword" id="txtPassword" /><br />
<input type="submit" value="Login" name="loginSubmit"/>
</form>
</body>
</html>
You can put your php code anywhere you like let's say in the body like attribute. You can try the following code:
<body <?php
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
if($_POST['txtUsername']=='')
{
echo "onload = 'showMessage("VALUE")'";
}
}
?> > // end of body start tag
<form action="login.php" method="POST">
Username <input type="text" size="30" name="txtUsername" id="user" /><br />
Password <input type="password" size="30" name="txtPassword" id="pass" /><br />
<input type="submit" value="Login" name="loginSubmit"/>
</form>
</body>
<script type="text/javascript">
function showMessage(value)
{
document.getElementById(value).innerHTML= value+"can not be empty.";
}
</script>
If the validation is successful the php code wont echo anything and the javascript function will not be called. Works for me :). Tell me if this helps.
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
if($_POST['txtUsername']=='')
{
?>
<script>
//Define the function somewhere in the top or in external js and include it.
callyourfunction();
</script>
<?php
}
}
?> //Its not working

Categories