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
}
?>
Related
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.
How can I make this form redirect the user to an external site, for example http://amaze.bg, after the user submits the form with the "Register" button and after the form sends the e-mail to antoniya.p#amaze.bg with the entered by the user details?
Here is the PHP code (contact_process.php):
<?php
usleep(500000);
$to = "antoniya.p#amaze.bg";
$author = "";
$email = "";
$comment = "";
$class = "FORM CONTACT ";
if (isset($_POST['input_name']))
$author = $_POST['input_name'];
if (isset($_POST['input_email']))
$email = $_POST['input_email'];
if (isset($_POST['input_class']))
$class = $_POST['input_class'];
if (isset($_POST['input_message']))
$comment = $_POST['input_message'];
$sub="Alumni registration recieved - ".$date1;
$name=$authorlast."< ".$email." >";
$msg = '';
if (#mail($to,$sub,$body,"Content-Type: text/html; charset=iso-8859-1"))
{
$msg = 'Your registration was sent successfully';
//echo '<div class="alert success pngfix">'. $msg .'</div>';
}
else{
$msg = 'Email failed to be sent (mail function not work)';
//echo '<div class="alert error pngfix">'. $msg .'</div>';
}
echo $msg;
?>
And here is the .js part:
jQuery.validator.addMethod(
"math",
function(value, element, params) {
if (value==='')
return false;
return this.optional(element) || value == params[0] + params[1];
},
jQuery.format("Please enter the correct value for {0} + {1}")
);
$('.form-register').validate({
rules: {
input_name: {
minlength: 3,
required: true
},
input_email: {
required: true,
email: true
},
input_message: {
minlength: 0,
required: false
}
,
submitHandler: function(form) {
var a=$('.form-register').serialize();
$.ajax({
type: "POST",
url: "contact_process.php",
data:a,
complete:function(){
},
beforeSend: function() {
},
success: function(data){
if (data=='success') {
$('.form-register').find("input[type=text], textarea").val("");
alert('You have successfully registered. Thank you for being active alumni!');
} else {
alert(data);
}
},
error : function() {
}
});
return false;
}
});
});
Thank you for the help.
After some experiments and help from Charlie I managed to find where and what exactly to add to the code, so that the form sends the information to the server and them redirects the user to another website. The change should be made in the .js file with the addition of the following line:
location = "http://amaze.bg/"
But it should be added under "else" in the .js file, with the "alert" being under "success" for everything to work properly:
success: function(data){
if (data=='success') {
alert(data);
} else {
location = "http://amaze.bg/"
}
},
error : function() {
}
In Your Success Callback, Add location = "http://amaze.bg"
success: function(data) {
// if you echo "success" in your php script when the mail is sent
if (data === 'success') {
$('.form-register').find("input[type=text], textarea").val("");
alert('You have successfully registered. Thank you for being active alumni!');
// Now redirect
location = "http://amaze.bg"
} else {
// if you echo "Some Error Message" from your php script
alert(data);
}
},
Ultimately, You should be sending the proper headers from php so that the success hook in your $.ajax fires on a 200 Status Code and the error hook fires in your $.ajax when a 400 - 500 Status Code is encountered. Please look into HTTP Status Codes and Sending Proper Headers in PHP
I am using the validation plugin and Laravel 4.2.
I try to check the username via ajax, but I can't get it work.
The username can always be taken, doesn't matter if exists or not.
My second issue is if I am using the validation rule remote, I can't submit the form.
Does anybody know what I am doing wrong? Because in the chrome log all is fine, the request is sent and I can see the debug messages.
Php
<?php
use App\Models\User;
class ValidationController extends BaseController {
public function getCheckUsername()
{
if(Request::ajax()) {
$user = User::where('username', Input::get('username'))->get();
if($user->count()) {
return Response::json(array('msg' => 'true'));
}
return Response::json(array('msg' => 'false'));
}
}
}
JS
$(document).ready(function()
{
$("form").validate({
rules: {
username: {
required: true,
rangelength:[3,255],
remote: {
url:"http://"+location.host+"/validation/checkusername",
type: "get",
success: function(msg){
if(msg.msg == 'true') {
console.log('exists');
return true;
}
console.log('doesnt exists');
return false;
}
},
},
messages: {
username: {
required: "Please Enter Username!",
remote: "Username already in use!"
}
}
});
});
I also tried to create an own rule via $.validator.addMethod(), but this doens't work either.
It doesn't look like you are sending the data. Try this. Note the post request. Also I believe the dataFilter method should return 'true'.
Update I just also realized the logic in your php is sending back true if the user exists, therefore the logic in the javascript should be like so:
remote: {
url: "http://"+location.host+"/validation/checkusername",
type: "post",
data: {
username: function () {
return $("input[name='username']").val();
}
},
dataFilter: function (data) {
var json = JSON.parse(data);
if (json.msg == "true") {
return "\"" + "That username is taken" + "\"";
} else {
return 'true';
}
}
}
I have this function:
$(function() {
$("#loginform").submit(function(e) {
e.preventDefault();
}).validate({
rules: {
username: {
required: true,
email: true,
},
password: {
required: true,
}
},
// Specify the validation error messages
messages: {
username: {
required: "please, enter your email",
email: "This is not a valid email!",
},
password: {
required: "please, enter your password",
}
},
submitHandler: function(form) {
$("#loginform").append('<div style="width:40%; margin: 20px auto;"class="loggingIn"><h4 style-"color:#ffffff; text-align:center;">Logging in ...</h4></div>');
$("#loginform").append('<div class="spinningWheel" style="width:100%; text-align:center;"><img src="/images/ajaxspinner.gif" / width="50px;"></div>');
$(".redFormButton").hide();
var username = $('input[id=username]').val();
var password = $('input[id=password]').val();
var token = $('input[id=token]').val();
$.ajax({
url: '/processLogin.php',
type: 'post',
dataType: 'json',
data: {'username': username , 'password':password, 'token':token},
success: function(data) {
if (data == true) {
$(".loggingIn").remove();
$(".spinningWheel").remove();
window.location.replace("index.php");
} else {
$(".loggingIn").remove();
$(".spinningWheel").remove();
$(".redFormButton").show();
$("#loginform").append('<div style="width:80%; margin: 0 auto;"class="loggingError"><h4 style="color:red; text-align:center;">the username or password is wrong. Please Check Again. </h4></div>');
}
},
}); // end ajax call
return false; //This doesn't prevent the form from submitting.
}
});
});
this works perfectly either when the user use the correct credentials or when they are wrong but if the user click again login leaving the wrong username and password, the "spinning wheel" keep turning without going any further.
processLogin.php, the first time (when the data are wrong) return false but the second time it doesn't return anything:
<?php
require 'core/init.php';
if ($_POST) {
$username = filter_var($_POST['username'], FILTER_SANITIZE_EMAIL);
$password = filter_var($_POST['password'], FILTER_SANITIZE_STRING);
$token = filter_var($_POST['token'], FILTER_SANITIZE_STRING);
if (Token::check($token)) {
$user = new User();
$remember = true; //this is intentional as it wasn't working
$login = $user->login($username, $password, $remember);
if ($login) {
$result = true;
echo json_encode($result);
} else {
$result = false;
echo json_encode($result);
}
}
} else {
Redirect::to('index.php');
}
*******UPDATE***************
the problem is given from Token::check($token). The second times that the script run for some reason it return false. If I remove that it always works.
<?php require 'core/init.php';
if($_POST){
$username = filter_var($_POST['username'], FILTER_SANITIZE_EMAIL);
$password = filter_var($_POST['password'], FILTER_SANITIZE_STRING);
//$token = filter_var($_POST['token'], FILTER_SANITIZE_STRING);
$user = new User();
$remember = true;
$login = $user->login($username, $password, $remember);
if($login) {
echo 'true';
} //if true login
else{
echo 'false';
}
}
Token Class is:
<?php
class Token {
public static function generate() {
return Session::put('token', md5(uniqid()));
}
public static function check($token) {
$tokenName = Config::get('session/token_name');
if(Session::exists($tokenName) && $token === Session::get($tokenName)) {
Session::delete($tokenName);
return true;
}
return false;
}
}
any idea how I can keep using Token?
try this trick
at this line change
var username = $('input[id=username]').val();
var password = $('input[id=password]').val();
var token = $('input[id=token]').val();
$.ajax({
url: '/processLogin.php',
To
var makhash = (new Date).getTime();
var username = $('input[id=username]').val();
var password = $('input[id=password]').val();
var token = $('input[id=token]').val();
$.ajax({
cache: false,
url: '/processLogin.php?hashcode='+makhash,
I have a problem with my ajax loader in CI.
This is what I have tried so far:
<script type="application/javascript">
$(document).ready(function() {
$('#submit').click(function() {
var form_data = {
username : $('.username').val(),
password : $('.password').val(),
};
var loader = $('<img/>', {
'src':'assets/img/ajax-loader.gif',
'id':'message'
});
loader.insertAfter($(this));
//.removeClass().addClass('loader').html('<img src="assets/img/ajax-loader.gif">').fadeIn(1000);
$.ajax({ //
url: "<?php echo site_url('login/ajax_check'); ?>",
type: 'POST',
async : false,
data: form_data,
success: function(msg) {
$('#ajax_loader').remove();
$('#message').html(msg);
}
});
return false;
});
});
</script>
c_login.php controller
function ajax_check() {
//if($this->input->post('ajax') == '1') {
if($this->input->is_ajax_request()){
$this->form_validation->set_rules('username', 'username', 'trim|required|xss_clean');
$this->form_validation->set_rules('password', 'password', 'trim|required|xss_clean');
$this->form_validation->set_message('required', 'Please fill in the fields');
if($this->form_validation->run() == FALSE) {
echo validation_errors();
} else {
$this->load->model('m_access');
$user = $this->m_access->check_user($this->input->post('username'),$this->input->post('password'));
if($user) {
echo 'login successful';
//echo '<img src="assets/img/loader-bar.gif"> Hello!';
//$this->load->view('welcome');
} else {
echo 'unknown user'; //
//echo ' <img src="assets/img/icon_error.gif"> Username or password not valid';
}
}
}
}
UPDATE:
The problem is, it's just displaying the loader infinitely.
What I want to do is, if the user is valid, will show the loader.gif and then redirect to main page else will display the username or password incorrect. What is wrong with my code? Any ideas? Thanks.
It seems that you named your loader as "message" instead of creating a "message" new element and name your loader as "ajax_loader".
var loader = $('<img/>', {
'src':'assets/img/ajax-loader.gif',
'id':'ajax_loader'
});
var message = ...
...
'id':'message'
.
success: function(msg) {
$('#ajax_loader').remove();
$('#message').html(msg);
}