ajax doesn't check email availability - php

I want to check email availability, but something is wrong here. Inside a form I have:
<input id="inpMail" name="email" type="text" placeholder="E-mail">
JS
$(document).ready(function() {
$("#inpMail").change(function() {
var mail = $("#inpMail").val();
var msgbox = $("#status"); //`status` is a div
if (mail.length > 4) {
$("#status").html('<img src="img/loader.gif" align="absmiddle"> Checking availability...'); //this works
$.ajax({
type: "POST",
url: "ajax.php", // this file is in the same folder
data: "mail="+ mail,
success: function(msg) {
$("#status").ajaxComplete(function(event, request){
if (msg == 'OK') {
msgbox.html('<img src="img/available.png" align="absmiddle">'); //doesn't work
}
else {
msgbox.html(msg); // doesn't work
}
});
}
});
}
else {
$("#status").html('<font color="#cc0000">Please enter atleast 5 letters</font>'); //this works
}
return false;
});
});
ajax.php
$conn = mysql_connect("localhost","root","") or die("Database not connected"); // this message never appears
$db = mysql_select_db("vedic", $conn) or die("Database not connected");
if (isset($_POST['inpMail']))
{
$mail = $_POST['inpMail'];
$sql = mysql_query("select id from members where email='$mail'");
// my db is named `vedic`, table is `members` some fields are `id` and `email`
if (mysql_num_rows($sql))
{
echo '<STRONG>'.$mail.'</STRONG> is already in use.';
}
else
{
echo 'OK';
}
}

You don't need to add the ajaxComplete handler in the success callback as it has already happened. Try this:
success: function(msg) {
if (msg == 'OK') {
msgbox.html('<img src="img/available.png" align="absmiddle">');
}
else {
msgbox.html(msg);
}
}
Also your PHP code is wide open to injection attacks. Use parameterised queries instead.

Replace your javascript with code below,
$(document).ready(function()
{
$("#inpMail").change(function()
{
var mail = $(this).val();
var msgbox = $("#status"); //`status` is a div
if(mail.length > 4)
{
msgbox.html('<img src="img/loader.gif" align="absmiddle"> Checking availability...'); //this works
$.ajax({
type: "POST",
url: "ajax.php", // this file is in the same folder
data: "mail="+ mail,
success: function(msg)
{
if(msg == 'OK')
{
msgbox.html('<img src="img/available.png" align="absmiddle">'); //doesn't work
}
else
{
msgbox.html(msg); // doesn't work
}
}
});
}
else
{
$("#status").html('<font color="#cc0000">Please enter atleast 5 letters</font>'); //this works
}
return false;
});
});
You have extra }); at the end, Also you were repeating yourself with same selector which was defined globally.
PHP
You are sending mail params as posted email address and you are checking for inpMail which will not return true ever.
IN php replace
if (isset($_POST['inpMail']))
with
if (isset($_POST['mail']))

Related

using ajax from a php function

