PHP -> jQuery -> AJAX form validation [duplicate] - javascript

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 6 years ago.
I'm using jQuery validation for a registration form in PHP. In my PHP my form is as follow:
<form id="register-form">
<input class="form-control" name="dispName" placeholder="Display name" type="text">
<input class="form-control" name="email" placeholder="Email address" type="email">
<input class="form-control" name="password" id="password" placeholder="Password" type="password">
<input class="form-control" name="password2" placeholder="Re-enter password" type="password">
<input class="btn btn-primary" id="submit-button" type="submit" value="Request Access">
</form>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.1.3.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.13.0/jquery.validate.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.13.0/additional-methods.min.js"></script>
<script src="request.js"></script>
In my request.js the validation is as follow:
$.validator.addMethod("checkUserName",
function(value, element) {
var result = false;
$.ajax({
type:"POST",
async: false,
url: "check-username.php", // script to validate in server side
data: {dispName: value},
success: function(data) {
result = (data == true) ? true : false;
}
});
// return true if username is exist in database
return result;
},
"This username is already taken! Try another."
);
$("#register-form").validate({
rules: {
dispName: {
required:true,
nowhitespace: true,
lettersonly: true,
checkUserName: true
},
email: {
required: true,
email: true,
remote: "http://localhost:3000/inputValidator"
},
pw: {
required: true,
strongPassword: true
},
cpw: {
required: true,
equalTo: '#password'
}
},
messages: {
email: {
required: 'Please enter an email address.',
email: 'Please enter a <em>valid</em> email address.',
}
}
});
in my PHP validation server side:
<?php
$searchVal = $_POST['dispName'];
try {
$dbh = new PDO("mysql:host=$hostname;dbname=$dbname", $username, $password);
$sql = "SELECT * FROM users WHERE dname = " . "'" . $searchVal . "'";
$stmt = $dbh->query($sql);
$result = $stmt->fetch(PDO::FETCH_ASSOC);
if($result){
echo 'true';
}else {
echo 'false';
}
$dbh = null;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
I keep getting This username is already taken! Try another. even i use name not in the database. I tested on check-username.php on the server using a dummy "POST" value and it worked fine. So i've got a strong feeling its with the syntax in request.js. Can anyone point me in the right direction.... Thank in advance...

you can do something like this:
$.validator.addMethod("checkUserName",
function(value, element) {
var result = false;
$.ajax({
type:"POST",
async: false,
url: "check-username.php", // script to validate in server side
data: {dispName: value},
success: function(data) {
result = (data == true) ? true : false;
if(result == true){/*here you show error according to your way*/}
}
});
},
);

var typingTimerEmail; //timer identifier
var doneTypingIntervalEmail = 1000; //time in ms, 5 second for example
var $input = $('#email');
//on keyup, start the countdown
$input.on('keyup', function () {
clearTimeout(typingTimerEmail);
$('#submit').attr("disabled", true);
typingTimerEmail = setTimeout(doneTypingEmail, doneTypingIntervalEmail);
});
function doneTypingEmail () {
//do something
var url = "http://172.16.0.60/bird_eye_api/";
var email_exist = $('#email').val();
if(email_exist.length > 0){
$('.email_exist_msg').hide();
$('#submit').attr("disabled", false);
//$('.check_mail').css('border','1px solid #ff0000');
$.ajax({
url: url + "admin/check",
type: 'POST',
data: {'email':email_exist},
success: function (data) {
console.log(data)
if(data == 'true'){
$('#submit').attr("disabled", true);
$('.email_exist_msg').html('User with this email already exist').show();
} else {
$('#submit').attr("disabled", false);
//$('.check_mail').css('border','');
$('.email_exist_msg').html('User with this email already exist').hide();
}
},
});
}
if(email_exist.length==0){
$('.email_exist_msg').hide();
//$('.check_mail').css('border','')
}
}
You can set your custom URL to that. On Key up of your email field it will fire ajax to your URL and will check if users exists or not. Certainly return true or false. According to that in ajax success it will display message.

Related

Not able to display message after submitting form using ajax

I am trying to submit the form using AJAX in CodeIgniter. Values of the form are getting saved in DB but the reply that has been set in the controller is not getting displayed in console.log or alert in AJAX code.
Code of form
<form class="form-signup" id="signup-form" method="post">
<input type="email" class="form-control" placeholder="Email" name="email" id="email">
<input type="password" class="form-control" placeholder="Password" name="password" id="password">
<button type="submit" class="btn btn-primary btn-lg btn-signup col-sm-offset-1" id="submit_form">SIGN UP</button>
</form>
Script code
<script type="text/javascript">
$(document).ready(function() {
$("#submit_form").click(function(event) {
event.preventDefault();
var email = $("input#email").val();
var password = $("input#password").val();
jQuery.ajax({
type: "POST",
url: "<?php echo base_url(); ?>" + "student/register",
dataType: 'json',
data: {email: email, password: password},
success: function(res) {
if (res)
{
console.log(res); //need to print the result here
//alert(res);
}
}
});
});
});
Controller code
public function register()
{
$data = array(
'email' => $this->input->post('email'),
'password'=>$this->input->post('password')
);
$email = $data['email'];
$password = $data['password'];
$this->db->where('email',$email);
$query = $this->db->get('student');
if ($query->num_rows() > 0)
{
echo "Email already exist";
}
else
{
$data1=array(
'email' => $email,
'password' => md5($password)
);
$final=$this->signin_model->register_user($data1);
return $final;
}
}
Model code
public function register_user($data1)
{
$success=$insert_data = $this->db->insert('student', $data1);
if($success)
{
$result= "success ";
}
else
{
$result= "register unsuccessful";
return $result;
}
}
As shown in the code there are 3 messages
Email already exists
Success
Register unsuccessful
In AJAX, if I do console.log or alert, I want any 1 of the above 3 messages to get displayed according to the flow.
How to display the reply on front end?
You have to use echo instead of return for success.
Please change it as follows
if ($query->num_rows() > 0)
{
echo "Email already exist";
}
else
{
$data1=array(
'email' => $email,
'password' => md5($password)
);
$final=$this->signin_model->register_user($data1);
echo $final;
}
and remove that 2 variables initialized together. That is unnecessary. This is fine.
$success = $this->db->insert('student', $data1);
Hope this can help you.
The ajax that you have used has datatype as json. So if you want data to be displayed on front end either encode the reply in json or you need to change or remove the json datatype from your ajax
Please change dataType:'json' to dataType: 'text'
<script type="text/javascript">
$(document).ready(function() {
$("#submit_form").click(function(event) {
event.preventDefault();
var email = $("input#email").val();
var password = $("input#password").val();
jQuery.ajax({
type: "POST",
url: "<?php echo base_url(); ?>" + "student/register",
dataType: 'text',
data: {email: email, password: password},
success: function(res) {
if (res)
{
console.log(res); //need to print the result here
//alert(res);
}
}
});
});
});

Unable to use callback to get response from ajax call

I'm using the jQuery Validator plugin to try to check whether an email address getting entered into the form is unique after an ajax call which passes the email to a script which checks to see if the email is already in the database. I'm using a callback function to try to get the results of the ajax query but the function always returns undefined. I'm not sure what I'm doing wrong. Here is the code:
jQuery.validator.addMethod("unique", function () {
function foo(callback) {
$.ajax({
type: 'POST',
async: true,
url: '/form_processor',
data: 'action=email_validate&email=' + $("#email").val(),
success: callback
});
}
var return_value = foo(function (result) {
if (result !== 'g') {
return false;
} else {
return true;
}
});
alert(return_value);
}, "Email address taken. Choose another.");
If you are using jquery validator, in built method is their to validate, So your validate code will like,
$(document).ready(function(){
$( "#myform" ).validate({
rules: {
email: {
required: true,
email: true,
remote: {
url: "form_processor",
type: "post",
data: {
email: function() {
return $( "#email" ).val();
}
}
}
}
},
messages:
{
email:
{
required: "Please enter your email address.",
remote: "Email already taken"
}
}
});
})
In server side you have to return (print) true or false code will be (if you are using php)
<?php
$email = $_POST['email'];
$query = "SELECT ID FROM users WHERE user_email = "$email" LIMIT 1;";
$results = $mysqli->query($query);
if($results->num_rows == 0)
{
echo "true"; //good to register
}
else
{
echo "false"; //already registered
}
}
else
{
echo "false"; //invalid post var
}
?>

