I'm having trouble getting the value from this function, I'm not sure why but is returning empty. I debug it with firebug and it run two times, the first one return empty and then the second one return the value.
Any idea how I can correct this.
function validation() {
if (val()); {
alert("Error");
} else {
alert("Pass");
}
}
function val() {
var answer;
dojo.xhrGet({
url: "ValodS?option=12",
handleAs: "text",
load: function (response) {
if (response == 'Pass') {
answer = false;
} else {
answer = true;
}
}
});
return answer;
}
The problem is that you're returning answer before it is ever being sent (the AJAX request is run in the backround without blocking the calling code.
The easiest solution would be to have the caller pass a callback function to your function. You could then call the callback function inside of the load handler (thus passing the data that way).
When val returns, answer is not assigned. You are calling an asynch operation that sends off a http request. The control flow then continues, and when the http request eventually is finished, the anonymous function you defined, that assigns answer, is executed.
You have an extra ; after your if
Change the first line from
if (val());
to
if (val())
Related
result is undefined why? how to solve this problem. assign variable and i need to use that variable before
<script type="text/javascript">
function getAdvanceAmount (element, callback) {
if (element === '' || !window.XMLHttpRequest) return
var xhr = new XMLHttpRequest()
xhr.onreadystatechange = function () {
if (xhr.status === 200 && xhr.readyState === 4) {
callback(xhr.responseText)
}
}
xhr.open('GET', 'get_advance_amount.php?q=' + element, true)
xhr.send()
}
function get_value()
{
getAdvanceAmount('1',function (karat) {
console.log(karat)
k1=karat;
})
alert(k1);
}
</script>
<button onclick="get_value()">Click</button>
It would work fine, if you change your as follows:
Your Code:
function get_value()
{
getAdvanceAmount('1',function (karat) {
console.log(karat)
k1=karat;
})
alert(k1);
}
Change it as follows:
function get_value()
{
getAdvanceAmount('1',function (karat) {
console.log(karat)
alert(karat);
})
}
Since this is async call your alerting code should also be in the callback function.
For better crossbrowser compatibility, not only with IE6/7, but also to cover some browser-specific memory leaks or bugs, and also for less verbosity with firing ajaxical requests, you could use jQuery.
$.get('get_advance_amount.php?q=' + element, function(responseText) {
alert(responseText);
});
Hope this will help you.
You are calling the getAdvanceAmount function and you pass some parameters to it, namely an element and a function called callback. getAdvanceAmount sends an AJAX request and when it receives a response, executes the callback. Inside the callback k1 is initialized.
After getAdvanceAmount is executed, there is an attempt to use k1, however, it is unsuccessful. The reason is that the callback was not executed yet by the time k1's value is tried to be used. This is what happens:
getAdvanceAmount is called
an AJAX request is sent
k1's value is attempted to be used
the server receives the request
the server parses the request
the server sends the response
the browser receives the response
the browser calls the callback which initializes k1
You simply tried to use k1's value chronologically before it was initialized, due to the mistaken assumption that using it after calling getAdvanceAmount, which is responsible for its initialization guarantees that it will be initialized, which is clearly not the case. Try to use k1 in the callback and you will see it was properly initialized.
The issue here is that the XMLHttpRequest is asynchronous request, so it will take sometime to finish, and call your callback function.
On the other hand, you are calling alert immediately after click event firing, so the callback is not fired yet, and assigned the karat to k1 variable.
getAdvanceAmount('1',function (karat) {
console.log(karat)
useKaratValue(karat);
})
function useKaratValue(karat) {
// Make use of the value here...
}
This will solve the issue, and alert after getting karat value.
function outer() {
$(['hi', 'there']).each(function(idx, e) {
console.log(e);
return;
});
alert("I don't want to be called");
}
function outer() {
$.get('http://test.com', function (data) {
console.log(data)
return; // I want to terminate the entire outer() function here.
});
alert("I don't want to be called");
}
What's the convention of breaking out of nested functions in cases like this? When using for loops, returning inside them terminates the entire function that encloses them. However, since $.each() is an individual function call, returning from it only ends itself, not the outer function. I could simply return twice, once inside and once outside in that case, but I am not sure how I would deal with $.ajax() because it is necessary to terminate the function only when I get a successful response.
Here is a summary of how it all works.
.each()
return true; // skips to the next iteration of .each()
return false; // exits the .each() loop
In short there's no way of breaking out of the function containing .each() in a single statement.
$.get()
return [true|false]; // makes no sense at all.
As the return in $.get() does not get executed until the ajax call is complete, it wont serve much purpose. Even when you make a synchronous ajax call, a return statement in the success callback still does not do anything substantive. Think of a return from a function as a value to be assigned to the calling statement.
What's making it necessary to break out of your functions?
For $.each(), you can stop the iteration with return false; in the callback, as described in the jQuery documentation.
This won't return from the calling function, but you can set a flag and test it in the outer function.
If you want an easy way to return from the outer function from inside the loop, you're better off with a simple for loop:
var array = [ 'hi', 'there' ];
for( var i = 0; i < array.length; ++i ) {
var e = array[i];
console.log(e);
return;
}
alert("I don't want to be called");
For $.get(), you should add some console.log() calls to your code and observe the order in which they are called:
function outer() {
console.log( 'in outer before $.get is called' );
$.get('http://test.com', function (data) {
console.log( 'inside $.get callback' );
});
console.log( 'in outer after $.get returns' );
}
Now what you'll notice is the order of the log messages:
in outer before $.get is called
in outer after $.get returns
inside $.get callback
See how the callback is the last thing? It's called after the outer function finishes. Therefore, there is nothing this callback can do to prevent the rest of outer from executing.
So you need to think some more about what you need to do and figure out a different way to accomplish it.
If you use $.ajax() instead of the short hand $.get(), it is possible to specify that it be executed synchronously.
$.ajax({
url: 'http://test.com',
success: function (data) {
},
async: false
});
Typically, when you want to make a decision based on the return value of a function you have it return a value and then use a conditional statement to determine what happens next.
I basically want to have a function which is GET'ing a page and then returns a result based on that, this leads to the following problem:
All GET methods are using a callback function, meaning that the function will end before the result is there. How do I pause the thread until the callback is fired and then return the result of the callback in my main function?
function someFunction(){
$.get(
"blabla.php",
function(data) {
// This data is supposed to be returned by "someFunction"
}
)
return //the data we retrieved from 'blabla.php'
}
How would you accomplish this?
EDIT: I know this concept from lua, however I'm not entirely sure if someone would call it "Yielding a function result". Please correct me, if I'm wrong.
Correct answer: don't. Asynchronous is the correct way to do HTTP requests. However, there are cases when you want to block while waiting on a result, so in those cases:
Use the async parameter.
function somefunction() {
var retVal;
$.ajax({
url: "blabla.php",
success: function(data) {
// modify data here
retVal = data;
},
async: false
});
return retVal;
}
Instead of returning something from your function why not just take a callback as an argument?
function someFunction(callback) {
$.get("blabla.php", function (data) {
callback(data);
});
// Or simply $.get("blabla.php", callback) if the data need not be modified before calling the callback.
}
Which can then be used like so:
someFunction(function (data) {
alert("Data received!");
});
JavaScript is single-threaded, so this is really the only reasonable way to accomplish something like this without blocking the entire script.
Hey everyone - I'm having some difficulties properly getting a return value from one of my Javascript callback functions, and it looks to be dependent on a race condition, but I'm not sure:
JSOBJ.container = function() {
return {
getName: function() {
var value;
companyfn.app.getInfo(callback);
function callback(foo) {
// alert("gets here");
if (foo.hadError()) {
alert("Error found!");
} else {
value = foo.getField(companyfn.app.Field.SUB_DOMAIN);
}
// alert('callback: ' + value);
}
return value;
}
}
}();
JSOBJ.main = function () {
return {
init: function() {
alert(JSOBJ.container.getName());
}
};
}();
In JSOBJ.main.init(); above, I'm trying to get the proper value, but when I run my code, I almost always get a return value of undefined. When I uncomment my alert statements in JSOBJ.container.getName(), the getName function seems to run without invoking the callback, the alert pops up, and then the getName function gets called. So it feels like a race condition, and I want to say it has to do with closures, but I'm not sure how to implement it properly so it "waits" for getField to return a value. Can anyone help?
Pass the defined function to your ajax call (I am assuming that is an ajax call) or pass it as an anonymous lambda. Your callback function is created on the fly after the call that passes it.
You cannot make your function block until the callback finishes without completely freezing the browser, which is not a good idea.
You need to make your getName function take a callback and give the callback its value, just like companyfn.app.getInfo.
I have a problem returning a variable in my function, the below script works fine:
function sessionStatus(){
$(document).ready(function(){
$.getJSON(scriptRoot+"sessionStatus.php",function(status){
alert(status);
});
});
}
sessionStatus();
Bet when I try the following I get a message box with the message "undefined":
function sessionStatus(){
$(document).ready(function(){
$.getJSON(scriptRoot+"sessionStatus.php",function(status){
return status;
});
});
}
alert(sessionStatus());
This is really bugging me, I just can't seem to see what I've done wrong.
There are two things you should know:
1: the JSON thing is asynchronous, so the function call to sessionStatus could already be done when the JSON is still being fetched. The following would work:
function sessionStatus(callback){
$(document).ready(function(){
$.getJSON(scriptRoot + "sessionStatus.php", function(status){
callback(status);
});
});
}
sessionStatus(function(s){alert(s);});
or rather:
function sessionStatus(callback){
$(document).ready(function(){
$.getJSON(scriptRoot + "sessionStatus.php", callback);
});
}
sessionStatus(function(s){alert(s);});
2: even when it would be synchronous, you are only giving a return value from the inner function, so the sessionStatus would return nothing. Check out this code (not related to your JSON thing):
function do() {
var x = 0;
(function(){
x = 2;
})();
return x;
}
or:
function do() {
var x = (function(){
return 2;
})();
return x;
}
Both return 2. Hopefully this explains a bit.
Your function sessionStatus() doesn't return anything, hence the alert says undefined.
All the function does is set thing up for the AJAX call to happen once the page loads - nothing actually happens within sessionStatus() that could be returned.
The code in function(status) { ...} doesn't get run until the AJAX call to the server returns a value, and that AJAX call doesn't get sent until the page loads.
You ought to read up on what $.getJSON() and $(document).ready() actually do, because you're going to continue to get confusing behaviour until you understand them properly.
Your sessionStatus() function never returns anything. It sets a function to run later, and that function returns something, but that's not anything to do with sessionStatus()
You're returning a value when the document ready event is done. Where is your value supposed to go? The jQuery object doesn't know what to do with it.
The function sessionStatus just sets up the event listener for $(document).ready() and then returns without returning a value. That's the undefined you see.
Later when $(document).ready() fires it calls the ajax which if it succeeds returns the status, but nothing is receiving that status.
function sessionStatusCallback(status)
{
alert(status);
}
function sessionStatus(){
$(document).ready(function(){
$.getJSON(scriptRoot+"sessionStatus.php",function(status){
sessionStatusCallback(status);
});
});
}
sessionStatus();
Your function is being called asynchronously -- actually after two asynchronous calls, made via .ready() and .getJSON(). In such a case there is no available return value, instead you have to use a callback, as in the above, to process the response.
Though I should note that the function passed to getJSON in the above already is a callback. You could change that function definition to just be "sessionStatusCallback" and it would call the above callback once the JSON was ready, and you could continue to process there. Or...continue your processing in the current callback (it's a matter of style whether to use a function reference or declare the anonymous function right there in the .getJSON() call)
Functions should never be included in a jQuery(document).ready function. Separate them, so you don´t have side effects you don´t want to have. How do you want to call the session status? And witch function should get the return value?