I have a form on my page. When the user hits the Send button, in the background it also generates a unique_number by calling for a function that generates this number and also checks in the DB that this number doesn't exist; if it does - generates it again, if doesn't - returns this number. However, for some reason when I'm trying to print out this number to the page, or alert it - I'm getting undefined
, though the function returns the number.
Here's the call for the function:
var unique_num = create_unique_number();
alert(unique_num);
rest of this function...
And here's the function itself:
function create_unique_number()
{
var num = Math.floor(Math.random() * (999999 - 100000 + 1)) + 100000;
$.getJSON("inc/API.php",
{
command:"is_unique_number_exist",
unique_num:num
},
function(result){
if(result==true){
create_unique_number();
}
else
{
return num;
}
});
}
I do get the results, if it's true - it generates new number, if false - should return. I tried to alert
the num in the else
part, and it did Alert the number, but on return - undefined.
Why is it happening and how to fix it?