How to check if email exists - php

I'm trying to get an error that says that the email exists already and I'm trying to use jquery. I'm using ajax and it does work, because when I use firebug and I go to the console it says that the email address exists but I would like that to appear on the page.
index.php
<div class="register-newsletter">
<form id="myForm">
<input type="email" name="email" id="email" value="enter email address" required>
<input type="image" value="SUBMIT" id="sub" src="images/register.jpg">
</form>
<a class="newsletter" href="javascript:void(0);">Add to e-mailing list</a>
This is my jquery
$("#email").click(function(){
if($.trim($(this).val() ) == "enter email address"){
$(this).val("");
}
})
$("#email").blur(function(){
if($.trim($(this).val() ) == ""){
$(this).val("enter email address");
}
})
$("#sub").click(function () {
var email = $.trim($("#email").val());
if(email == "" || !isValidEmailAddress(email)){
alert('enter valid email');
return false;
}
var ajaxid = ajax("ajax/userInfo.php","email="+encodeURIComponent(email));
$("#result").html($.trim(ajaxid));
});
$("#myForm").submit(function () {
return false;
});
function clearInput() {
$("#myForm :input").val('');
}
$('p').hide();
$('#myForm').hide();
$(".newsletter").click(function(){
$(".newsletter").hide();
$('#myForm').show();
});
$('#myForm').submit(function(){
$('#myForm').hide();
$('p').show();
});
and this is my userInfo.php
<?php
include("../config.php");
global $_NEWSLETTER_CUSTOMERS_TABLE;
$email = $_POST['email'];
//$email = html_entity_decode(str_replace("'", "\'", $_POST["email"]));
$query = mysql_query("SELECT * FROM $_NEWSLETTER_CUSTOMERS_TABLE WHERE `email` = '".$email."'");
if(mysql_num_rows($query) >0){
echo '<span class="exists">Email address arleady exists</span>';
} else {
if(mysql_query("INSERT INTO $_NEWSLETTER_CUSTOMERS_TABLE(email) VALUES('$email')"))
echo "Successfully Inserted";
else
echo "Insertion Failed";
}

You are attempting to append the data incorrectly. jQuery's ajax() method takes a function that will be called upon the success of the request, called success. At the moment, you are trying to append ajaxid, (which contains ajax()s return value, not the result of the request) to #result.
var ajaxid = ajax("ajax/userInfo.php","email="+encodeURIComponent(email));
$("#result").html($.trim(ajaxid));
Should be more like:
var ajaxid = ajax("ajax/userInfo.php", {
data:"email="+encodeURIComponent(email),
success:function(d){
$("#result").html($.trim(d));
}
});

Use jQuery.post() inside your click handler:
$.post('ajax/userInfo.php', { email: email }, function(data) {
alert(data.message);
}, 'json');
And in your PHP file instead of echo use:
$response = array();
$response['message'] = mysql_query("...") ? 'success' : 'fail';
return json_encode($response);

You must return the value, eg JSON
Your JS
$("#sub").click(function () {
$.ajax({
url : "ajax/userInfo.php",
dataType : "json",
error : function(request, error) {
alert("Erreur : responseText: "+request.responseText);
},
success : function(data) {
alert(data.email_exist);
$("#result").html(data.email_exist);
}
});
});
AND your PHP
if(mysql_num_rows($query) >0){
$result = array(
'email_exist' => 'Email address arleady exists'
);
}
json_encode($result);

Related

How to redirect user on successful ajax call? Otherwise display error message in form

