ajax always showing email already Email already exist in this function - php

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")

Related

Ajax not sending proper success back

I have the below Ajax function
ajax = function (params, action) {
$.ajax({
type: "POST",
url: "ajax.php",
data : params+"&action="+action,
dataType: "json",
success: function(response) {
switch(action)
{
case "save":
//some stuff
break;
case "del":
var seclastRow = $("."+table+" tr").length;
if(response.success == 1)
{
$("."+table+" tr[id='"+response.id+"']").effect("highlight",{color: '#f4667b'},500,function()
{
$("."+table+" tr[id='"+response.id+"']").remove();
});
}
break;
}
},
error: function() {
alert("Unexpected error, Please try again");
}
});
}
The following is the ajax.php that it calls. The file is a big if-else series, but I am pasting the wrong part only.
else if ($action == "del")
{
$id = $_POST['rid'];
$res = $obj->delete_record($id);
if ($res)
{
echo json_encode(array("success" => "1","id" => $id));
}
else
{
echo $obj->error("delete");
}
}
However, once the result is echoed back, the success function never enters in the Ajax part and I always get the Unexpected error alert.
Any ideas?
I as able to get the error using the callback error: function() and then displaying the response inside console.log. Check the image. response text

how to get ajax "success" and "error" response using php-crud-api

