D3.get populating Global Object [duplicate] - javascript

My experience in jQuery is limited and I've searched around for an answer but can't seem to find it.
This function returns a false or true based on a get. Now my problem is that the function 'Availability' doesn't return a false nor true if I get my data.
This is the code.
function Availability(){
var email = jQuery('#emailRegister').val();
jQuery.get("test.php", {email: email})
.done(function(data) {
if(data == 'true'){
jQuery(".warningEmailDuplicate").hide();
return true;
}else if(data == 'false'){
jQuery(".warningEmailDuplicate").show();
return false;
}
});
}

jQuery.get creates an AJAX request. These are asynchronous. You cannot return a value from the AJAX callback to the calling function. The function will have exited, returning nothing, before the HTTP request completes.
You need to rewrite your code to use callbacks:
function Availability(){
var email = jQuery('#emailRegister').val();
jQuery.get("test.php", {email: email})
.done(function(data) {
if(data == 'true'){
jQuery(".warningEmailDuplicate").hide();
AvailabilityResult(true);
}else if(data == 'false'){
jQuery(".warningEmailDuplicate").show();
AvailabilityResult(false);
}
});
}
function AvailabilityResult(available) {
// *available* will be true or false
// do with this value what you wanted to do with the return value from Availability
}

JQuery is Async scripting language, so when you calls this method compiler does not wait to get the return value.
When you call Availablity(); then off-course an Ajax get request sends to test.php and in the mean time compiler returns nothing from your method and assign variable seems undefined.
To prevent this issue, you need to create a callback function rather than simple return the value.
see example with no callback and example with callback
Try this code:
function Availability(callback){
var email = jQuery('#emailRegister').val();
jQuery.get("test.php", {email: email})
.done(function(data) {
if(data == 'true'){
jQuery(".warningEmailDuplicate").hide();
callback(true);
}else if(data == 'false'){
jQuery(".warningEmailDuplicate").show();
callback(false);
}
});
}
//calling function
Availablity(function(status){
var available = status;
alert(available);
});

Related