Updated:
Thanks for reading - My login form calls on login.php to check whether the user has entered a registered email address or not. If the address is registered, it echoes back "redirect", if it is not registered, it echoes "Email not registered". My current code only redirects to mydomain.com/# since the form action is set to #, because I'm using the ajax to submit the form.
How do I:
Redirect the user to page private.php if the php has echoed "redirect" - otherwise how do I display "Email not registered" within the form, if it echoes "Email not registered"? My login form contains a div to display the error if necessary.
ajax:
<script>
$(document).ready(function() {
$("#loginform").submit(function(e){
e.preventDefault();
$.post('login/login.php', {email: $('#email').val(), loginsubmit: 'yes'}, function(data)
{
if (data === "redirect")
{
window.location = "http://www.gathercat.com/login/private.php";
}
else {
$("#formResponse").html(data).fadeIn('100');
$('#email').val('');
}
, 'text');
return false;
}
});
});
</script>
PHP:
...
if($login_ok)
{
echo 'redirect';
}
else
{
echo 'That email address is not registered';
}
...
login form:
...
<form id="loginform" name="loginform" method="POST" class="login" action="#">
<input name="email" id="email" type="email" class="feedback-input" placeholder="My Email" required/>
<div id="formResponse" style="display: none;"></div>
<button type="submit" name="loginsubmit" class="loginbutton">Login</button>
...
Full PHP
<?php
$emailaddress = $_POST["email"];
?>
<?php
// First we execute our common code to connection to the database and start the session
require("common.php");
// This if statement checks to determine whether the login form has been submitted
// If it has, then the login code is run, otherwise the form is displayed
if(!empty($_POST))
{
// This query retrieves the user's information from the database using
// their email.
$query = "
SELECT
email
FROM users
WHERE
email = :email
";
// The parameter values
$query_params = array(
':email' => $emailaddress
);
try
{
// Execute the query against the database
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex)
{
die("Failed to run query");
}
// This variable tells us whether the user has successfully logged in or not.
// We initialize it to false, assuming they have not.
// If we determine that they have entered the right details, then we switch it to true.
$login_ok = false;
// Retrieve the user data from the database. If $row is false, then the email
// they entered is not registered.
$row = $stmt->fetch();
if($row) {
$login_ok = true;
}
// If the user logged in successfully, then we send them to the private members-only page
// Otherwise, we display a login failed message and show the login form again
if($login_ok)
{
// This stores the user's data into the session at the index 'user'.
// We will check this index on the private members-only page to determine whether
// or not the user is logged in. We can also use it to retrieve
// the user's details.
$_SESSION['user'] = $row;
// Redirect the user to the private members-only page.
echo 'redirect';
}
else
{
// Tell the user they failed
echo 'That email address is not registered';
}
}
?>
I've rewritten the code for you as it likes like you had quite a few problems.
$(document).ready(function() {
$("#loginform").submit(function(e){
e.preventDefault();
jQuery.ajax({
type: "POST",
url: "login/login.php",
dataType:"text",
data: { email: $('#email').val(), loginsubmit: 'yes' },
success:function(response){
if(response == "redirect"){
window.location.replace("http://www.gathercat.com/login/private.php");
}
else{
$("#formResponse").html(response).fadeIn('100');
$('#email').val('');
}
}
})
});
});
This is untested but please let me know if you have any questions about how it works.
if ( formResponse === "redirect" ) ...
what is formResponse variable?
it should be data
if ( data == "redirect" ) ...
UPDATE:
may be this will help
$(document).ready(function () {
$("#loginform").submit(function (e) {
e.preventDefault();
$.post('login/login.php', {
email: $('#email').val(),
loginsubmit: 'yes'
}, function (data) {
if (data === "redirect") {
window.location = "http://www.gathercat.com/login/private.php";
} else {
$("#formResponse").html(data).fadeIn('100');
$('#email').val('');
}}, 'text');
// this does not matter
return false;
}
// add line below
return false;
});
});
Ok, I solved it!
I changed my ajax to:
<script>
$(document).ready(function() {
$("#loginform").submit(function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "login/login.php",
dataType:"text",
data: {email: $('#emailaddy').val(), loginsubmit: 'yes'},
success:function(result){
if(result === "redirect"){
// window.location.replace("login/private.php");
window.location.replace("http://www.gathercat.com/login/private.php");
//alert(result);
}
else{
$("#formResponse").html(result).fadeIn('100');
$('#emailaddy').val('');
}
}
})
});
});
</script>
and removed some commented-out HTML within the bottom of my php file which was disrupting the "result" variable's content. Everything runs perfectly now. I added this answer so people could see the full code easily, but I'm giving massive credit to paddyfields for their help, thank you again. You too Lee, appreciate the support. Take care

jQuery Validation - prevent submit on remote

