Raj
Raj

Reputation: 23

Calling two user defined functions in jquery

Hi I am trying to call two user defined functions and expecting the first one has to execute first and then the second one.. but they are executing simultaneously.

$.firstfunc = function(){
//Do something
//jQuery.ajax({
});

$.secondfunc = function(){
//Do something
jQuery.ajax({
});

$.(document).ready(function(){
$.firstfunc();
$.secondfunc();
});

any help would be appreciated.

Thanks!

Upvotes: 2

Views: 4668

Answers (4)

Raynos
Raynos

Reputation: 169471

Warning: Requires jQuery 1.5+

$.firstfunc = function() {
  return $.ajax({});
}

$.secondfunc = function() {
  return $.ajax({});
}

$(function() {
  $.when($.firstfunc).then($.secondfunc);
});

Using the black magic of $.Deferred's and $.when.

It basically says when you first function finishes its ajax call then call the second function.

This is because $.ajax returns a jqXHR object which inherits from $.Deferred.

If you want to attach a callback when both $.firstfunc and $.secondfunc complete then you can do the following (requires jQuery 1.6):

$(function() {
  $.first().pipe($.second).done(function(second_data) {
    // both finished.
  });
});

Legacy: jQuery 1.4.2 & 1.3.2 support.

$.firstfunc = function(cb) {
  $.ajax({
    success: function() {
      ...
      cb();
    },
    ...
  });
}

$.secondfunc = ...

$(function() {
  $.firstfunc($.secondfunc);
});

Upvotes: 10

user113716
user113716

Reputation: 322562

You should call the second one from the callback of the first .ajax call.

You can either define it explicitly:

$.firstfunc = function(){
    //Do something
    jQuery.ajax({
        callback:$.secondfunc
    });
};

$.secondfunc = function(){
    //Do something
    jQuery.ajax({
    });
};

$(document).ready(function(){
    $.firstfunc();
});

...or pass it as an argument:

$.firstfunc = function( func ){
    //Do something
    jQuery.ajax({
        callback:func
    });
};

$.secondfunc = function(){
    //Do something
    jQuery.ajax({
    });
};

$(document).ready(function(){
    $.firstfunc( $.secondfunc );
});

Upvotes: 0

Fosco
Fosco

Reputation: 38526

That happens because Ajax requests are processed Asynchronously. If you want the second function to run after the first, add it to the callback function of the first Ajax request.

Upvotes: 0

dtbarne
dtbarne

Reputation: 8210

Have the first function call the second function after the code.

function firstfunc() {
    // Do something

    secondfunc();
}

function secondfunc() {
    // Do something else
}

EDIT (now that I see your edit):

Use the callback portion of the ajax functions.

$.get("somepage.php", "key1=value1&key2=value2", function(data) {
    // This code will run when the result is received
});

Upvotes: 0

Related Questions