AJAX function does not return any value [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 months ago.
Problem
I have a JavaScript function which uses AJAX for getting a value from a MySQL table through PHP. I wrote all of my PHP and AJAX code correctly because when I check the result it receives, it shows the value as I want it to. So, the problem is when I receive the data correctly, I try to return it. But when I tried calling that function, even though it shows the correct value when I try seeing the value inside the AJAX function, as soon as I return it and check where I call the function, it shows "undefined".
Code Used
This is the AJAX function code -
function CheckUser(EmailID) {
alert(EmailID);
$.ajax("AJAXcommands\\CheckUser.php", {
type: "POST", // type of the data we send (POST/GET)
data: {
EmailID: EmailID,
},
success: function (data) {
// when successfully sent data and returned
alert(data); //It returns correct value here
return data;
},
});
}
And this is where I call the function -
function Confirm(button) {
var input = document.getElementById("UserEmail");
var checkUser = CheckUser(input.value);
alert(checkUser); //This does not return correct value and return "undefined"
if (input.value == "") {
alert("Pls enter a value!");
} else if (checkUser == "true") {
alert("User Doesn't Exist!");
} else {
//Do Something...
}
}
When I try alerting the data in the AJAX function it works correctly, but when I try alerting it in the second function, it returns "undefined"
Tried Solutions
I tried using the callback() method instead of return but it still does not work and returns the same result. I used callback() like this -
callback(data);
So does anyone has any solution to my problem? Thanks in advance!
By the way, thinking it is not relevant, I did not add PHP code, if I need to then please tell me in the comments.
function CheckUser(EmailID, callback) {
alert(EmailID);
$.ajax("AJAXcommands\\CheckUser.php", {
type: "POST", // type of the data we send (POST/GET)
data: {
EmailID: EmailID,
},
success: function (data) {
// when successfully sent data and returned
alert(data); //It returns correct value here
callback(data)
},
});
}
function Confirm(button) {
var input = document.getElementById("UserEmail");
CheckUser(input.value, data => {
alert(data);
if (input.value == "") {
alert("Pls enter a value!");
} else if (data== "true") {
alert("User Doesn't Exist!");
} else {
//Do Something...
}
}
}

Value is not passed to Variable(JQuery, Javascript) [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 7 years ago.
I have a JQuery-Code like this:
$.post("count_images.php",{}, function(data)
{
if (data != '')
{
alert(data);
}
else
{
//Error
}
});
It simply sends a request to count_images.php and returns a number like 23 for example. This works perfectly fine, but when i change it into this:
var number_images;
$.post("count_images.php",{}, function(data)
{
if (data != '')
{
number_images = data;
}
else
{
//Error
}
});
alert(number_images);
It does not work correctly. The alert-function always outputs an undefined. I simply want to save the result saved in data in a variable called number_images so i can keep on working with that. Thank you very much in advance.
The $.post() method is asynchronous, so when the second code snippet runs, the alert will be fired off before the AJAX POST returns with date, hence why number_images is undefined (as it hasn't been populated yet).
You can have the POST be executed synchronously by using $.ajax() and passing async: false and method: 'POST' flags. But this is not usually a good idea, as it defeats the entire purpose of AJAX (the A stands for asynchronous, after all).
Alternatively, either use the callback function (same as the first snippet) or attack other callbacks using the jQuery Promise API. For example
$.post("count_images.php")
.done(function(data)
{
if (data != '')
{
alert(data);
}
else
{
//Error
}
});
Keep in mind that $.post() is an asynchronous method and all that code is in a callback function, so when
alert(number_images);
is called, your callback function likely has not run yet because $.post() is still waiting for a response.
You need to put anything that uses number_images in the callback. It might be helpful to define another function like so:
var number_images;
var do_stuff_with_number_images = function() {
alert(number_images);
// any other code referencing number_images goes here
};
$.post("count_images.php",{}, function(data)
{
if (data != '')
{
number_images = data;
}
else
{
//Error
}
do_stuff_with_number_images();
});
alert(number_images);
var number_images,
data ='';
$.post("count_images.php",{}, function(data)
{
if (data != '')
{
number_images = data;
}
else
{
//Error
}
});
alert(number_images);

Wait for Json call to be completed in javascript

I am using the below json call in my javascript method
function go123(){
var cityName = "";
var temp = $.getJSON("https://abc.in/api/city?callback=?", args,function (data) {
if (data.properties.city != null){
cityName = data.properties.city;
check = true;
} else {
cityName = "NaN"
}
}); // end of my Json Call.
// my validation is done below
if(cityName != "NaN"){
return false;
} else {
// here I except the cityName to not be "" but be some value which is set as :cityName = data.properties.city;
return true;
}
} // end of my function
Now what problem I am facing is that before my Json call is compelete the next set of statements ( in the code below the line "// my validation is done below " ) is already executed.
I want to get the values set in my json call (cityName) and only once when the call is completed then only I want the next set of statements to be executed.
Please help me on this. Any advice/ideas/suggestions will be highly appreciated ! Thanks.
The function you passed into $.getJSON() is the callback run when the function completes successfully. All else being equal, stick the "rest of it" inside that method. If you can't do so, what you're after is called a jQuery Deferred. See http://www.erichynds.com/jquery/using-deferreds-in-jquery/ and http://joseoncode.com/2011/09/26/a-walkthrough-jquery-deferred-and-promise/ for code that looks like so:
var req = $.getJSON('blah', 'de', 'blah');
req.success(function(response){
// The request is done, and we can do something else
});
AJAX calls are asyncrhonous. They don't wait for the reply. They operate in the background and execute the code that follows it immediately after the call. Therefore, the data received in getJSON is not yet there when the operations below it are executed.
You can put the operations you want in the callback so that they get executed when the data is revceived:
function go123(callback){
var temp = $.getJSON("https://abc.in/api/city?callback=?", args,function (data) {
//execute the callback, passing it the data
callback(data);
});
}
//when you call go123, it get's back the result:
function goBefore123(){
//get our JSON
go123(function(data){
//when we get our data, evaluate
if (data.properties.city != null){
cityName = data.properties.city;
check = true;
alert('executed after returned');
afterCall();
} else {
cityName = "NaN"
}
});
alert('i am executed before anything else');
}
function afterCall(){
alert('im also executed after');
}
Calling an external url will take too much time, wait for the result
Check below
var jqxhr = $.getJSON("example.json", function() {
alert("success");
})
.success(function() { alert("second success"); })
.error(function() { alert("error"); })
.complete(function() { alert("complete"); });
http://api.jquery.com/jQuery.getJSON/
.success
http://api.jquery.com/jQuery.getJSON/

Using synchronous JAX in registration form for checking username availability

I have a registration form. When I hit the Submit button it should check if the Username is not taken and that the passwords match. So I wrote a few functions: one that checks the passwords, one that checks if the username is available and the main function, that calls for the 2 checking functions. The password checking function works nice, but my problem is with the username checking function. This is the function:
function checkIsUsernameExist(){
if($("#txtNewUsername").val() == "") {
$("#divIsUsernameExist").html("");
return false;
} else {
$.getJSON("inc/API.php",
{
command : 'isUsernameExist',
username : $("#txtNewUsername").val(),
},
function(result)
{
if (result != true){
$("#divIsUsernameExist").html("This username is available!");
return true;
} else {
$("#divIsUsernameExist").html("This username is not available!");
return false;
}
});
}
}
When the username is empty, it does return False. But when some value is entered it returns Undefined.
Somebody told I should use Synchronous JAX (but didn't tell me how), so I tried to write this code:
function checkIsUsernameExistAsync(){
if($("#txtNewUsername").val() == "") {
$("#divIsUsernameExist").html("");
return false;
} else {
$.ajax({
type: 'POST',
url: 'inc/API.php',
data: ({
command : 'isUsernameExist',
username : $("#txtNewUsername").val(),
cache: false,
async: false
}),
success: function(result){
if (result != true){
$("#divIsUsernameExist").html("This username is available!");
return true;
} else {
$("#divIsUsernameExist").html("This username is not available!");
return false;
}
}
});
}
}
But I get the same result - False when it's empty, Undefined when some value is entered. I tried to change $.ajaxto $.getJSON in the second function, but still had the same result.
This is the code from API.php:
case "isUsernameExist":
echo (isUsernameExist($_REQUEST["username"]));
break;
it calls for a function in included page BusinessLogic.php, here's this function:
function isUsernameExist($username)
{
$arr = select("select * from users where username='$username'");
if(count($arr) == 1)
return json_encode(true);
else
return json_encode(false);
}
How can I make it work??
Thank you!
To summarise the comment chain:
Avoid synchronous AJAX requests: Remove async: false
Add `dataType: 'json',
return inside a success handler of jQuery.ajax does not set the return value of the outer function. To correctly pass the results, define a callback handler. Replace:
Before: http://jsfiddle.net/wGfzc/
After: http://jsfiddle.net/wGfzc/2/

javascript: returning a bool

I have written a jQuery / JS function which "runs a php query".
function runQuery(op){
if(op.type == "edit"){
var b = false;
if(op.id != "" && (op.fromSong || op.toSong || op.when || op.comment)){
$.post("processor.php", { id: op.id, type: "edit", fromSong: op.fromSong, toSong: op.toSong, when: op.when, comment: op.comment }, function(data){
if(data == true){
console.log(true);
b = true;
}else{
console.log(false);
b = false;
}
});
}
return b;
}
I want it to return true of false depending on what the server answers. I'm sure that the php script is working correctly and returning true or false correctly. But every time i run the function the console.log() outputs the correct value, unlike the variable b. It seems to alway be false. What am I doing wrong?
Since any .ajax() call ($.post is just a wrapper to $.ajax) runs asyncronously, your variable b will always return false. Best thing to "workaround" this is to pass in another callback:
function runQuery(op, callback){
if(op.type == "edit"){
if(op.id != "" && (op.fromSong || op.toSong || op.when || op.comment)){
$.post("processor.php", { id: op.id, type: "edit", fromSong: op.fromSong, toSong: op.toSong, when: op.when, comment: op.comment }, function(data){
if(data == true){
console.log(true);
callback.apply(this, [data]);
}else{
console.log(false);
callback.apply(this, [data]);
}
});
}
}
runQuery({
type: 'edit',
}, function(data) {
alert(data);
});
yes it is wrong.
$.post is done asynchronously, so b is set in the call back but returned before you reach the callback.
you should use $.ajax instead with method:"POST", and async: false
However it could be better to have a deisgn when you use the value of b in the callback only because async: false can freeze your browser.
Your function will return before the asynchronous request to the server has completed. Before you ask, it is both impractical and undesierable to make the call synchronous so that you can return true/false from your function. You might consider supplying a callback argument or arguments to your function:
function runQuery(op, success, failure){
// ...
if(data == true){
success();
}else{
failure();
}
// ...
}
runQuery('edit',
function () { alert('success!'); },
function () { alert('failure!'); }
);
This is a wrong way to do it. Ajax requests are asynchronous and not performed one after another as you expect them too. There is no way around that. You will have to redesign your code to nest ajax calls.
Something similar to this:
$.post("a.php", {function(data){
//1st check
$.post("b.php", {function(data){
//2nd check
$.post("c.php", {function(data){
//final actions
});
});
});
Only this way ajax calls will be stacked - the next will be performed after the previous.

Categories

Resources