rerturning response of an ajax post - javascript

i am trying to check if an email exists in the db but the function doesn't return a value.
This is the code:
function checkemail(email)
{
var returnVal = "";
if (email.indexOf("#") != -1 && email.indexOf(".") != -1)
{
$.post( "registreren.php?email=" + email, function( response ) {
if(response == 1) { returnVal = 1; }
if(response == 2) { returnVal = 2; }
});
}
else
{
returnVal = 3;
}//email
return returnVal;
}
EDIT: email is send as a string

I short, You can not return values from ajax calls as it is asynchronous by nature, the statement return value executes before
To address such cases, use callback, a function accepted as argument and which is executed when response is been received (when asynchronous action is completed).
Try this:
function checkemail(email, callback) {
var returnVal = "";
if (email.indexOf("#") != -1 && email.indexOf(".") != -1) {
$.post("registreren.php?email=" + email, function(response) {
callback(response);
});
} else {
callback(3);
}
}
checkemail('abc#xyz.com', function(val) {
alert(val);
});
checkemail('INVALID_EMAIL', function(val) {
alert(val);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

Can you use something simple like below
$.ajax({
url: 'registreren.php',
type: 'post',
dataType: "json",
data: {'email': email},
success: function (response) {
if (response == 1)
{
returnVal = 1;
}
else
{
returnVal = 3;
}
}
});
instead of
$.post( "registreren.php?email=" + email, function( response ) {
if(response == 1) { returnVal = 1; }
if(response == 2) { returnVal = 2; }
});

Related

Validation error not displaying with AJAX

I have been struggle with this now for two days and I do not know where the problem is.
When I leave the textbox the Ajax call is correct and the result are returned as a true or false and the success: function is executing.
The problem is that the image and error text is not displaying next to the textbox. If I type in more than 50 characters in the textbox the "Must be under 50 characters" message is showing but it I type in a user name that already exist the message is not showing.
What am I missing? Any suggestions?
I use a DevExpress Text Box
Html.DevExpress().Label(
edtSettings =>
{
edtSettings.ControlStyle.CssClass = "label";
edtSettings.Text = "User Name:";
edtSettings.AssociatedControlName = "UserName";
}
)
.Render();
Html.DevExpress().TextBox(
edtSettings =>
{
edtSettings.Name = "UserName";
edtSettings.ControlStyle.CssClass = "editor";
edtSettings.ShowModelErrors = true;
edtSettings.Width = 100;
edtSettings.Properties.ValidationSettings.Assign(IserValidationHelper.UserNameValidationSettings);
edtSettings.Properties.ClientSideEvents.Validation = "OnNameValidation";
edtSettings.ControlStyle.BackColor = System.Drawing.Color.LightYellow;
}
)
.Bind(DataBinder.Eval(IserUser, "UserName"))
.Render();
I have the following JavaScript.
<script type="text/javascript">
function OnNameValidation(s, e) {
if (e.value == null)
e.isValid = false;
$.ajax({
type: 'POST',
url: '/Admin/CheckUsername',
dataType: 'json',
data: { userName: e.value },
error: function () { alert("error"); },
success: function (Data) {
if (Data.result == true) {
e.isValid = false;
e.errorText = "User Exits";
};
}
});
var name = e.value;
if (name == "")
e.isValid = false;
if (name.length > 50) {
e.isValid = false;
e.errorText = "Must be under 50 characters";
}
}
I have the following method in my controller.
[HttpPost]
public ActionResult CheckUsername(string userName)
{
bool status = WebSecurity.UserExists(userName);
return Json(new { result = status });
}
The problem was with my $.ajax call. I had to include the setting async (async:false,) as the default async is true. It is working now correctly.
function OnNameValidation(s, e) {
if (e.value == null)
e.isValid = false;
$.ajax({
type: 'POST',
url: '/ISERAdmin/CheckUsername',
dataType: 'json',
async:false,
data: { userName: e.value },
error: function () { alert("error"); },
success: function (Data) {
if (Data.result == true) {
e.isValid = false;
e.errorText = "User Exits";
};
}
});
var name = e.value;
if (name == "")
e.isValid = false;
if (name.length > 56) {
e.isValid = false;
e.errorText = "Must be under 56 characters";
}
}

check on return value from jquery fails

I use jquery to validate the form, check the math-captcha and finally, send a mail.
The validation works fine and the mail works fine. There is only one problem. When my ajax returns false, the bool validCaptcha keeps always true...
$(document).ready(function() {
$("#confirm").on("click", function(e) {
e.preventDefault();
//Check name
var validName = true;
if ($("#name").val().length == 0) {
$("#name").addClass('error');
validName = false;
}
$("#name").change(function() {
$("#name").removeClass('error');
})
//Check email
var validEmail = true;
if ($("#email").val().length == 0 || validateEmail($("#email").val()) != true) {
$("#email").addClass('error');
validEmail = false;
}
$("#email").change(function() {
$("#email").removeClass('error');
})
//Check message
var validMessage = true;
if ($("#message").val().length == 0) {
$("#message").addClass('error');
validMessage = false;
}
$("#message").change(function() {
$("#message").removeClass('error');
})
//Check captcha
var validCaptcha = true;
$.ajax({
type: 'POST',
url: '../captcha/checkCaptcha.php',
data: $("#mailform").serialize(),
success: function(data) {
var result = $.trim(data);
if (result == 'false') {
$("#inputcaptcha").addClass('error');
validCaptcha = false;
} else if (result == 'true') {
$("#inputcaptcha").removeClass('error');
}
}
});
//Send email
if (validName == true && validEmail == true && validMessage == true && validCaptcha == true) {
$.ajax({
type: 'POST',
url: '../sendMail.php',
data: $("#mailform").serialize(),
success: function(data) {
var result = $.trim(data);
if (result == 'true') {
$("#succesmessage").removeClass('hidden');
}
else if (result == 'false') {
$("#failmessage").removeClass('hidden');
}
}
});
} else {
reloadCaptcha();
$("#inputcaptcha").val("");
}
});
});
In Firebug I see I get a 'false' back from checkCaptcha.php when e.g. I left the field blank of entered a wrong code.
checkCaptcha.php
session_start();
if ( !empty($_POST['inputcaptcha']) ) {
if ( $_POST['inputcaptcha'] == $_SESSION['security_number'] ) {
echo 'true';
}
else {
echo 'false';
}
}
else {
echo 'false';
}
To check I first checked the result-value from the captcha-ajax
alert(result)
//returned false as it should when leaving blank or entering wrong value
Then before calling the mail-ajax I called all bools
alert('validName='+validName+' & validEmail='+validEmail+' & validMessage='+validMessage+' & validCaptcha='+validCaptcha);
//validCaptcha was true, even when result was false...
What do I not see??
Simply put you can't do that since the validate captcha is an asynchronous request,
Instead you can move the email code to the validate captcha success handler like
$(document).ready(function () {
$("#confirm").on("click", function (e) {
e.preventDefault();
//Check name
var validName = true;
if ($("#name").val().length == 0) {
$("#name").addClass('error');
validName = false;
}
$("#name").change(function () {
$("#name").removeClass('error');
})
//Check email
var validEmail = true;
if ($("#email").val().length == 0 || validateEmail($("#email").val()) != true) {
$("#email").addClass('error');
validEmail = false;
}
$("#email").change(function () {
$("#email").removeClass('error');
})
//Check message
var validMessage = true;
if ($("#message").val().length == 0) {
$("#message").addClass('error');
validMessage = false;
}
$("#message").change(function () {
$("#message").removeClass('error');
})
//Check captcha
var validCaptcha = true;
if (validName == true && validEmail == true && validMessage == true) {
$.ajax({
type: 'POST',
url: '../captcha/checkCaptcha.php',
data: $("#mailform").serialize(),
success: function (data) {
var result = $.trim(data);
if (result == 'false') {
$("#inputcaptcha").addClass('error');
} else if (result == 'true') {
$("#inputcaptcha").removeClass('error');
$.ajax({
type: 'POST',
url: '../sendMail.php',
data: $("#mailform").serialize(),
success: function (data) {
var result = $.trim(data);
if (result == 'true') {
$("#succesmessage").removeClass('hidden');
reloadCaptcha();
$("#inputcaptcha").val("");
} else if (result == 'false') {
$("#failmessage").removeClass('hidden');
}
}
});
}
}
});
}
});
});

Javascript does user exists, returning value from ajax to late?

I have a script that tells a visitor if the username is already exist or not before he can proceed,
Below you see a part of my code;
EDIT: Ok I have read what you guys said, and modified it, but I still dont get it to work :S, my teacher doesn't know it either...
<script type="text/javascript">
jQuery(document).ready(function(){
// Smart Wizard
jQuery('#wizard').smartWizard({onFinish: onFinishCallback, onLeaveStep: onNextStep});
function onNextStep(){
validateSteps(function (next) { return next; });
}
function onFinishCallback(){
alert('Finish Clicked');
}
function UsernameExist(fullname, callback)
{
    var data = 'user='+ fullname;
    if(fullname) {
        $.ajax({
            type: "POST",
            url: "user_check.php",
            data: data,
async: false,
            beforeSend: function(html) {
                $("#msg_lastname").html('');
            },
            success: function(html){
                $("#msg_lastname").show();
                 $("#msg_lastname").append(html);
if(html.search("red") != -1)
{
callback(false);
}
else
{
callback(true);
}
            }
        });
}
}
function validateSteps(callback){
var isStepValid = true;
// validate step 1
var firstname = $('#firstname').val();
if(!firstname || (firstname.length < 3 || firstname.length > 10))
{
$('#msg_firstname').html('<br/><font color="red">Enter a first name, between 3 and 10 letters.</font>').show();
isStepValid = false;
}
else
{
$('#msg_firstname').html('').hide();
}
var lastname = $('#lastname').val();
if(!lastname || (lastname.length < 3 || lastname.length > 14))
{
$('#msg_lastname').html('<br/><font color="red">Enter a last name, between 3 and 14 letters.</font>').show();
isStepValid = false;
}
else
{
$('#msg_lastname').html('').hide();
}
var gender = $('#gender').val();
if(!gender || Number(gender) == -1)
{
$('#msg_gender').html('<br/><font color="red">Choose your gender!</font>').show();
isStepValid = false;
}
else
{
$('#msg_gender').html('').hide();
}
var age = $('#age').val();
if(!age || Number(age) > 90 || Number(age) < 21)
{
$('#msg_age').html('<br/><font color="red">Enter a age between 21 and 90.</font>').show();
isStepValid = false;
}
else
{
$('#msg_age').html('').hide();
}
var pin = $('#pin').val();
if(!pin || pin.length > 10 || pin.length < 4)
{
$('#msg_pin').html('<br/><font color="red">Enter a PIN between 4 and 10 numbers.</font>').show();
isStepValid = false;
}
else
{
$('#msg_pin').html('').hide();
}
if (isStepValid) {
UsernameExist(firstname + ' ' + lastname, function (exists) {
callback( exists );
});
} else {
callback( false );
}
}
jQuery('select, input:checkbox').uniform();
});
</script>
Now the problem is that when I run this script, it returns undefined, I guess because the UsernameExist is not done fast enough, and it seems the return UsernameExist is not waiting for it for some reason...
You are returning UsernameExists before it has been run.
Instead, call UsernameExists like this:
if (isStepValid) {
UsernameExist(firstname + ' ' + lastname, function (exists) {
return exists;
});
} else {
return false;
}
This works because UsernameExists expects a callback function and on success passes either true or false to callback().
you need just to set async option as false
function UsernameExist(fullname, callback) {
var data = 'user=' + fullname;
if (fullname) {
$.ajax({
type: "POST",
url: "user_check.php",
data: data,
async: false,
beforeSend: function (html) {
$("#msg_lastname").html('');
},
success: function (html) {
//your code after success
}
});
}
}
from jQuery documentation jQuery.ajax
If you need synchronous requests, set this option to false
so you need to execute your ajax call and wait until it's completely finish to execute what you want based on the result
Maybe you should call UsernameExist(fullname, callback) after jQuery load complete.
try this :
getScript('http://code.jquery.com/jquery-1.9.1.min.js', function () {UsernameExist(fullname, callback)});
function getScript(url, callback) {
var script;
script = document.createElement("script");
script.setAttribute('language', 'javascript');
script.setAttribute('type', 'text/javascript');
script.setAttribute('src', url);
var done = false;
vObj = script.onload;
script.onload = script.onreadystatechange = function () {
if (!done && (!this.readyState ||
this.readyState == "loaded" || this.readyState == "complete")) {
done = true;
if (typeof callback === 'function')
callback(this.ownerDocument.attributes);
}
};
var head = document.getElementsByTagName('head')[0];
head.appendChild(script);}
Try something like this :
// Smart Wizard
$('#wizard').smartWizard({onFinish: onFinishCallback, onLeaveStep: onNextStep});
function onNextStep() {
var isValid = validateSteps();
alert(isValid);
}
function onFinishCallback(){
alert('Finish Clicked');
}
function UsernameExist(fullname)
{
var data = 'user='+ fullname;
var userAlreadyExists = null;
if(fullname) {
$.ajax({
type: "POST",
url: "user_check.php",
data: data,
async: false,
beforeSend: function(html) {
$("#msg_lastname").html('');
},
success: function(html){
$("#msg_lastname").show();
$("#msg_lastname").append(html);
if(html.search("red") != -1)
{
userAlreadyExists = false;
}
else
{
userAlreadyExists = true;
}
}
});
}
return userAlreadyExists;
}
function validateSteps(){
...
if (isStepValid) {
return UsernameExist(firstname + ' ' + lastname);
} else {
return false;
}
}

Ajax continuous pull from database

I have literally just started programing with Ajax and cant get this to work.
Here is what I have so far:
var oldAction = '';
function updateCheck() {
$.ajax({
url: 'check_status.php',
success: function (data) {
if (data.length != oldAction) {
if (data.length == '4') {
playSong();
} else {
pauseSong();
}
}
oldAction = data.length;
}
});
}
setInterval('updateCheck();', 1000);
Does anyone know why this would not be working?
Thanks
Sure. length() is looking for an integer, but you are comparing it to a string.
If oldAction really needs to be a string, then you need to do something like this:
if (data.length != Number(oldAction)) {
if (data.length == 4) {
playSong();
} else {
pauseSong();
}
};
try this:
function updateCheck() {
var
oldAction = 0,
callAjax = function () {
$.ajax({
url: 'check_status.php',
success: function (data) {
if (data.length != oldAction) {
(data.length == 4) ? playSong() : pauseSong();
}
oldAction = data.length;
}
});
};
setInterval(callAjax, 1000);
}
updateCheck();
​

How can I get returned value from JavaScript function that contain jQuery.get()?

I have a JavaScript method that call JQuery.get() and i want to return value from itto callee function .. the following is the code :
function CheckExistance(userName) {
$.get(
"JQueryPage.aspx", { name: userName },
function(result) {
if (result == "1") {
value = true;
}
else if (result == "0") {
value = false;
}
else if (result == "error") {
value = false;
}
}
);
return value;
}
i want return value; return the value setted in get() function ... i know that get() is asynchronous operation anf i want a solution to do that ?
You cannot "return" the value into the called function; because as you've realised, the AJAX call is asynchronous. Instead, you need to effectively delay the execution of the code that follows the AJAX call; by placing this code in the callback function instead.
What happens now, is that this code is executed when the AJAX request has completed, and the value is available.
function CheckExistance(userName, callback) {
$.get(
"JQueryPage.aspx", { name: userName },
function(result) {
var value = false;
if (result == "1") {
value = true;
}
callback(value);
}
);
}
Then where your function might previously have been:
function validateUserName() {
var input = $('someField').val();
var isUnique = CheckExistance(input);
if (isUnique) {
// whatever
} else {
alert("This username is already taken");
};
};
Should now be:
function validateUserName() {
var input = $('someField').val();
CheckExistance(input, function (isUnique) {
if (isUnique) {
// whatever
} else {
alert("This username is already taken");
};
});
};
here is a simple example that works perfectly
function test() {
return $.ajax({
url: "/url/" + param,
type: 'get',
dataType: 'html',
async: false
}).responseText
}
This might work;
function CheckExistance(userName) {
var value
$.get(
"JQueryPage.aspx", { name: userName },
function(result) {
if (result == "1") {
value = true;
}
else if (result == "0") {
value = false;
}
else if (result == "error") {
value = false;
}
}
);
while(value == undefined);
return value;
}

Categories