I am new with ajax. I have this php function already from functions.php
function checkUserEmailExistent($email){
...
return $boolean;
}
and this is for my views views.html
<input type='text' name='email' id='email'>
this is for the script.js
jQuery( "#email" ).blur(function() {
jQuery.ajax({
type: 'POST',
url: 'url',
dataType: 'json',
data: { 'value' : $(this).val() },
success : function(result){
}
});
});
my issue is how can I call my php function in ajax to connect it to my html. when it blur it check the email value if it is exist or not.
work in WordPress
JS SCRIPT
jQuery( "#email" ).blur(function() {
jQuery.ajax(
{
url: ajax_url,
type: "POST",
dataType: "json",
data: {
action: 'checkUserEmailExistent',
email: $(this).val(),
},
async: false,
success: function (data)
{
if (data.validation == 'true')
jQuery('.email-massage').html('<div class="alert alert-success">×<strong>Success!</strong> successfully</div>');
else
jQuery('.email-massage').html('<div class="alert alert-danger">×<strong>Oops!</strong> Something went wrong.</div>');
},
error: function (jqXHR, textStatus, errorThrown)
{
jQuery('.email-massage').html('<div class="alert alert-danger">×<strong>Oops!</strong> Something went wrong.</div>');
}
});
});
WP SCRIPT in functions.php
add_action('wp_ajax_checkUserEmailExistent', 'checkUserEmailExistent');
add_action('wp_ajax_nopriv_checkUserEmailExistent', 'checkUserEmailExistent');
function checkUserEmailExistent() {
$email = $_POST['email']; // get email val
/*if() your condition
$email = 1;
else
$email = 0;
*/
if ($email == 1):
$email_val= 'true';
else:
$email_val = 'false';
endif;
echo json_encode(array("validation" => $email_val));
die;
}
in function.php Enqueue file after add this code like this
wp_enqueue_script('themeslug-default', get_template_directory_uri() . '/js/default.js', array('jquery'));
wp_localize_script('themeslug-default', 'ajax_url', admin_url('admin-ajax.php'));
Set url to the php file where you have checkUserEmailExistent function. Then:
function checkUserEmailExistent($email){
...
return $boolean;
}
return checkUserEmailExistent($_REQUEST['value']);
I give the example for validation.This will help you to check
Email id<input type="text" name="email" id="email" size=18 maxlength=50 onblur="javascript:myFunction(this.value)">
You need to add the script
<script>
function myFunction(em) {
if(em!='')
{
var x = document.getElementById("email").value;
var atpos = x.indexOf("#");
var dotpos = x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length) {
alert("Not a valid e-mail address");
document.getElementById("email").value = "";
return false;
exit();
}
var email=$("#email").val();
$.ajax({
type:'post',
url:'email_client.php',
data:{email: email},
success:function(msg){
if (msg.length> 0) {
alert(msg);
document.getElementById("email").value = "";
}
}
});
} }
</script>
Create a page 'email_client.php' and add the code
<?php
$s=$_POST['email'];
include "config.php";
$echeck="select email from client where active=0 and email='".$_POST['email']."'"; //change your query as you needed
$echk=mysql_query($echeck);
$ecount=mysql_num_rows($echk);
if($ecount>='1' && $s!='0')
{
echo "Email already exists";
}
?>
You would call it in your url parameter. However, you'll need to manage your AJAX handler in the PHP script.
AJAX
jQuery( "#email" ).blur(function() {
jQuery.ajax({
type: 'POST',
url: 'functions.php',
dataType: 'json',
data: { 'value' : $(this).val() },
success : function(result){
if (result.success) {
//handle success//
} else if (result.failure) {
//handle failure//
}
}
});
});
PHP
function checkUserEmailExistent($email){
...
return $boolean;
}
if ($_POST['value']) {
$status = checkUserEmailExistent($email);
if ($status === true) {
echo json_encode (array('status' => 'success'));
} elseif ($status === false) {
echo json_encode (array('status' => 'failure'));
}
}
you don't call your server function inside Ajax you only send your data in JSON format to the server on getting this data,server will route(if MVC) it to specific function and return a response to client in JSON format so now inside Ajax you perform operation on success (what to do next ) and in case of failure show the error
How server will route it to specific function that depend on framework you use, but i think they simply use regexp to match with URL

PHP Ajax post result not working

