Hy I'm trying to validate the email address in a registration form. I want to check if the address exists in the database;
i have the following function:
function validateEmailRepeat(){
// check if email exists in the database;
var emailVal = $('#email').val();
// assuming this is a input text field
$.post('check_email.php', {'email' : emailVal}, function(data) {
if(data==1)
{
email.addClass("error");
emailInfo.text("Adress exists");
emailInfo.addClass("error");
dataExist=1;
}
else {
email.removeClass("error");
emailInfo.text("Valid adress");
emailInfo.removeClass("error");
dataExist=0;
}
});
if(dataExist==1)
return false;
else
return true;
}
the check_email.php looks like this:
require_once('db.php');
if (isset($_POST['email'])){
$email=mysqli_real_escape_string($con,$_POST['email']);
$sql = "SELECT * FROM users WHERE `username`='".$email."'";
$select=mysqli_query($con,$sql) or die("fail");
$row = mysqli_num_rows($select);
if ($row >0) {
echo 1;
}else echo 0 ;
}
else
echo "post error";
i'm new at this . So don't be to tough. thanks in advance.
LE:Sorry ! i forgot the question...
the problem is that my function returns true if I define var dataExist outside of the function form $.post
and if i let it like it is now in the function I get "dataExist is not defined " error and returns true
Le: the PHP returns the expected 1 and 0 just the way i wanted..
LE:
seems like defining the
var dataExist=0;
outside the function validateEmailRepeat() resolved the issue.
if there's another way more elegant please tell me because this seems a little stupid to me.
The problem is you cannot return the value into the called function, because ajax work asynchronously.
function validateEmailRepeat(){
// check if email exists in the database;
var emailVal = $('#email').val();
// assuming this is a input text field
$.post('check_email.php', {'email' : emailVal}, function(data) {
if(data==1){
email.addClass("error");
emailInfo.text("Adress exists");
emailInfo.addClass("error");
dataExist=1;
}else{
email.removeClass("error");
emailInfo.text("Valid adress");
emailInfo.removeClass("error");
dataExist=0;
}
$('#some_input').val(dataExist);
validateUserName();
});
}
function validateUserName() {
var input = $('#some_input').val();
if (input) {
alert("This username is already taken");// whatever
} else {
// whatever
}
};
You are comparing the username with the email address. Is this how your DB works?
$sql = "SELECT * FROM users WHERE username='".$email."'";
I bet you have a field in your database for the email itself, otherwise i suggest you do this. The query should look like this:
$sql = "SELECT * FROM users WHERE email = '".$email."'";
Without the single quotes for the column.
Related
I have the following username lookup function that checks if the username is available.
<script language="javascript">
function lookUpUsername(){
var name = document.getElementById('username').value;
//alert(name);
$.post(
'users/ajax_lookUpUsername',
{ username: name },
function(response) {
if (response == 1) {
// alert('username available');
} else {
// setTimeout("alert("Here I am!")", 5000);
alert('Username Already Taken! Please Select Another Name.');
}
});
}
</script>
And here is my AJAX_lookUpUsername function in the controller:
function ajax_lookUpUsername(){
$username = $this->input->post('username');
$this->db->where('username', $username);
$query = $this->db->get('mcb_users');
if ($query->num_rows() > 0){
echo 0;
} else {
echo 1;
}
The code works fine. When a user enters an existing username, it displays an alert message, but, when a user continues without modifying it and clicks on the save button, it gets saved!
Is there any way to redirect the user before saving to the database from the controller?
You can do this by using onsubmit form validation also. But, there is another approach too.
You can do this through controller also. Add the following code in save function of your controller, just before inserting data to database:
$userarraydb = $this->mdl_users->getAllusername();
foreach($userarraydb as $dbusersname)
{
if(($dbusersname->text == $username) && ($dbusersname->id != $user_id) )
{
//echo $this->lang->line('user_name_must_be_unique');
//sleep(1);
?> <script> alert('Record can not be saved! Username must be unique.'); </script> <?php
return false;
}
}
and add following function to your user model:
function getAllusername()
{
$teller_id = $this->session->userdata('user_id');
$this->db->select('username as text, id as id');
$this->db->from('mcb_users');
$result = $this->db->get();
$username = $result->result();
//all user name taneko cha
return $username;
// return $result->result();
}
I am having a problem setting a value to a variable. My code is as below.
function fpform(){
var response_new = '';
var password_reset = "";
var fpemail = $('#frgtpwd').val();
//var fpemail = document.getElementById('frgtpwd').value;
if (fpemail == ""){
$('span#fperror').text("insert your emal address");
//document.getElementById('fperror').innerHTML = "Insert your email address";
password_reset = 'no';
} else {
var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (filter.test(fpemail)==false) {
$('span#fperror').text("Email address is not in valid format");
//document.getElementById('fperror').innerHTML = "Email address is not in valid format";
password_reset = 'no';
} else {
$("#loader").html('<img src="images/ajax-loader.gif" />');
$.post("forgot_password_process.php", {
email:fpemail
}, function(response){
response_new = response.trim();
}).success(function () {
if (response_new == 'yes'){
$("#fperror").html('<font color="green"><b>Your password has been reset now and emailed to you </b></font>');
$("#loader").empty();
password_reset = 'yes';
} else {
$("#loader").empty();
$("#fperror").html('<font color="black"><b> Email address was not found in database!</b></font>');
password_reset = 'no';
}
});
}
}
if (password_reset == "yes"){
alert(password_reset);
return true;
} else {
alert(password_reset);
return true;
}
}
The last if condition is checking if the password_reset variable is set to yes or not and returns true or false depending on that. But the alert displays blank value of the password_reset variable. I can't seem to find a problem behind this as the password_reset variable should get assigned before reaching the last if. can anyone please suggest a solution.
Kind Regards
$.post() is asynchronous, therefor the request hasn't completed when you alert the data. For this to work, you need to call the alert within the success-callback as well, to make sure that you have the data before you try to alert it. Another option would be to use a synchronous AJAX-call (this is rarely a good option though).
Update
Not sure why your function return true/false, but for that to work, you would have to make a synchronous AJAX-call, otherwise the outer function will return long before the AJAX-call completes, and at that point you don't know what the response is.
You should probably try to restructure your code to make the code that depend on the response of your outer function callable by the success-callback instead.
I was gonna post the same thing as as Christofer. Here's a fixed code sample. Just remove the last code block too.
.success(function () {
if (response_new == 'yes'){
$("#fperror").html('<font color="green"><b>Your password has been reset now and emailed to you </b></font>');
$("#loader").empty();
password_reset = 'yes';
alert 'yes';
return true;
} else {
$("#loader").empty();
$("#fperror").html('<font color="black"><b> Email address was not found in database!</b></font>');
password_reset = 'no';
alert 'no';
return false;
}
Alright so I have this function
<?php
/**
* #author Mitchell A. Murphy
* #copyright 2011
*/
include ('func_lib.php');
connect();
echo (check($_POST['input']) ? 'true' : 'false');
function check($args)
{
$args = strtolower($args);
$checkemail = "/^[a-z0-9]+([_\\.-][a-z0-9]+)*#([a-z0-9]+([\.-][a-z0-9]+)*)+\\.[a-z]{2,}$/i";
if (preg_match($checkemail, $args))
{
//logic for email argument
$sql = "SELECT * FROM `users` WHERE `email`='" . $args . "'";
$res = mysql_query($sql) or die(mysql_error());
echo "type=email:";
if (mysql_num_rows($res) > 0)
{
return true;
} else
{
return false;
}
} else
{
//logic for username argument
$sql = "SELECT * FROM `users` WHERE `username`='" . $args . "'";
$res = mysql_query($sql) or die(mysql_error());
echo "type=username:";
if (mysql_num_rows($res) > 0)
{
return true;
} else
{
return false;
}
}
}
?>
The function should be accessed by this jquery script:
$('form.register .submit').click(validateRegister);
function validateRegister() {
//Variables
var emailExists = false;
var userExists = false;
var $error = "";
//Executes functions
email();
function email() {
var $error = $('#email .error');
var input = $('#email input').val();
var emailRE = /^.*#.+\..{2,5}$/;
if (input.match(emailRE)) {
$error
.html('<div>Proper Email Format: <span>Hello#Yoursite.com</span></div>')
.animate({
'left': '-130px',
'opacity': '0'
});
//Checks for Existing Email
function checkExisting_email() {
$.ajax({
type: 'POST',
url: 'includes/checkExist.php',
data: input,
statusCode: {
404: function () {
alert('page not found');
}
},
success: function (data) {
alert(data);
},
error: function () {
alert("error bro");
}
});
}
emailExists = checkExisting_email();
//If it exists
if (emailExists) {
alert("This email already exists!");
} else if (emailExists == false) {
alert("Email doesnt exist!");
}
} else {
//Email doesn't match
$error
.html('<div>Proper Email Format: <span>Hello#Yoursite.com</span></div>')
.animate({
'left': '-150px',
'opacity': '1'
});
}
}
return false;
}
But for some reason the script (js) isn't sending any data? if so, how do i reference it. I am the backend developer but the designer who did the javascript left me to fix this. I know the php works because I made a test form to send the data with this html markup:
<form action="includes/checkExist.php" method="post">
<input type="text" name="input" />
<input type="submit" name="submit" />
</form>
And that works...so why is the input from jquery returning as NULL?
See that checkExisting_email() don't return anything, so emailExists = checkExisting_email(); will not set emailExists. This data will only be provided on the callback function, which today only display the result on an alert().
To make things easier, use jQuery ajax validation field remote. Check the documentation and sample.
You need to pass in a key/value pair for the "data", not just the value.
As is, your form is going to be posted with a querystring looking like this:
target.php?asdf#hotmail.com
it should be:
data: { input: input },
This will set the querystring to look like:
target.php?input=asdf#hotmail.com
Also, since you are getting the value out of an element by ID, you dont need to specify the input tag.
var input = $('#email').val();
I'm having troubles using ajax and php. What I'm trying to do is call an ajax function that grabs a value from an form's input, and checks if that email exists in a database. Here is my current javascript:
//Checks for Existing Email
function checkExisting_email() {
$.ajax({
type: 'POST',
url: 'checkExist.php',
data: input
});
emailExists = checkExisting_email();
//If it exists
if (emailExists) {
alert("This email already exists!");
}
Unfortunately, I can't get my alert to go off. In my PHP function, it checks whether the input is a username or an email (just for my purposes, and so you know), and then it looks for it in either column. If it finds it, it returns true, and if not, it returns false:
include ('func_lib.php');
connect();
check($_POST['input']);
function check($args)
{
$checkemail = "/^[a-z0-9]+([_\\.-][a-z0-9]+)*#([a-z0-9]+([\.-][a-z0-9]+)*)+\\.[a-z]{2,}$/i";
if (!preg_match($checkemail, $args)) {
//logic for username argument
$sql = "SELECT * FROM `users` WHERE `username`='" . $args . "'";
$res = mysql_query($sql) or die(mysql_error());
if (mysql_num_rows($res) > 0) {
return true;
} else {
return false;
}
} else {
//logic for email argument
$sql = "SELECT * FROM `users` WHERE `email`='" . $args . "'";
$res = mysql_query($sql) or die(mysql_error());
if (mysql_num_rows($res) > 0) {
return true;
} else {
return false;
}
}
}
SO my issue is, how does ajax respond to these returns, and how do I make ajax function accordingly? Mainly, why doesn't this work?
Any help is very much appreciated. Thank you!
You need to add the success option to your Ajax request, which is the JS function which gets executed when the XHR succeeds. Have a look at the jQuery documentation for more info.
Without running the script, I think you'll find that $_POST['input'] is empty; you need to pass your data as something like data: {'input': input} to do that.
Your PHP also needs to return some content to the script; consider changing your call to check() to something like this:
echo (check($_POST) ? 'true' : 'false');
You can now check the content in JavaScript.
Basically ajax is a hand-shaking routine with your server.
Ajax:
$.post('yoursite.com/pagewithfunction.php',
{postkey1:postvalue1, postkey2:postvalue2...},
function (response) {
// response is the data echo'd by your server
}, 'json'
);
pagewithfunction:
yourFunction(){
$var1 = $_POST['postkey1'];....
$result = dosomething($var1..);
echo json_encode($result); // this is passed into your function(response) of ajax call
}
So in $.post you have the url of the php page with the function, { var:val } is the post data, and function(response) is where you handle the data that is echo'd from your server -- the variable, response, is the content that is echo'd.
i have a login box...
when the user starts typing.. i want to check whether the LOGIN NAME entered exists in the database or not...
if the login name is exist i am going to set the login button active... if it doesnot exist i am going to set the login button deactive...
offcourse i am going to need AJAX to perform my mySQL via PHP tough i don't know how it will be done...
lets say this is my query
<?php
$result = mysql_query("SELECT * FROM accounts WHERE name='mytextboxvalue'");
?>
how to do it
keep it simple:
$(document).ready(function(){
var Form = $('#myForm');
var Input = $('input.username',Form)
Input.change(function(event){
Value = Input.val();
if(Value.length > 5)
{
$.getJSON('/path/to/username_check.php',{username:Value},function(response){
if(response.valid == true)
{
Form.find('input[type*=submit]').attr('disabled','false');
}else
{
Form.find('input[type*=submit]').attr('disabled','true');
}
});
}
});
});
and then PHP side..
<?php
//Load DB Connections etc.
if(!empty($_REQUEST['username']))
{
$username = mysql_real_escape_string($_REQUEST['username']);
if(isset($_SESSION['username_tmp'][$username]))
{
echo json_encode(array('valid' => (bool)$_SESSION['username_tmp'][$username]));
die();
}
//Check the database here... $num_rows being a validation var from mysql_result
$_SESSION['username_tmp'][$username] = ($num_rows == 0) ? true : false;
echo json_encode(array('valid' => (bool)$_SESSION['username_tmp'][$username]));
die();
}
?>
You can use JSON-RPC, here is implementation in php.
and in JQuery you can use this code.
var id = 1;
function check_login(){
var request = JSON.stringify({'jsonrpc': '2.0',
'method': 'login_check',
'params': [$('#login_box').val()],
'id': id++});
$.ajax({url: "json_rpc.php",
data: request,
success: function(data) {
if (data) {
$('#login_button').removeAttr('disabled');
} else {
$('#login_button').attr('disabled', true);
}
},
contentType: 'application/json',
dataType: 'json',
type:"POST"});
}
and in php
<?php
include 'jsonRPCServer.php';
//mysql_connect
//mysql_select_db
class Service {
public function login_check($login) {
$login = mysql_real_escape_string($login);
$id = mysql_query("SELECT * FROM accounts WHERE name='$login'");
return mysql_num_rows($id) != 0;
}
}
$service = new Service();
jsonRPCServer::handle($service);
?>
Look at jQuery AJAX and jQuery TypeWatch
But like #halfdan said, this is a potential security risk. I have never seen a site do this with a username, only with search results.
Your potentially giving away an end point (URL) on your web site which anyone could query to find out if a username is valid. Intranet or not, it is a risk.