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;
}
}
Related
I used this system.. sendind a json with success = 0 or 1 depending on success or error, is this correct or there is a better more correct method to pass true or false to the ajax call?
if (empty($item)) {
// add to the DB
$return['success'] = 0;
return Response()->json($return);
} else {
$return['success'] = 0;
$return['message'] = "Already in Collection";
return Response()->json($return);
}
then in Ajax:
jQuery(function ($) {
$(document).ready(function () {
$("body").on("submit", ".dynamic-form", function (e) {
var form = $(this);
var span = $(form).find('input[name="span_id"]').val();
$.ajax({
url: form.prop('action'),
type: 'post',
dataType: 'json',
data: $(this).serialize(),
success: function (data) {
if (data.success == 1) {
alert("success");
}
else if (data.success == 0) {
alert("error");
}
}
});
e.preventDefault();
});
});
});
I use true or false and then compare like that if (data.success).
If you want a boolean send a boolean, but it's just my opinion.
This depends only on you, you can save your success as you do or to status...
<?php
if (empty($item)) {
// add to the DB
$return['success'] = true;
} else {
$return['success'] = false;
$return['message'] = "Already in Collection";
}
return Response()->json($return);
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
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")
I m trying to check if a username exists or not but even if the username doesn't exists it keeps saying "Username already exists" this is my javascript code:
$.validator.addMethod("checkUsername",
function(value, element) {
var test = "";
$.ajax({
type:"GET",
url: site_url + "/ajax/checkusername/" + value,
success: function(result){
if(result=="exists")
return false;
else
return true;
}
});
},
"Username Already Exists."
);
$("#myform").validate({
rules: {
username2: {
required: true,
minlength: 6,
checkUsername:true
},
password2: {
required: true,
minlength: 6
},
email: {
required: true,
email: true
}
}
});
});
This is my controller code:
public function checkusername($username)
{
$this->load->model('user_model');
$user = $this->user_model->getUser($username);
if($user == null)
{
echo json_encode("notexists");
}
else
{
echo json_encode("exists");
}
}
Any Ideas about this how this can be solved?
Thanks in advance.
Why are you encoding the response as JSON when you're not parsing JSON with your ajax?
What happens when you simply do this?:
public function checkusername($username)
{
$this->load->model('user_model');
$user = $this->user_model->getUser($username);
if($user == null)
{
echo "notexists";
}
else
{
echo "exists";
}
}
EDIT:
$.validator.addMethod("checkUsername",
function(value, element) {
var result = false;
$.ajax({
type:"GET",
async: false,
url: site_url + "/ajax/checkusername/" + value,
success: function(msg) {
result = (msg == "exists") ? false : true;
}
});
return result;
},
"Username Already Exists."
);
$.ajax read a string. Cause you do echo json_encode this string is json.
You can use $.getJSON in stead of $.ajax
$.getJSON( site_url + "/ajax/checkusername/" + value, function( json ) {
if(json=="notexists"){alert('Not exists')}
});
or add $.parseJSON to your original code:
if($.parseJSON(result)=="exists")
update: i had to change my answer
your function doesn't return the result of your $.ajax. $.ajax had to set your return value. Cause can't return before your ajax has been finished, you also have to add async: false to your request (see: How do I make jQuery wait for an Ajax call to finish before it returns?)
$.validator.addMethod("checkUsername",
function(value, element) {
var test = false;
$.ajax({
type:"GET",
async: false,
url: site_url + "/ajax/checkusername/" + value,
success: function(result){
if(result=="notexists") {test = true; }
}
});
return test;
},
"Username Already Exists."
);
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;
});