Reputation: 362
The issue I am having is I cannot access the value of the variables outside the function. I have just started to learn jQuery and I really like it, but this has had me stuck for quite a while now.
I have read other threads related to this, but those methods still do not work!
$.get("/new/verify.php", { username: username, email: email },
function(data){
var stop_loading = '0';
if(data == 'username')
{
alert('username taken');
$('#username_taken_error').show();
$('#username').focus();
stop_loading = '1';
}else if(data == 'email') {
alert('email taken');
$('#email_taken_error').show();
$('#email').focus();
stop_loading = '1';
}else if(data == 'username|email') {
alert('username/email taken');
$('#username_taken_error').show();
$('#email_taken_error').show();
$('#username').focus();
stop_loading = '1';
}
});
alert(stop_loading);
if(stop_loading == '1') {
alert('Stop loading');
return false;
}
Upvotes: 1
Views: 118
Reputation: 87073
As $.get()
performs an AJAX request which is asynchronous, so within your $.get()
success function call another function with your stop_loading
like following:
$.get("/new/verify.php", { username: username, email: email },
function(data){
var stop_loading = '0';
if(data == 'username')
{
alert('username taken');
$('#username_taken_error').show();
$('#username').focus();
stop_loading = '1';
}else if(data == 'email') {
alert('email taken');
$('#email_taken_error').show();
$('#email').focus();
stop_loading = '1';
}else if(data == 'username|email') {
alert('username/email taken');
$('#username_taken_error').show();
$('#email_taken_error').show();
$('#username').focus();
stop_loading = '1';
}
// call function with stop_loading
callAFunction(stop_loading);
});
// this function will be called
// with stop_loading arugment
function callAFunction(stop_loading){
if(stop_loading == '1') {
alert('Stop loading');
return false;
}
}
Upvotes: 2
Reputation: 9080
Declare your variable in parent scope: var stop_loading = '0';
$.get("/new/verify.php", { username: username, email: email },
function(data){
if(data == 'username')
{
alert('username taken');
$('#username_taken_error').show();
$('#username').focus();
stop_loading = '1';
}else if(data == 'email') {
alert('email taken');
$('#email_taken_error').show();
$('#email').focus();
stop_loading = '1';
}else if(data == 'username|email') {
alert('username/email taken');
$('#username_taken_error').show();
$('#email_taken_error').show();
$('#username').focus();
stop_loading = '1';
}
});
alert(stop_loading);
if(stop_loading == '1') {
alert('Stop loading');
return false;
}
Upvotes: 1