I am trying to get a form to work, but when I call ti with ajax, it will not work.
// ----------------------------EDIT----------------------------
I actually found exactly what I was looking for while browsing around.
jQuery Ajax POST example with PHP
I just have one question, would this be the best way to get the data, or could I call it from an array somehow?
post.php
$errors = array(); //Store errors
$form_data = array();
$query = #unserialize(file_get_contents('http://ip-api.com/php/'.$_POST['name'])); //Get data
if (!empty($errors)) {
$form_data['success'] = false;
$form_data['errors'] = $errors;
} else {
$form_data['success'] = true;
$form_data['country'] = $query['country'];//Have a bunch of these to get the data.
$form_data['city'] = $query['city'];//Or is there an easier way with an array?
$form_data['zip'] = $query['zip'];
// Etc, etc
}
echo json_encode($form_data);
Then in index.php just call it via:
$('.success').fadeIn(100).append(data.whatever-i-have-in-post);
// ----------------------------v-ORIGINAL-v----------------------------
This is I have so far. At the bottom you can see I have an if statement to check if I could get the results from post, but it always results in "unable to get country" (I'm checking with google.com). I don't know if I am doing it correct or not. Any ideas?
<script type="text/javascript" src="//code.jquery.com/jquery-1.11.1.min.js"></script>
<script type="text/javascript" >
$(function() {
$(".submit").click(function() {
var name = $("#name").val();
var dataString = 'name=' + name;
if (name == '') {
$('.error').fadeOut(200).show();
} else {
$.ajax({
type: "POST",
url: "post.php",
data: dataString
});
}
return false;
});
});
</script>
<form id="form" method="post" name="form" style="text-align: center;">
<input id="name" name="name" type="text">
<input class="submit" type="submit" value="Submit">
<span class="error" style="display:none">Input Empty</span>
<?php
include_once('post.php');
if($query && $query['status'] == 'success') {
$query['country'];
} else {
echo 'Unable to get country';
}
?>
</form>
Post.php
$ip = $_POST['name'];
//$ip = isset($_POST['name']); // I dont know if this makes a difference
$query = #unserialize(file_get_contents('http://ip-api.com/php/'.$ip));
Try with this after changing the dataString = {name: name}
$(".submit").click(function() {
var name = $("#name").val();
var dataString = {name: name};
if (name == '') {
$('.error').fadeOut(200).show();
} else {
$.ajax({
type: "POST",
url: "post.php",
data: dataString,
success: function(response) {
// Grab response from post.php
}
});
}
return false;
});
The best way i like to grab the JSON data from ajax request. You can do it by slightly changes in your script.
PHP File
$query = #unserialize(file_get_contents('http://ip-api.com/php/'.$ip));
echo json_encode(array('status'=>true, 'result'=>$query)); // convert in JSON Data
$(".submit").click(function() {
var name = $("#name").val();
var dataString = {name: name};
if (name == '') {
$('.error').fadeOut(200).show();
} else {
$.ajax({
type: "POST",
url: "post.php",
data: dataString,
dataType: 'json', // Define DataType
success: function(response) {
if( response.status === true ) {
// Grab Country
// response.data.country
// And disply anywhere with JQuery
}
}
});
}
return false;
});

add header in php with AJAX

My question is simple, I'm using AJAX and i want to redirect the user to another page if the user fill up the registration form properly, however if the user failed to match his/her password. i want to show an error message.
here is my PHP code:
if (isset($_POST['password']) && isset($_POST['retype_password']))
{
$password = $_POST['password'];
$retype_password = $_POST['retype_password'];
if(!empty($password) && !empty($retype_password))
{
if($password == $retype_password)
{
header("Location: anotherpage.php");
exit();
}
else
{
echo 'password does not match';
}
}
}
here is my ajax:
var frm = $('#frm_register');
frm.submit(function (e)
{
e.preventDefault();
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
$('#error').text(data);
}
});
return false;
});
The problem here is that it doesn't redirect to another page unless i refresh the page.
You can simply use javascript to redirect to the page like below:
if (isset($_POST['password']) && isset($_POST['retype_password']))
{
$password = $_POST['password'];
$retype_password = $_POST['retype_password'];
if(!empty($password) && !empty($retype_password))
{
if($password == $retype_password)
{
echo true;
}
else
{
echo 'password does not match';
}
}
}
And for redirecting, you can use:
var frm = $('#frm_register');
frm.submit(function (e)
{
e.preventDefault();
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
if(data === true) {
window.location = 'Your url path here';
} else {
$('#error').text(data);
}
}
});
return false;
});
Instead of header("Location: anotherpage.php"); just do echo '1' and in your AJAX call, if data['responseText'] == '1' than just do a document.location.href = 'anotherpage.php'
JavaScript does not work with header() as it is browser-based language whereas PHP communicates directly with the Server. The best solution would probably be to return an error flag and message json_encode()'d.
If you return 0 (error) then display a message.
If you return 1 (success) redirect with JavaScript to a URL passed by php. That way you will be able to easily change the new URL should anything change in the website.
JavaScript
var frm = $('#frm_register');
frm.submit(function (e)
{
e.preventDefault();
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
dataType: 'json',
data: frm.serialize(),
success: function (data) {
if (data.r == 0){
$('#error').text(data.m);
}
if (data.r == 1){
document.location.href = data.m;
}
}
});
return false;
});
PHP
if (isset($_POST['password']) && isset($_POST['retype_password']))
{
$password = $_POST['password'];
$retype_password = $_POST['retype_password'];
if(!empty($password) && !empty($retype_password))
{
if($password == $retype_password)
{
echo json_encode(array(
'r' => 1,
'm' => 'anotherpage.php'
));
exit();
}
else
{
echo json_encode(array(
'r' => 0,
'm' => 'Passwords do not match'
));
exit();
}
}
}
var frm = $('#frm_register');
frm.submit(function (e)
{
e.preventDefault();
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
if(data) {
winlow.location = data;
}
}
});
return false;
});
In your action page just echo the link where you wanna redirect if you want

ajax always showing email already Email already exist in this function

