Accessing a javascript variable outside of a jQuery statement - javascript

$.getJSON("../../index.php/churchlocator/base", function(data) {
base_url = data.base;
});
alert(base_url);
How can I get base_url in the above code to be accessible outside of the getJSON var?

The right answer here is to put all code that references the result of the ajax call in the success handler for the ajax call. Do not use global variables for this:
$.getJSON("../../index.php/churchlocator/base", function(data) {
var base_url = data.base;
alert(base_url);
// or you may call some other function here and pass it the data
myFunction(base_url);
});
Ajax calls are "asynchronous" (that's what the A in Ajax stands for). What that means is that they complete sometime in the future and your other javascript continues running. When they complete, they will call their success handler. As such, the ONLY way you can know when the data has been returned from the Ajax call is by either placing code inside the success handler to operate on the returned data or by calling a function from that success handler and passing it the data.
This is asynchronous programming and you MUST use this model if you program with asynchronous functionality of any kind. You cannot use traditional sequential programming with asynchronous function calls.

Related

Callback function for asynch request

The below code gets a state from latitude/longitude coordinates. How can I extract the value "result.body.region" from the scope of the anonymous function and use it in a higher scope?
latitude=tweets[0].latitude
longitude=tweets[0].longitude
var Request = unirest.get("https://montanaflynn-geocoder.p.mashape.com/reverse?latitude="+myobj.latitude+"&longitude="+myobj.longitude)
.header("X-Mashape-Key", "xxxxxxxxxxxxxxxxxxx")
.header("Accept", "application/json")
.end(function (result) {
state = result.body.region
});
What I want to do is write a callback function that will wait for the asynch request to finish and use that information in a different scope. I am self taught on javascript so I am struggling to understand callbacks. How can I do this?
The code you have already will do that.
You are probably trying to read the value of state before the callback has fired.
This is why we normally put the code to process the data in the callback: to make sure it runs after the asynchronous event has occurred.

jQuery's Request To Javascript Function

Okay so look at these to alert()s. Here is the full code:
function OfficialFacebookLikes(Title)
{
$.getJSON('https://graph.facebook.com/'+Title, function(data) {
alert(data['likes'].toString()); //<<temp
return data['likes'].toString();
});
}
$(document).ready(function(){
$('.ui-btn').click(function(){ //cocacola
var LikeCount = OfficialFacebookLikes("cocacola");
alert(LikeCount);
});
});
Why does
alert(LikeCount)
display (which is "undefined" when displayed) before
alert(data['likes'].toString())
I called the function OfficialFacebookLikes before I called the alert(LikeCount). Could someone please explain why this is occurring. If my thought process isn't making since.. I'm use to coding in C++.
This is an asynchronous Ajax call. You won't have data available until the call returns. In your document ready code, you are attempting to alert the call immediately.
Instead, do whatever you need to do with the result set in the callback handler of the ajax:
$.getJSON('https://graph.facebook.com/'+Title, function(data) {
doSomethingWithMy(data);
});
The .getJSON function is asynchronous, this means that it needs a callback to call when it's finished, otherwise you'll never know when the function has been completed. Asynchronous functions run separately from the rest of the code.
When you call OfficialFacebookLikes("cocacola") it will call the .getJSON function. Now the .getJSON functions starts by its own and doesn't stop the script, so right after calling OfficialFacebookLikes("cocacola"), the next line of code is executed, which is actually alert(LikeCount). But LikeCount has not yet been defined, since that .getJSON is still working.
When .getJSON finishes working the callback function given in $.getJSON(..., function() {... }) gets executed, and then the LikeCount variable gets defined. So if you want to alert LikeCount you have to put the alert() inside the callback of .getJSON.

Execute a method whenever some method has finished executing completely

I've a javascript method defined as follows:
updtCrtEdtPage = function() {PrimeFaces.ab({source:'j_id_ev',formId:'j_id_es',process:'typeNewLOB_in lobIdForEdit j_id_ev',update:'createLOBFullPagePanel',oncomplete:function(xhr,status,args){prepareForCrtEdtFullPage();},params:arguments[0]});}
I want to execute certain method (afterComplete()) whenever this method has finished executing. (This method actually initiates an ajax request & appends the received HTML data on the DOM). So I want my afterComplete() method to be executed whenever ajax response has been received.
I cannot directly do like:
updtCrtEdtPage();
afterComplete();
as this would call the afterComplete() soon after ajax request is initiated & not completely finished executing yet.
Is there any JS/ jQuery way I could do that ?
You could pass afterComplete as a parameter so your function can call it when the ajax call is complete. Something like this...
updtCrtEdtPage = function(callback) {
PrimeFaces.ab({
source:'j_id_ev',
formId:'j_id_es',
process:'typeNewLOB_in lobIdForEdit j_id_ev',
update:'createLOBFullPagePanel',
oncomplete:function(xhr,status,args){
prepareForCrtEdtFullPage();
callback();
},
params:arguments[0]
});
}
updtCrtEdtPage(afterComplete);
Since you say you can't modify updtCrtEdtPage, but you can modify prepareForCrtEdtFullPage I'd suggest using a global variable to determine which callback function to call when the method is complete...
updtCrtEdtPageCallback = afterComplete;
and then in prepareForCrtEdtFullPage just add the last line...
updtCrtEdtPageCallback();
The first method is tidier, but the second will suffice for your particular situation.
your updtCrtEdtPage = function() has an oncomplete callback which is called when the ajax response has been received, add your afterComplete function in that callback and it will execute after the ajax request has been completed.
oncomplete:function(xhr,status,args){
prepareForCrtEdtFullPage();
afterComplete()
}

How to make function that returns it's inner-function's value?

It's probably obvious to you, but I can't figure it out.
I need to make function that returns it's inner-function's value. In other words, I have function get_users() that must return JSON object. That JSON object is got by $.post (built-in jQuery).
function get_users() {
return
$.post(
url_base + 'travel/trip/get_users/' + trip_id,
function(response) {
return response;
},
'json'
);
}
(above is what I tried to do, but it returned undefined - what a surprise)
Because of variable scope, I cannot just make variable in inner-function because it won't be visible in main function. I don't want to use global variables neither. Looking for better solution!
Thanks in any advice!
Why are you fighting against the asynchronous nature of AJAX? When you do AJAX you should get accustomed to work with events and callbacks instead of writing sequential code. You can't return the inner contents. The simple reason for this is that this inner function could execute much later than the outer function. So the outer function will return a result much before the success callback executes.
So here's the correct way:
function get_users() {
$.post(
url_base + 'travel/trip/get_users/' + trip_id,
function(response) {
// instead of trying to return anything here
// simply do something with the response
// Depending on what the server sent you there
// will be different ways.
// Here you could also call some other custom function
// and pass it the response
}
'json'
);
}
You can't return values from ajax calls. (Without setting async false, but that wouldn't really be ajax)
By the time you hit the inner return, the outer function has already completed
You will need to use a callback to process the users.
get_users(function(response) { // this anonymous function is passed in as a parameter
// do something with the response
});
function get_users(callback) {
$.post(
url_base + 'travel/trip/get_users/' + trip_id,
function(response) {
// call the passed in function and pass in the response as a parameter
callback(response);
},
json'
);
}
You need a primer on how asynchronous ajax calls work.
When you call $.post(), it starts a networking call to do the post and immediately returns from the $.post() call and continues executing the rest of your javascript. It will even exit your function get_users() right away.
But, the ajax call is not yet done - it's still in progress. Some time later, the ajax call will finish and when that happens the success handler for the ajax call that you have defined as function(response) {...} will get called. Only then, at that later time, is the response value from the ajax call known.
This is what asynchronous ajax means. You cannot write a call like get_users() and expect it to get the users and return with them. Instead, you have to make use of callback functions that will get called some time later (when the ajax has completed) and you can continue the path of your code then. Yes, this is inconvenient, but it's how things work in javascript with asynchronous ajax calls. The benefit of asynchronous ajax calls is that the browser and other javascript code can be fully live while the ajax call is underway. The cost of asynchronous ajax calls is that coding for them is more complicated.
You have a number of choices for how to deal with this complication. First off, you can make your get_users() call and then just continue the programming sequence that you want to carry out in the internal callback inside of get_users() since that's the only place that the response (the actual users) is known. If you're only using get_users() in one place in your code, then that could work fine. It would look like this:
function get_users() {
$.post(
url_base + 'travel/trip/get_users/' + trip_id,
function(response) {
// process the user list here and continue whatever other code you
// need that deals with the user list
},
'json'
);
}
If you need to use get_users() in several different places for different purposes, then you can change it to take a callback itself and let the post call just call that callback when the ajax call is done. You would then complete your processing of the response in that callback function:
function get_users(callback) {
$.post(
url_base + 'travel/trip/get_users/' + trip_id,
callback,
'json'
);
}
In this second option you could call get_users() like this:
get_users(function(response) {
// process the user list here and continue whatever other code you
// need that deals with the user list
});
There are even more advanced options available using jQuery's deferred object.

Retrieve data from $.ajax function in javascript

I have used $.ajax function to fetch data from C# in asp.net MVC3.0, Now I want is to get the value from the success function of $.ajax and used it in another function defining global variable and putting the result in it is not working so please let me know how can I get the value.
Invoke a callback function from within the success function. Most likely you are treating everything as synchronous when infact Ajax is asynchronous.
Low down dirty way would probably be to specify async:false

Categories