Getting validation error but also form is submitting using ajax and PHP

I have one form and fields are Name, Email, Message.I am inserting data in the database with the help of ajax and I am using Jquery validator for validation. When I clicked on submit button without filled the fields then I am getting the validation error but the form is also submitting. First, It should check the data in the field proper or not. If data is proper then the form will submit otherwise it will display the validation error. Would you help me in this?
HTML
<form name="contact_form" id="form_sub" method="post">
<input type="text" name="name" id="name"><br>
<input type="email" name="email" id="email"><br>
<textarea name="message" id="message"></textarea><br />
<input name="submit" type="submit" value="submit">
<span class="success">Message was Sent</span>
</form>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="js/jquery.validate.min.js"></script>
<script type="text/javascript">
// When the browser is ready...
$(function() {
// Setup form validation on the #register-form element
$("form[name='contact_form']").validate({
// Specify the validation rules
rules: {
name:{ required: true,
minlength:3,
maxlength:30
},
email: {
required: true,
email: true
},
message:{
required: true,
minlength:10,
maxlength:500
}
},
// Specify the validation error messages
messages: {
name:
{
required:"Please enter your name",
minlength:"Please enter min 3 character"
},
email: "Please enter a valid email address",
message: {
required:"Please enter your message",
minlength:"Please enter min 10 character",
maxlength:"Not more then 500 character"
}
},
submitHandler: function(form) {
form.submit();
}
});
});
$(function () {
$('#form_sub').submit('click', function (event) {
event.preventDefault();// using this page stop being refreshing
$.ajax({
type: 'POST',
url: 'demo2.php',
data: $('#form_sub').serialize(),
success: function () {
$('.success').fadeIn(200).show();
}
});
});
});
</script>
PHP
$name=$_POST['name'];
$email=$_POST['email'];
$user_message=$_POST['message'];
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "demo";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO contactus(name, email, message) VALUES ('$name', '$email', '$user_message')";
if ($conn->query($sql) === TRUE) {
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
You need to move your submit function contents into your submit handler:
submitHandler: function ( form ) {
$.ajax( {
type: 'POST',
url: 'demo2.php',
data: $( '#form_sub' ).serialize(),
success: function () {
$( '.success' ).fadeIn( 200 ).show();
}
});
}

ajax call and validate email in php

I'm trying to "transform" a form action into an ajax call.
My form:
<!-- <form method="POST" onSubmit="return doSubmitLogic()" action="action.scripts.php" >
<input type="hidden" name="actiune" value="login" />
<div>
<label> Email </label>
<input type="email" name = "email" id="email" /><span id="emailErr"></span >
</div>
<div>
<label> Password </label>
<input type="password" name = "password" id="password" /> <span id="passErr"></span >
</div>
<div>
<input id ="submitBtn" type="submit" name="button" value="Send"/>
</div>
And what I tried to do with my ajax:
$(document).ready(function(){
$("#submitBtn").click(function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "functions.php",
data: {
Email: $("#email").val(),
Password: $("#password").val(),
},
success: function(result){
alert(result);
},
error: function (error){
alert("Error");
}
});
});
});
Also my piece of code "functions.php" is composed by many checking if the action has a specific value and if so to do something.So:
if ($_POST['actiune']==="login") {
$email = $_POST['email'];
$password = $_POST['password'];
$encript_pass = md5($password);
$query = "select * from user where email='$email' and password='$encript_pass'";
$result = mysql_query($query) or die ("Error in query: $query " . mysql_error());
$row = mysql_fetch_array($result);
if (!filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
echo("$email is a valid email address");
} else {
echo("$email is not a valid email address");
}
}
when I run it it give me an alert saying error. Any syggestions?
Just replace your code with this, notice the "actiune" under the Email & Password
$(document).ready(function(){
$("#submitBtn").click(function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "functions.php",
data: {
Email: $("#email").val(),
Password: $("#password").val(),
actiune: $('input[name="actiune"]').val()
},
success: function(result){
alert(result);
},
error: function (error){
alert("Error");
}
});
});
});
You need to pass actiune with your datas too.
data: {
email: $("#email").val(),
password: $("#password").val(),
actiune: 'login'
},
I also removed the uppercases from the field you pass since you require password and email in your php not Password and Email

