jQuery: Wait for function - javascript

I have 2 functions in jQuery and one needs data the other is loading from a DB via php and json(this part works).
My problem is that the first one starts berfore the data is loaded.
How con I fix this?
Here a little code to understand:
function loadBody(){
//Create an calendar of selectet month with classes to Events
}
function loadEvents(){
//loads Events from DB with php and json and puts them into an array
}
I tryed e.g. the following:
function loadCal(){
$.when(loadEvents()).done(loadBody());
}

loadBody not loadBody() : you were executing loadBody instead of giving the callback.
function loadCal(){
$.when(loadEvents()).done(loadBody);
}

$when expects a promise to be returned by the method passed into it. You need to make sure loadEvents method returns a promise.
function loadEvents(){
return $.ajax({
//Make ajax call to loads Events from DB
});
}

function loadBody(){
//Create an calendar of selectet month with classes to Events
}
function loadEvents(){
//loads Events from DB with php and json and puts them into an array
loadBody();//call here after load complete
}
function loadCal(){
loadEvents();
}

the problem is that loadEvents immediatelly returns, so loadBody is called before it finishes to load the file asynchronously. Can you post the full loadCal function? In it you'll have some callback, that saves the data to the array. There you could call loadBody(). I know it's not as nice as you tried, but it should work :)

You can try this:
var loadEvents = function (callback) {
// do stuff...
callback()
};
var loadBody = function () {
loadEvents(function () {
// loadEvents function is already done here...
// continue with loadBody function
})
};

Related

Calling function by string not working

I'm trying to write a js function that triggers another, variable, function when complete. I figured I could do this by passing the second function's name as a string, but I can't get it to work. Here's my code:
logMeIn('likeThisPost');
function logMeIn(callBack) {
//First function content
$.post("/ajaxurl/",
{
login_id: login_id,
intent: 'login'
},
function(){
console.log('Logged in, refreshing header');
$.post("/secondajaxurl/",{},
function(data){
//success
if(typeof callBack!=='undefined') {
window[callBack]();
}
}
);
}
);
});
}
This should, according to my thinking, run likeThisPost after successfully completing both ajax calls in logMeIn, but instead I get this error:
window[callBack] is not a function
The function I'm calling on success definitley exists, and besides which, it doesn't look like it's even trying to call that function, but it's treating callBack as literal rather than a string.
I'm using jQuery and have everything wrapped in a $. Where am I going wrong?
With thanks to Jonas W and Rory McCrossan, the answer was to change the passed function to the function name, rather than a string, and then call the function directly rather than using window.
So logMeIn(likeThisPost) instead of logMeIn("likeThisPost") and callBack(); rather than window[callBack]();.
Thanks!

Add event listener of a method present in another js file

I am accessing few methods written in another js file. So i'm accessing them like this:
file1:
function minit() {
this.addval = function(val1, val2) {
return val1 + val2;
}
function autoexecute(d) {
//do something here//
//raise event//
}
};
file2:
var con = new minit();
var result = con.addval(2, 3);
/*
con.autoexecute(function(d) { //Wanna do something like this
alert(d);
});
*/
Above things are working as expected, getting result..
Now, Suppose autoexecute(d) method is invoking automatically after a time interval. How can i know if the method is executed ?
So that, I want to create an event(in file2) of autoexecute(d)(in file1).
UPDATE:
I hope this example will help you to understand the issue..
company.js //this is the main file which will be used as a reference in ui.html
function hello(personname) { //this method will invoke automatically after 1 minute..
}
ui.html
<script src="company.js"></script>
<script>
$(document).ready(function() {
function bye(personame) { //this method will be called automatically if hello method invoked.... personame is the argument passed from hello method//
alert("comany.js -> hello function is executed");
}
});
</script>
You can only do this if the functions have the same scope (global scope is the best case scenario). If the autoexecute function has local scope then you cannot to do it.
In essence, override the original function like this...
// keep a reference to the original function
var _autoexecute = autoexecute;
// override the original function with your new one
function autoexecute(d) {
alert("before autoexecute"); // fired before the original autoexecute
_autoexecute(d); // call the original autoexecute function
alert("after autoexecute"); // fired after the original autoexecute
}
Now, whenever autotexecute is called it will call your new function which can handle both before and after events, as well as calling the original function. Just remove the (horrible) alerts and replace with event handlers as required.
To my knowledge, and someone should correct me if I am wrong, there is no way (at least without some library) to detect a function being fired in javascript. Function executions do not fire an event that other functions can 'handle' in that that sense.
In your example you wanted a function to automatically fire after the other function has fired, all you need to do is call the function you want to fire at the end of the one that was "fired" in the first place. Confusing but hope this helps.
function handler(){
alert("main function was fired!");
}
function main(){
//Code of main goes here and then at the end just add:
handler();
}
Now when your "main" has finished its work it will call upon the handler function.
Regardless of where you define the handler function, which can be a different file or same file, so long as it is reachable from within the main's scope, it will be fired at the end of it. It can even be declared after main has been declared, so long as it is declared before main is fired.