I am having issues validating a response from API.
I am using php-crud-api and I am passing the values from my login form to the url filter[], the server responds with a 200 OK and returns the json data from the table. However I don't need the json data just a "success" or "error" response. Any help would be amazing. Thank you in advance for any feedback.
$(document).ready(function() {
$("#login-button").click(function() {
log_email = $("#login_email").val();
log_password = $("#login_password").val();
$.ajax({
type: "GET",
url: "http://www.website.com/api.php/users?",
crossDomain: true,
data: "filter[]=email,eq,email=" + log_email + "&filter[]=password,eq,password=" + log_password,
dataType: 'json',
success: function(data) {
if (data == "null") {
console.log("Email and Password DIDN'T match");
$( "#invalid-login" ).popup( "open" );
}
else if (data == "true") {
console.log("it's a !!MATCH!!");
window.location = "content.html";
}
}
});
return false;
});
});
I've read the documentation of https://github.com/mevdschee/php-crud-api and its written that it will return the output in json format only "Condensed JSON ouput: first row contains field names", so you need to change your code accordingly or you can use some other option.
Luckily the API developer got back to me and he offered the following solution:
in the ajax call add the following line to limit the output:
+"&columns=email"
Replase:
if (data == "null") {
With:
if (data.users.records.length==0) {
In the else clause, just replace:
else if (data == "true") {
with:
else {
RESULT:
$(document).ready(function() {
$("#login-button").click(function() {
log_email = $("#login_email").val();
log_password = $("#login_password").val();
$.ajax({
type: "GET",
url: "http://www.website.com/api.php/users?",
data: "filter[]=email,eq,"+log_email+"&filter[]=password,eq,"+log_password+"&columns=email",
crossDomain: true,
dataType: 'json',
cache: false,
success: function(data) {
if (data.itouchyou.records.length == 0) {
//FAIL
$( "#invalid-login" ).popup( "open" );
console.log("Email and Password DIDN'T match");
}
else {
// SUCCESS
window.location = "content.html";
console.log("it's a !!MATCH!!");
}
}
});
return false;
});
});

ajax doesn't check email availability

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']))

Jquery Remote Validation Rule - php email check failing

I have been scanning the interwebs for many days now, and have tried just about everything posted to resolve the issue. What i am trying to do is (like many other posts), send a remote mysql query via remote validation.. there has been much debate on the proper format of the return data (like json_encode or not) and i have tried both suggestions to no avail.
Jquery Code
$('#register-form-step-1').validate({ // initialize plugin
rules:
{
confirmEmail:
{
equalTo: "#clientEmailAddress"
},
clientPassword:
{
rangelength: [6,32],
required: true
},
clientUserName:
{
minlength: 4,
required: true,
remote:
{
async:false,
type:'POST',
url:'<?php echo base_url("home/checkusername")?>',
data: {
clientUserName: function() {
return $("#clientUserName").val();
}},
success: function(data)
{
console.log(data);
if (String(data) === String('true'))
{
//not registered
console.log("Not registered");
return true;
}
else
{
console.log(data);
//already registered
console.log("Already registered");
}
},
error: function()
{
console.log("There was an error");
}
}
},
clientEmailAddress:
{
async:false,
required: true,
email: true,
remote:
{
type:'POST',
url:'<?php echo base_url("home/checkemail")?>',
data: {
clientEmailAddress: function() {
return $("#clientEmailAddress").val();
}},
success: function(data)
{
console.log(data);
if (String(data) === String('true'))
{
//not registered
console.log("Not registered");
return true;
}
else
{
//already registered
console.log("already registered");
}
},
error: function()
{
console.log("There was an error");
}
}
}
},
submitHandler: function ()
{
$.ajax({
type: 'POST',
url: '<?php echo base_url("home/register")?>',
data: $('#register-form-step-1').serialize(),
success: function ()
{
alert('success')
console.log('form was submitted');
$("#register-form-1").modal('hide');
$("#register-form-2").modal('show');
},
error: function(data, textStatus, jqXHR) {
alert('error')
}
});
return false; // ajax used, block the normal submit
}
});
PHP CODE
public function checkemail()
{
$email = mysql_real_escape_string($_POST['clientEmailAddress']);
$qResult = $this->db->query('
SELECT clientEmailAddress FROM clientdata WHERE clientEmailAddress = "'.$email.'" limit 1
');
$result = true;
if ($qResult->num_rows == 1)
{
$result = false;
}
header('Content-Type: application/json');
echo json_encode($result);
}
Replace the line in php
echo json_encode($result);
by
echo json_encode(array($result));
and add datatype as json in js
Otherwise you can simply try
echo 1 or 0; return;
Before the line :
header('Content-Type: application/json');
Add :
header("HTTP/1.1 200 OK");
I had the same issue but finally the sample funtion did it for me.
function checkIfEmailExists($email){
$query="SELECT email FROM users WHERE email='".$email."'";
$link=#mysql_query($query);
$count=mysql_num_rows($link);
$response='';
if($count==1){
$response=false;
}else if($count==0){
$response=true;
}
header('Content-Type: application/json');
echo json_encode($response);
return;
}
}

How to return an error callback in php?

I was wondering if I can return an error callback back to my jquery from my php page that I created, which will then display an alert based upon the actions that happen in my php page. I tried creating a header with a 404 error but that didn't seem to work.
Sample JQuery Code:
$(document).ready(function()
{
var messageid= '12233122abdbc';
var url = 'https://mail.google.com/mail/u/0/#all/' + messageid;
var encodedurl = encodeURIComponent(url);
var emailSubject = 'Testing123';
var fromName = 'email#emailtest.com';
var dataValues = "subject=" + emailSubject + "&url=" + encodedurl + "&from=" + fromName + "&messageID=" + messageid;
$('#myForm').submit(function(){
$.ajax({
type: 'GET',
data: dataValues,
url: 'http://somepage.php',
success: function(){
alert('It Was Sent')
}
error: function() {
alert('ERROR - MessageID Duplicate')
}
});
return false;
});
});
Sample PHP Code aka somepage.php:
<?php
include_once('test1.php');
include_once('test2.php');
if(isset($_GET['subject']))
{
$subject=$_GET['subject'];
}
else
{
$subject="";
}
if(isset($_GET['url']))
{
$url=$_GET['url'];
}
else
{
$url="";
}
if(isset($_GET['from']))
{
$from=$_GET['from'];
}
else
{
$from="";
}
if(isset($_GET['messageID']))
{
$messageID = $_GET['messageID'];
}
else
{
$messageID="";
}
$stoqbq = new test2($from, $messageID);
$msgID = new stoqbq->getMessageID();
if($msgID = $messageID)
{
header("HTTP/1.0 404 Not Found");
exit;
}
else
{
$userID = $stoqbq->getUser();
$stoqb = new test1($subject,$url,$messageID,$userID);
$stoqb->sendtoquickbase();
}
?>
-EDIT-
If you get the invalid label message when using json this is what I did to fix this problem:
Server Side PHP Code Part-
if($msgID == $messageID)
{
$response["success"] = "Error: Message Already In Quickbase";
echo $_GET['callback'].'('.json_encode($response).')';
}
else
{
$userID = $stoqbq->getUser();
$stoqb = new SendToQuickbase($subject,$url,$messageID,$userID);
$stoqb->sendtoquickbase();
$response["success"] = "Success: Sent To Quickbase";
echo $_GET['callback'].'('.json_encode($response).')';
}
Client Side JQuery Part-
$('#myForm').submit(function(){
$.ajax({
type: 'GET',
data: dataValues,
cache: false,
contentType: "application/json",
dataType: "json",
url: "http://somepage.php?&callback=?",
success: function(response){
alert(response.success);
}
});
return false;
});
You can a return a JSON response from your PHP with a success boolean.
if($msgID = $messageID)
{
echo json_encode(array('success' => false));
}
else
{
$userID = $stoqbq->getUser();
$stoqb = new test1($subject,$url,$messageID,$userID);
$stoqb->sendtoquickbase();
echo json_encode(array('success' => true));
}
and in your Javascript:
$.ajax({
type: 'GET',
dataType: 'json',
data: dataValues,
url: 'http://somepage.php',
success: function(response){
if(response.success) {
alert('Success');
}
else {
alert('Failure');
}
}
});
There is an accepted q/a with the same thing: How to get the jQuery $.ajax error response text?
Basically you need to grab the response message from the error callback function:
$('#myForm').submit(function(){
$.ajax({
type: 'GET',
data: dataValues,
url: 'http://somepage.php',
success: function(){
alert('It Was Sent')
}
error: function(xhr, status, error) {
alert(xhr.responseText);
}
});
return false;
});

Categories