I'm validating user email by ajax and php but here ajax always showing email already exit;
AJAX/Javascript Code:
$.ajax({
type: "POST",
url: "classes/aeAjaxFunction.php",
data: "do=sem&ci=" + ci11,
success: function(msg) {
if(msg ="yes") {
alert('Email already exist');
}
else {
// alert("Occured internal Error. please check network connection");
}
// $('#psid').html("<img src='images/spacer.gif'>");
//$('#email1').html(msg);
//
//$('#sid').sSelect({ddMaxHeight: '300px'});
},
error: function() {
// alert('some error has occured...');
},
start: function() {
// alert('ajax has been started...');
}
});
PHP Code:
<?php
function checkSpEmail($postAr) {
$mysqli = dbconn::get_mysqli();
$email = $postAr['ci'];
$selEmail = "SELECT fld_email FROM tbl_spouse WHERE fld_email = '$email' ";
$res = mysqli_query($mysqli, $selEmail);
$count = mysqli_num_rows($res);
if (mysqli_num_rows($res) == 1) {
echo 'yes';
exit;
}
}
?>
change your ajax code, you are using msg = "yes" and you must have to use msg == "yes"
$.ajax({
type: "POST",
cache: false,
url: "classes/aeAjaxFunction.php",
data: "do=sem&ci=" + ci11,
success: function(msg) {
if(msg == "yes") {
alert('Email already exist');
}
else {
// alert("Occured internal Error. please check network connection");
}
// $('#psid').html("<img src='images/spacer.gif'>");
//$('#email1').html(msg);
//
//$('#sid').sSelect({ddMaxHeight: '300px'});
},
error: function() {
// alert('some error has occured...');
},
start: function() {
// alert('ajax has been started...');
}
});
Change
if(msg ="yes")
to
if(msg =="yes")

Form Validation To Send Only If Username Doesn't Exist

I've created a JQuery script that checks a database for usernames and shows an error if you type in an existing name on keyup, this is workng fine but the form still submits even if this error is true. What other code can I add to check that this error doesn't exist? Here is the code I have so far:
<script>
$(function()
{
var ck_username = /^[A-Za-z0-9_]{5,15}$/;
// Username validation
$('#username').keyup(function()
{
var username=$(this).val();
if (!ck_username.test(username))
{
$('.usernameStatus').removeClass("success").addClass("error");
}
else
{
$('.usernameStatus').removeClass("success").removeClass("error");
jQuery.ajax({
type: 'POST',
url: 'check-users.php',
data: 'username='+ username,
cache: false,
success: function(response){
if(response == 1){
$('.usernameStatus').removeClass("success").addClass("error");
}
else {
$('.usernameStatus').removeClass("error").addClass("success");
}
}
});
}
});
// Submit button action
$('#registerButton').click(function()
{
var username=$("#username").val();
if(ck_username.test(username))
{
jQuery.post("register.php", {
username:username,
}, function(data, textStatus){
if(data == 1){
window.location.replace("registered.php");
}else{}
});
}else{
alert("Something went Wrong - Please Check All Fields Are Filled In Correctly");
}
return false;
});
//End
});
</script>
Thank you
please see the comments on the code
assuming that the data == 1 means that the name is already registered and you will show an error
<script>
$(function()
{
var name = false; // a variable that holds false as the initial value
var ck_username = /^[A-Za-z0-9_]{5,15}$/;
// Username validation
$('#username').keyup(function()
{
var username=$(this).val();
if (!ck_username.test(username))
{
$('.usernameStatus').removeClass("success").addClass("error");
}
else
{
$('.usernameStatus').removeClass("success").removeClass("error");
jQuery.ajax({
type: 'POST',
url: 'check-users.php',
data: 'username='+ username,
cache: false,
success: function(response){
if(response == 1){
$('.usernameStatus').removeClass("success").addClass("error");
}
else {
$('.usernameStatus').removeClass("error").addClass("success");
name = true; // on success , if the name isnt there then assign it to true
}
}
});
}
});
// Submit button action
$('#registerButton').click(function()
{
var username=$("#username").val();
if(ck_username.test(username) && name == true) // check for the value of name
{
jQuery.post("register.php", {
username:username,
}, function(data, textStatus){
if(data == 1){
window.location.replace("registered.php");
}else{}
});
}else{
alert("Something went Wrong - Please Check All Fields Are Filled In Correctly");
}
return false;
});
//End
});
</script>
Instead of checking the username against the regex, you should check the status of $('.usernameStatus') because it is possible that it passes the regex test but still fails the duplicate test returned from your db.
So
$('#registerButton').click(function()
{
var username=$("#username").val();
if(ck_username.test(username))
{
should instead be:
$('#registerButton').click(function()
{
var username=$("#username").val();
if(!$('.usernameStatus').hasClass('error'))
{
Even better would be to introduce a variable that holds the validity of the name field so you don't need to get the DOM Element all the time and check it's class.
I think your error might be because of a bad data syntax
It should be like this:
data: 'username:'+ username,
Debug your PHP code to see if its receiving the username properly at the moment though

Categories