I need to prevent form from submitting when remote call returns true as result. How can I do this?
The JS code:
var userForm = $('#user-form');
userForm.validate({
rules : {
email : {
email: true,
remote: {
url: userForm.find('#uniqueUrl').val() + '/isUniqueEmail',
type: 'POST',
data: function(){
return $('#email').val()
},
complete: function(data){
if(data.responseText.trim() == 'true'){
return false;
}
}
}
}
}
});
Server side:
public function isUniqueEmail()
{
$result = $this->users->isUniqueEmail($this->input->post('email'));
if($result):
echo false;
else:
echo true;
endif;
}
Quote OP:
"I need to prevent form from submitting when remote call returns true as result."
That's backwards. You would return false to block the submit and trigger the validation message.
You don't need the data option since the plugin sends the field value by default. You also don't need the complete option as the plugin captures the server response automatically.
JavaScript:
var userForm = $('#user-form');
userForm.validate({
rules: {
email: {
email: true,
remote: {
url: userForm.find('#uniqueUrl').val() + '/isUniqueEmail',
type: 'POST' // default is GET
}
}
}
});
Server-side:
public function isUniqueEmail()
{
$result = $this->users->isUniqueEmail($this->input->post('email'));
if($result):
// setting message in PHP allows you to dynamically have any message
echo json_encode('name is already taken');
else:
echo true;
endif;
}
ALTERNATE
(Custom error message set in JavaScript)
JavaScript:
var userForm = $('#user-form');
userForm.validate({
rules: {
email: {
email: true,
remote: {
url: userForm.find('#uniqueUrl').val() + '/isUniqueEmail',
type: 'POST' // default is GET
}
}
},
messages: {
email: {
remote: "name is already taken"
}
}
});
Server-side:
public function isUniqueEmail()
{
$result = $this->users->isUniqueEmail($this->input->post('email'));
if($result):
echo false;
else:
echo true;
endif;
}
DOCUMENTATION: http://jqueryvalidation.org/remote-method/

insert form values with database lookup without refreshing the page

I have a form with 5 fields.
Name
Last Name
Date of Birth
Occupation
Place of Birth
When user fills name and last name, I want the rest of the form to be filled from database without refreshing the page or user doing anything.
I am using php and jquery.
Here is my html page:
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
<input type="text" name="name" id="name">
<input type="text" name="lastname" id="lastname">
<input type="text" name="occupation" id="occupation">
<input type="text" name="date_of_birth" id="date_of_birth">
<input type="text" name="place_of_birth" id="place_of_birth">
<script type="text/javascript">
$('#lastname').blur(function ()
{
var name = $("#name").val();
var lastname = $("#lastname").val();
$.ajax({
url: "get.php",
type: "POST",
data: "name="+name+"&lastname="+lastname,
success: function(data)
{
if (data == "Error")
{
alert("error-1"+data);
}
else
{
var fields = data.split(",");
if (fields.length < 3)
{
alert("error-2"+data);
}
else
{
$("#occupation").val(fields[0]);
$("#date_of_birth").val(fields[1]);
$("#place_of_birth").val(fields[2]);
}
}
},
error: function(xhr, status, error)
{
alert("error-3"+data);
}
});
});
</script>
</body>
</html>
Here is the php page:
<?php
$name= $_REQUEST['name'];
$lastname= $_REQUEST['lastname'];
if($name == "mike" && $lastname = "brown")
{
echo "cook,1980-10-10,NYC";
}
?>
It works now.
-- Edit #1
Maybe this example can help you to understand how to use it:
$.ajax({
url: "phppage.php",
type: "POST", // Or get as you like
data: "name="+name+"&lastname="+lastname,
success: function(data)
{
// As i said, here in "data" you have what the server returned
// You can return the last field delimited with a , and do something like:
if (data == "Error")
{
// If something went wrong in your Database or invalid "name" or "last name"
// You can return "Error" in the PHP page so the Javascript know something is wrong
// and handle this error
}
else
{
var fields = data.split(",");
if (fields.length < 3) {
// As above.
// Something went wrong or invalid response
}
else
{
// In fields array you have what server said.
// Here you can reload the page, change page do what you want
}
}
},
error: function(xhr, status, error)
{
// Error here
}
});
It pass name and lastname to the server and wait for a response like:
field1,field2,field3
The PHP page should be something like..
<?php
// Connect to the server
// Send query to the server
if ($isEverythingOK) {
echo $field1 . "," . $field2 . "," . $field3;
}
else {
echo "Error";
}
?>
Ajax - jQuery Ajax + PHP page
A php page where you pass the 5 fields, add it in the database and return something like "OK" if everything is OK or an error if something went wrong.
Example
$.ajax({
url : "URL to PHP page",
success : function (data) {
if (data === "OK") { /* all ok, here you can update the page to show the new field */ alert("OK"); }
else { /* Error */ alert("Error"); }
},
error : function (xhr, status, error) {
// Request error
alert("Error");
}
});

