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."
);
Related
Say I have a function as following. alert_danger returns the error message in red box. check_empty checks if a value posted from form is empty or not.
function alert_danger($msg){
$alert = "<div class='alert alert-danger' id='responseBox'>".$msg."</div>";
return $alert;
}
function checkEmpty($postValue, $msg){
if($postValue == null){
echo alert_danger($msg);
exit();
}
}
Now when I want to return the function value using jSON it's not returning the same. The following error is occuring:
// It returns this
$msg = alert_danger("Ah! Hello Adventurer, and welcome to the town of Honeywood!");
echo json_encode(array('status' => $msg));
// But it does not returns this
$msg = checkEmpty($state, "Ah! Hello Adventurer, and welcome to the town of Honeywood!");
echo json_encode(array('status' => $msg));
What seems to be the problem here?
Here is my jQuery if needed!
$(".action").click(function() {
var form = $(this).closest("form");
var type = form.find(".type").val();
var dataString = form.serialize();
var btnValue = $(".action").html();
var btnElement = $(".action");
var url = form.attr("action");
$.ajax({
type: "POST",
dataType : "json",
url: url,
data: dataString,
cache: true,
beforeSend: function(){
$('.message').hide();
$(".overlay").show();
$(".wickedpicker").hide();
btnElement.html('Please wait...');
},
success: function(json){
$('.message').html(json.status).fadeIn();
// $('#content').html(json.result).fadeIn();
$(".overlay").hide();
$("html, body").animate({ scrollTop: $(".message").offset().top }, "slow");
btnElement.html(btnValue);
if(type == 'admin'){
if($('.message').find('#responseBox').hasClass('alert-success')){
setTimeout(function(){
$(".overlay").hide();
window.location.replace("dashboard.php");
}, 1000);
}
}
}
});
return false;
});
Consider the following.
PHP
<?php
function checkEmpty($postValue, $msg){
return $postValue == null ? array("status" => "error", "message" => "Empty Value") : array("status" => $postValue, "message" => $message);
}
header('Content-Type: application/json');
echo json_encode(checkEmpty($state, "Ah! Hello Adventurer, and welcome to the town of Honeywood!"););
?>
JavaScript
function redirectTo(url, time) {
if (!url) {
return false;
}
time = time != undefined ? time : 0;
setTimeout(function() {
window.location.href = url;
}, time);
}
$(".action").click(function() {
$(this).closest("form").submit();
});
$("form").submit(function(event) {
event.preventDefault();
var type = $(this).find(".type").val();
var dataString = $(this).serialize();
var btnValue = $(".action").html();
var btnElement = $(".action");
var url = $(this).attr("action");
$.ajax({
type: "POST",
dataType: "json",
url: url,
data: dataString,
cache: true,
beforeSend: function() {
$('.message').hide();
$(".overlay").show();
$(".wickedpicker").hide();
btnElement.html('Please wait...');
},
success: function(json) {
if (json.status == "error") {
$(".message").html("<div class='alert alert-danger error'>" + json.message + "</div>").fadeIn();
} else {
$('.message').html("<div class='alert alert-danger'>" + json.message + "</div>").fadeIn();
$("html, body").animate({
scrollTop: $(".message").offset().top
}, "slow");
btnElement.html(btnValue);
if (type == 'admin') {
if ($('.message').find('#responseBox').hasClass('alert-success')) {
redirectTo("dashboard.php", 1000);
}
}
}
}
});
return false;
});
Typically, it is bad practice to use language X to generate code in language Y. Try decoupling the two languages by making data their only interface -- don't mingle the code.
https://softwareengineering.stackexchange.com/questions/126671/is-it-considered-bad-practice-to-have-php-in-your-javascript
You have to be careful to not confuse echo and return, they do very different things.
https://www.php.net/manual/en/function.echo.php
https://www.php.net/manual/en/function.return.php
Since you're passing back JSON data to the AJAX Call, I would advise wrapping your HTML inside the callback versus sending it back inside the JSON.
I think you should take a look at your success function. I think it normally runs before the page loads. So, its possible none of the html your referencing in there exists yet. So move it out to a function like this:
success: function(json) {
doSomething();
}
function doSomething(json){
$( document ).ready(function() {
console.log('page has loaded now modify your html with jquery'+json);
}
}
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;
});
});
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 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;
}
}