get return value of jQuery get().done() function

I have the code:
function images(){
$.get("page").done(function(data) {
manipulation to get required data
});
}
and I have tried to get a variable from inside the get function, using global variables, return values, and functions outside of the function. Does anyone know how I would be able to get a variable from inside the get function and return it as a value if I called images()?
You can't do it since $.get() executes asynchronously. The solution is to use a callback in images to process the value returned by $.get()
function images(callback){
$.get("page").done(function(data) {
manipulation to get required data
var d = ? //manipulated data that was supposed to be returned
callback(d);
});
}
then
//calls images
images(function(data){
//this method will get called when the $.get() is completed, and data will be the value passed to callback(?) in the done function
})
More: read this

Can we save jquery POST/GET callback function's data and status in a variable for further use?

I want to save the value of data and status in a variable and use it after the closing brackets of jquery GET/POST function.But alert comes only when it is inside .get braces.
$(document).ready(function(){
$.get("demo_test.asp",function(data,status){
v = data;
});
alert("Data:"+v);
});
As Jasper said, your alert is being triggered before the request is complete (async!). So, you have two options:
Do your logic inside the callback:
$.get("demo_test.asp",function(data,status){
v = data;
alert("Data:"+v);
//Process stuff here
});
Or pass the received data onto another function and work with it there
$.get("demo_test.asp",function(data,status){
v = data;
doStuff(v);
});
function doStuff(param) {
console.log(param);
}
You're absolutely correct; the code is working as it should... here's why:
The page loads and starts running code, it then hits the .get command and then keeps running, obviously making it to the 'alert' you have next. Since the .get function is still working on fetching the data before your page makes it to the 'alert' part... there's nothing to prompt.
You might want to string things together after the .get, using deferred objects. Look into: http://api.jquery.com/deferred.always/
This is a way of tacking on another function inside of the one fetching your data, so they depend on each other.
Simple answer, yes, you can store the data in a global variable and access it elsewhere. However, you must wait until it is ready.
The better way to do it is to instead store the jqXHR globally and simply add a done callback to it when you need to access the data.
var reqDemoTest = $.get(...);
//... some time later...
reqDemoTest.done(function(data){
console.log(data);
});

Call external function from ajax() success function

I have a function defined within $(document).ready() which arranges some JSON into HTML using DoT.js:
$(document).ready(function() {
function arrangeResults(jsonObject, templateFunc) {
$(jsonObject).each(function(i, item) {
$.each(item, function(i2, item2) {
$('#ajax-article-list .col-left').append( templateFunc(item2) );
});
});
};
I have an AJAX call on page load which executes this function to display the data:
$.post(ajaxRequestURL, function(data) {
arrangeResults(ajaxData.pages, projectTemplate);
}
and this works fine.
However I have a set of links which requests more/different JSON data using the click() handler, which should execute arrangeResults again with the returned data, but the function isn't executed:
$('nav.filters a').click(function(ev) {
ev.preventDefault();
$.post(ajaxRequestURL, function(data) {
ajaxData = parseJSON(data);
arrangeResults(ajaxData.pages, projectTemplate);
}
}
This doesn't work. The data is all valid, and everything works if I take the contents of arrangeResults and put them directly within the script, but I was hoping to follow DRY and have an external function that I could call upon both on pageload and when one of the filters is clicked.
I guess it's because the AJAX call is asynchronous but since the function call is within success I presumed this wouldn't cause a problem.
If I understand it right, you have first AJAX call inside $(document).ready() block.
So it could be because you have arrangeResults function inside your $(document).ready() block. Because of that you are unable to call the function from other part of JScript.
Define it like that:
function arrangeResults(jsonObject, templateFunc) {
...
}
$(document).ready(function() {
...
);
and so on.
Correct me if I wrong, please.

Categories

Resources