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

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);

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...
}
}
}

how to get data outside javascript function

im wondering if i can get some help here, im not a skilled coder by far, but im trying to retrieve results outside the function and the result in log im getting is Undefined
var pricecrex;
getDataFromAPI("https://api.crex24.com/CryptoExchangeService/BotPublic/ReturnTicker?request=[NamePairs=BTC_WAGE]",
true,
function(data){
var resultcrex = JSON.parse(data);
if (resultcrex !== "undefined") {
if (resultcrex) {
var pricecrex = resultcrex.Tickers[0].Last
}
else {
msg.reply("0")
}
}
}
);
console.log(pricecrex);
It is because Ajax requests are async. console.log() gets executed before response is received from request, and thus before setting value in pricecrex. So you were getting undefined.
var pricecrex;
getDataFromAPI("https://api.crex24.com/CryptoExchangeService/BotPublic/ReturnTicker?request=[NamePairs=BTC_WAGE]",
true, function(data) {
var resultcrex = JSON.parse(data);
if (resultcrex !== "undefined") {
if (resultcrex) {
pricecrex = resultcrex.Tickers[0].Last;
print(pricecrex);
}
else {
msg.reply("0")
}
}
}
);
function print(data) {
console.log(data);
}
The nature of Javascript is continue running code once an asynchronous function has been started. So you run getDataFromAPI(), and then while that's running, the interpreter goes to the next piece of code, which is your console.log(pricecrex).
So you can either run the console.log(pricecrex) directly in the callback, function(data){}, or to keep things cleaner, wrap your console.log() within a function and call that function from within your callback.
Example:
let someVar;
someAsync('someurl.com', (data) =>{
someVar = data;
callTheConsole()
})
function callTheConsole(){
console.log(someVar)
}
Instead of assigning the value to the variable. Pass it to another function. Thus the value passed to another function is not 'undefined'.
function validation(pricecrex){
console.log(pricecrex);
}
getDataFromAPI("https://api.crex24.com/CryptoExchangeService/BotPublic/ReturnTicker?request=[NamePairs=BTC_WAGE]",
true,
function(data){
var resultcrex = JSON.parse(data);
if (resultcrex !== "undefined") {
if (resultcrex) {
var pricecrex = resultcrex.Tickers[0].Last;
validation(pricecrex);
}
else {
msg.reply("0")
}
}
}
);
For more information, check out the below link. Detailed information with examples is available.
How to return the response from an asynchronous call??

See if username is taken or not, using ajax $.POST()?

This is the block that checks if returned value = 1:
} else if (validateUsername(username.val()) == 1) {
errors.html("That username already exists! Please use another.<span id='close'>X</span>");
errors.fadeIn("slow");
username.css("border", "solid 2px red");
}
If yes, username exists..
Now let's do the ajax work.
function validateUsername(username) {
$.post("js/ajax/ajax.php", { validateUsername : username }, function(data) {
return data;
});
}
This will send a request to ajax, and fill var data with the response.
if (isset($_POST['validateUsername']))
{
echo 1;
}
this is the ajax that will send a response, basically it's int 1 for now, for checking.
But, I always get undefined.
I mean, fireBug does say "request=1", but it looks like the if statement won't work.
If I just do return 1; manually without ajax, it will work.
Why is it doing that?
Ajax is asynchronous, so when you return data here :
function validateUsername(username) {
$.post("js/ajax/ajax.php", { validateUsername : username }, function(data) {
return data;
});
}
and try getting it here :
validateUsername(username.val()) == 1
it won't work, as the ajax call hasn't completed yet (and the return returns from the inner function only).
Instead you should do:
function validateUsername(username) {
return $.post("js/ajax/ajax.php", { validateUsername : username });
}
validateUsername(username.val()).done(function(data) {
if ($.trim(data) === 1) {
errors.html("That username already exists! Please use another.<span id='close'>X</span>");
errors.fadeIn("slow");
username.css("border", "solid 2px red");
}
});
Ajax functions are asynchronous. validateUsername() returns before the ajax call is complete (without a return value, which is why you see undefined).
Probably the most elegant way to handle this would be to refactor to return $.ajax... and work with the Deferred object that is returned.
AJAX stands for Asynchronous JavaScript And XML. Ignore the XML part, but the Asynchronous is what's biting you in the backside here.
Anything that depends on the result of an ajax call must be in the success handler, called by the success handler, or defined in such a way that it will only be run after the success handler.

Javascript rendering. How to write Javascript so it doesn't continue executing code before a function call has ended