Trying to send data to mysql, receiving callback issue

This is a mailing list script. It works by itself without jquery but I am trying to adapt it to work with ajax. However, without success. When the $.sql part is commented out it returns the variables in the url string successfully. However, when I uncomment that part of the js file and introduce the PHP into things it simply refreshes the page with the email address still in the input box. By itself, the PHP works so I'm at a loss as to where I'm going wrong. Here's what I have... any help would be appreciated.
Form :
<form name="email_list" action="" id="maillist_form">
<p><strong>Your Email Address:</strong><br/>
<input type="text" name="email" id="email" size="40">
<input type="hidden" name="sub" id="sub" value="sub">
<p><input type="submit" value="Submit Form" class="email_submit"></p>
</form>
JQuery :
$(function() {
$('#maillist_form').submit(function() {
var email = $("input#email").val();
if (name == "") {
$("input#email").focus();
return false;
}
var sub = $("input#sub").val();
if (name == "") {
$("input#sub").focus();
return false;
}
var dataString = $("#maillist_form").serialize();
//alert (dataString);return false;
$.ajax({
type: "POST",
url: "mailing_list_add2.php",
data: dataString,
success: function() {
$('#display_block')
.hide()
.fadeIn(2500, function() {
$('#display_block');
});
}
});
return false;
});
});
PHP :
<?php
// connects the database access information this file
include("mailing_list_include.php");
// the following code relates to mailing list signups only
if (($_POST) && ($_POST["sub"] == "sub")) {
if ($_POST["email"] == "") {
header("Location: mailing_list_add2.php");
exit;
} else {
// connect to database
doDB();
// filtering out anything that isn't an email address
if ( filter_var(($_POST["email"]), FILTER_VALIDATE_EMAIL) == TRUE) {
echo '';
} else {
echo 'Invalid Email Address';
exit;
}
// check that the email is in the database
emailChecker($_POST["email"]);
// get number of results and do action
if (mysqli_num_rows($check_res) < 1) {
// free result
mysqli_free_result($check_res);
// cleans all input variables at once
$email = mysqli_real_escape_string($mysqli, $_POST['email']);
// add record
$add_sql = "INSERT INTO subscribers (email) VALUES('$email')";
$add_res = mysqli_query($mysqli, $add_sql)
or die(mysqli_error($mysqli));
$display_block = "<p>Thanks for signing up!</p>";
// close connection to mysql
mysqli_close($mysqli);
} else {
// print failure message
$display_block = "You're email address - ".$_POST["email"]." - is already subscribed.";
}
}
}
?>
I won't put the include code in here because I'm assuming it is correct - unless the introduction of the jquery means this needs to be adapted as well.
Your AJAX is not catching back the result:
$.ajax({
type: "POST",
url: "mailing_list_add2.php",
data: dataString,
success: function(response) {
$('#display_block')
.hide()
.fadeIn(2500, function() {
$('#display_block').html(response); //just an example method.
//Are you sure the selector is the same?
//Can also be $(this).html(response);
}
});
And as noted by gdoron, there's no "name" variable. Maybe you meant "email" and "sub", respectively?
PHP response, also, isn't echoed back. Just put:
echo $display_block;
You don't echo an data from the server, not trying to get data in the success callback, and the fadeIn callback just have a selector,.
You check for the wrong variable:
var email = $("input#email").val();
if (name == "") { // Didn't you mean email?
$("input#email").focus();
return false;
}
var sub = $("input#sub").val();
if (name == "") { // Didn't you mean sub?
$("input#sub").focus();
return false;
}
How can it work!?

PHP Function can't read jquery POST data?

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();

Categories