Return PHP error when using ajaxForm Jquery Plugin

I'm trying to make a login script that uses ajaxForm and the validate plugin, but if PHP provides an error, it doesn't know. This is my Javascript
$(function login() {
$("#login").validate({ // initialize the plugin
// any other options,
onkeyup: false,
rules: {
email: {
required: true,
email: true
},
password: {
required: true
}
}
});
$('form').ajaxForm({
beforeSend: function() {
return $("#login").valid();
},
success: function() {
window.location="index.php";
},
error: function(e) {
alert(e);
}
});
});
Keep in mind I'm new to JS and there's probably a better way to do this. What I need is, if when the form is submitted but the username or password is wrong, I need it to not redirect, and give the error alert, but this does not work currently. I've googled this before, and checked here and so far have found nothing.
edit: using the below code, it still doesn't work:
JS
$(function login() {
$("#login").validate({ // initialize the plugin
// any other options,
onkeyup: false,
rules: {
email: {
required: true,
email: true
},
password: {
required: true
}
}
});
$("#login").submit(function(e) {
e.preventDefault();
$.ajax({
type : "POST",
dataType : "json",
cache : false,
url : "/doLogin",
data : $(this).serializeArray(),
success : function(result) {
if(result.result == "success"){
window.location = "/index.php";
}else if(result.result == "failure"){
$("#alert").html("Test");
}
},
error : function() {
$("#failure").show();
$(".btn-load").button('reset');
$("#email").focus();
}
});
});
});
HTML
<div class="shadowbar">
<div id="alert"></div>
<form id="login" method="post" action="/doLogin">
<fieldset>
<legend>Log In</legend>
<div class="input-group">
<span class="input-group-addon">E-Mail</span>
<input type="email" class="form-control" name="email" value="" /><br />
</div>
<div class="input-group">
<span class="input-group-addon">Password</span>
<input type="password" class="form-control" name="password" />
</div>
</fieldset>
<input type="submit" class="btn btn-primary" value="Log In" name="submit" />
</form></div>
PHP
public function login() {
global $dbc, $layout;
if(!isset($_SESSION['uid'])){
if(isset($_POST['submit'])){
$username = mysqli_real_escape_string($dbc, trim($_POST['email']));
$password = mysqli_real_escape_string($dbc, trim($_POST['password']));
if(!empty($username) && !empty($password)){
$query = "SELECT uid, email, username, password, hash FROM users WHERE email = '$username' AND password = SHA('$password') AND activated = '1'";
$data = mysqli_query($dbc, $query);
if((mysqli_num_rows($data) === 1)){
$row = mysqli_fetch_array($data);
$_SESSION['uid'] = $row['uid'];
$_SESSION['username'] = $row['username'];
$_SERVER['REMOTE_ADDR'] = isset($_SERVER["HTTP_CF_CONNECTING_IP"]) ? $_SERVER["HTTP_CF_CONNECTING_IP"] : $_SERVER["REMOTE_ADDR"];
$ip = $_SERVER['REMOTE_ADDR'];
$user = $row['uid'];
$query = "UPDATE users SET ip = '$ip' WHERE uid = '$user' ";
mysqli_query($dbc, $query);
setcookie("ID", $row['uid'], time()+3600*24);
setcookie("IP", $ip, time()+3600*24);
setcookie("HASH", $row['hash'], time()+3600*24);
header('Location: /index.php');
exit();
} else {
$error = '<div class="shadowbar">It seems we have run into a problem... Either your username or password are incorrect or you haven\'t activated your account yet.</div>' ;
return $error;
echo "{\"result\":\"failure\"}";
}
} else {
$error = '<div class="shadowbar">You must enter both your username AND password.</div>';
return $error;
$err = "{\"result\":\"failure\"}";
echo json_encode($err);
}
echo "{\"result\":\"success\"}";
}
} else {
echo '{"result":"success"}';
exit();
}
return $error;
}
In your login script, you will need to return errors in json format.
For Example
In your login script, if your query finds a row in the database for that user, echo this:
echo "{\"result\":\"success\"}";
and if it fails:
echo "{\"result\":\"failure\"}";
You then can parse these in JavaScript like so:
$('form').ajaxForm({
beforeSend: function() {
return $("#login").valid();
},
success: function(result) {
if(result.result == "success"){
window.location = "index.php";
}else if(result.result == "failure"){
alert('Failure!');
}
error: function(e) {
alert(e);
}
}
});
Here's an example of an Ajax script I use to log users into my site, you can use this for reference if needed. This is just to help you get an even broader understanding of what I am talking about:
I return more than just a success and failure for various reasons such as user intuitiveness, but the gist is there.
$("#loginForm").bind("submit", function() {
$("#invalid").hide();
$("#disabled").hide();
$("#error").hide();
$("#failure").hide();
$("#blocked").hide();
var email = document.getElementById("email").value;
var password = document.getElementById("password").value;
if(email != "" && password != ""){
$.ajax({
type : "POST",
dataType : "json",
cache : false,
url : "/ajax/functions/login",
data : $(this).serializeArray(),
success : function(result) {
if(result.result == "success"){
window.location = "/account";
}else if(result.result == "failure"){
$("#invalid").show();
$(".btn-load").button('reset');
$("#email").focus();
}else if(result.result == "disabled"){
$("#disabled").show();
$(".btn-load").button('reset');
$("#email").focus();
}else if(result.result == "blocked"){
$("#blocked").show();
$(".btn-load").button('reset');
$("#email").focus();
}
},
error : function() {
$("#failure").show();
$(".btn-load").button('reset');
$("#email").focus();
}
});
}else{
$("#error").show();
$(".btn-load").button('reset');
$("#email").focus();
}
return false;
});

Categories