$.get and get value - javascript

function get(){
$.get('/get.php', function(data) {
alert('one: ' + data)
return data;
});
}
var test = get();
alert('two:' + test);
In get.php is:
<?php echo "number"; ?>
why one alert show me
one: number
but two alert show me
two: undefined
How can i get this value outside function?

The $.get call is asynchronous. That means that you pass it a callback (your function(data) { ... }, which gets executed with the result from the call. You can't return from inside that callback - when it is executed, your outer function (doing the $.get) has already returned. Instead, try something like this:
// callback will be executed with the response from your GET request
function get(callback){
$.get('/get.php', callback);
}
// Call get with a callback receiving the response
get(function(data) {
alert('two:' + data);
});
This is a pattern you will have to get used to when writing javascript code.

Your return data is returning from the ajax anonymous function, not from the get() function.

This is because when this statement is called, the function get() has already returned before the callback of $.get() has been executed. Keep in mind that ajax requests are asynchronous.
What are the execution steps:
Call get()
Ajax request with $.get() is initiated
get() returns
ajax request ends and callback of $.get() is executed
To handle this case, you would typically pass the callback to execute as a parameter:
function get(callback) {
$.get('/get.php', function(data) {
if ($.isFunction(callback)) {
callback(data);
}
});
}

Related

Ajax call (b) within callback of another ajax call (a) executes before (a) completes

I have an ajax call, let's say callback (b), within the callback of another ajax call, let's say callback (a). In my code (b) depends on the success of ajax call (a). However, contrary to what I expected, ajax call (b) still completes successfully before the parent ajax call (a) completes.
Javascript
var ajaxAdata; //global
ajaxA(ajaxB(1));
function ajaxA(callback){
FB.api('/me', function(response) { //ajax call(a)
ajaxAdata = response.id;
callback(); // this completes before ajax call(a) completes
}
}
ajaxB = function(isPublic) {
.getJSON(){ //ajax call (b)
console.log(ajaxAdata); // necessary ajaxAdata returns undefined
}
}
Am I ignorant of something in regards to javascript here? I've read in many places that a callback function is the right way to handle asynch calls. In this case, does javascript still read ahead into the ajaxB function and starts to execute .getJSON() before the FB.api() call is complete?
Your call
ajaxA(ajaxB(1));
executes ajaxB(1) before ajaxA is even invoked to provide the value of parameter for ajaxA.
It should be
ajaxA(ajaxB, 1);
and
function ajaxA(callback, param){
FB.api('/me', function(response) { //ajax call(a)
ajaxAdata = response.id;
callback(param); // this completes before ajax call(a) completes
}
}
It should be:
ajaxA(function() {ajaxB(1);} );
You were calling ajaxB() first, and passing its return value (undefined) as the callback argument to ajaxA(). You want to pass a function that calls ajaxB() as the callback.
ajaxA(ajaxB(1));
Is actually executing ajaxB,, and then using the result to pass as an argument to ajaxA.
You need to pass in the function, not the result.
So try
ajaxA(ajaxB);
Then, in ajaxA, pass in your argument to the callback with
callback(1);
You are executing ajaxB here:
ajaxB(1)
I think what you want to do is either return a function from ajaxB or find a way to pass the isPublic flag to your ajaxA function like:
ajaxA(ajaxB, 1);
function ajaxA(callback, isPublic){
FB.api('/me', function(response) { //ajax call(a)
ajaxAdata = response.id;
callback(isPublic); // this completes before ajax call(a) completes
}
}

Possible to set the value of a javascript function parameter in a callback?

That title was a mouthful. Here's what I'm trying to do in code below. The callback in this case is in the jQuery $.get function.
function getMapMarkup(loadUrl, myVar) {
me = myVar;
$.get(
loadUrl,
{ var1: "hello", var2: "world" },
function(responseText) {
me = responseText;
myVar = me; //doesn't work.
},
"html"
);
}
Is there a way to change the value of myVar in the function(responseText) callback, so I can use it in my program later on? Or is there another (better) way to go about what I'm trying to do?
If by later on you mean immediately after the $.get call then no, there is no way because AJAX is asynchronous and the $.get returns immediately and the success callback can be executed much later. The only reliable way to know when this happens is to put the code that depends on its result inside the success callback. You could also call some other function inside the success callback passing it the result of the AJAX call.
Most likely you are accessing myVar before the callback is executed.
$.get makes an AJAX call which is asynchronous and so the callback function will be called later after your server responded and so any immediate access to myVar will not have the updated value.

Function not returning value

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

Ajax response handling and assigning to variable

Hello i have some problem with ajax response handling
i have a global function call() that makes ajax calls and just returns json response:
function call(request_url,params) {
$.post(request_url,params,function(response) {
return response;
},'json');
}
After that i have an object GetServices that uses global function call()
var GetServices = {
service_url:"http://xxx.com/req.php",
getCurrency:function() {
var resp = call(this.service_url,{act:'getCurrency'});
return resp;
}
}
I want GetServices.getCurrency() to return the ajax response but it returns undefined. Javascript assigns value undefined to it and after that finishes ajax call.
Please help me how to fix this.
This pattern will not work because the call is still executing while the resp variable is being set, therefore resp will always be null.
The alternative is to pass a delegate function to the call function to run on $.post success, or change the $.post to be a synchronous $.ajax call.
Its an asynchronous call...
Therefore it will make a call and resume its processing. You will get the value somewhere after making the call. It depends on various factors. For eg, your server's response time.
The easiest way is to call the target function (the function to which you want to pass this ajax value to) from your success handler of $.post()
For eg
function call(request_url,params) {
$.post(request_url,params,function(response) {
yourTargetFunction(response); // instead of returning the value from this
},'json');
}

function scope javascript, returning outside of function

I have this function in JS:
function redGet(key){
var response;
red.get(key, function (err, reply) {
response = reply;
});
return response;
}
This keeps returning undefined on :
console.log(redGet("hello"));
Assuming that red.get() is an AJAX-like asynchronous function, the problem is that you're expecting it to operate synchronously. You won't be able to get the reply value until the asynchronous operation is complete, which means that anything that relies on this value must be invoked in the callback function.
For example:
function redGet(key){
red.get(key, function (err, reply) {
// do whatever you need to do with the reply value here
console.log(reply);
});
}
redGet("hello");
You don't say what red is, but most likely its .get() method is asynchronous, which means execution of redGet() continues immediately with return response at which point the value is undefined. It is only later after .get() finishes its processing that your callback function is executed to set response - reply.
As with any asynchronous code (also found in Ajax, database access, etc. code) you will likely need to restructure your code such that whatever depends on the return value from .get() is executed in your callback function (or in other functions called from the callback).
I guess that your red.get is an ajax function call (which is asynchronous)
What happen is your console.log(..) get executed before red.get(..) get the result back.
If you still want it to work you have to pass a callback to it e.g.
redGet('hello', function(res) {
alert(res)
})
// then in your code
function redGet(key, cb){
red.get(key, function (err, reply) {
cb(reply)
});
}
You can use jquery $.ajax function with async:false option. May be red variable uses jquery $.ajax function inside and you can do this. But it will affect the performance.
More information on http://api.jquery.com/jQuery.ajax/

Categories

Resources