Not sure if my question is subjective/objective but as a JavaScript newbie i'm encountering this problem quite a lot. So here I go.
I'm used to write C#, so my JavaScript structure looks like C#. And just that, that gives problems I think ;-)
Let's give a simple example where I met my problem again today:
MyLibrary.fn.InitAddEntityForm = function () {
$('a#btnAddEntity').click(function () {
//post data and receive object with guid and isPersisted boolean
var persistedObject = MyLibrary.fn.CheckAndSendAddEntityForm("name", "avatarurl.png");
console.log("test");
//check if persisted and go to next step
if (persistedObject.isPersisted) {
MyLibrary.fn.InitAddAnotherEntityForm(persistedObject.gdEntityId);
} else {
alert("Oops, something went wrong. Please call 911");
}
});
};
//////*****/////
//SOME FUNCTION THAT SENDS MY FORM AND RETURNS AN OBJECT WITH TRUE VALUE AND POSTED ENTITY ID
/////*****//////
MyLibrary.fn.CheckAndSendAddForm = function (txtName, ImageUrl) {
var postUrl = "/admin/add";
var persistedObject = new Object();
$.post(
postUrl,
{ Name: txtName, ImageUrl: txtImageUrl},
function (data) {
if (data.Status == 200) {
console.log("Post status:" + data.Message);
persistedObject.isPersisted = true;
persistedObject.gdEntityId = data.Data;
} else if (data.Status == 500) {
console.log("Failed to post entitiy");
} else {
console.log("Fault with Javascript");
}
}, "json"
);
return persistedObject;
};
Okay, thats it. Everything looks okay right? Browser says no.
I tried to debug it using firebug, looping over my code line by line, and that way the browser does what I want: Execute a new function to show the next panel in my wizard.
After placing a lot of Console.logs() in my code I figured out that this must be something about timing in JavaScript. In C# the code executes line by line, but apparently JavaScript doesn't.
By placing that Console.log("test") I noticed that "test" appeared in my console before "Post status: Success!".
So here's my question, how should I write my JavaScript code so I have control over the way the browser executes my code?
Should I really replace the code below to the end of my CheckAndSendAddEntityForm()?
//check if persisted and go to next step
if (persistedObject.isPersisted) {
MyLibrary.fn.InitAddAnotherEntityForm(persistedObject.gdEntityId);
} else {
alert("fout");
}
Is this how I have to write JavaScript: One big domino effect or am I just doing something wrong?
$.post is a shortcut for an AJAX call, AJAX is by definition asynchronous, which means it won't wait on a response before continuing processing. If you switch it to a regular AJAX() method, there is an async option you can set to false, which will make it behave as you are expecting.
Alternatively you can also define a function to execute on successful return of the AJAX request, in which you can call the next step in your process chain.
The AJAX call is asychronous; that means that the callback method exposes by $.post will be executed when the request completes, but your javascript will continue executing as soon as the invoke to $.post finishes. If you want to do something after the ajax call is done, you need to provide a callback method and do something else, ex:
MyLibrary.fn.CheckAndSendAddForm = function (txtName, ImageUrl, callback) {
var postUrl = "/admin/add";
var persistedObject = new Object();
$.post(
postUrl,
{ Name: txtName, ImageUrl: txtImageUrl},
function (data) {
if (data.Status == 200) {
console.log("Post status:" + data.Message);
persistedObject.isPersisted = true;
persistedObject.gdEntityId = data.Data;
} else if (data.Status == 500) {
console.log("Failed to post entitiy");
} else {
console.log("Fault with Javascript");
}
callback(); // This is where you return flow to your caller
}, "json"
);
};
Then you invoke like so:
var persistedObject = MyLibrary.fn.CheckAndSendAddEntityForm("name", "avatarurl.png", function()
{
console.log("test");
//check if persisted and go to next step
if (persistedObject.isPersisted) {
MyLibrary.fn.InitAddAnotherEntityForm(persistedObject .gdPronoId);
} else {
alert("Oops, something went wrong. Please call 911");
}
});
JavaScript is single-threaded. If you have asynchronous functionality, a simple boolean semaphore variable will help not to allow invocations of a function while some processes are running.
If you want to execute asynchronous tasks one by one (like a domino line), you will need to use callback functions.
What you're encountering is the "asynchronous" bit of AJAX. If you want to physically (as in the line line by line in the Javascript file) you can use the .success,.pipe or .done jQuery methods to add a callback to process the data further. Don't embed your callbacks if you can help it, or you will get a "domino effect" as you call it.

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/

Categories

Resources