Hamid Reza
Hamid Reza

Reputation: 2973

Second function is not running in jquery

I have two functions and I want to call one function after the first is completed.

I wrote this:

$(document).ready(function () {
        FetchProducts('@Model.ProductId', function () {
            SimilarProducts('@Model.Class.Group.SectionId', '@Model.ProductId', '@TempData["Min"]', '@TempData["Max"]');
        });
    });

FetchProducts function runs an ajax call that will fill TempData["Min"] and TempDate["Max"] and returns a list of products.

SimilarProducts want to make another ajax request by min and max to get some similar products. FetchProducts is running properly but SimilarProducts is not running.

Whats the problem?

Update

This is FetchProducts function:

function FetchProducts(productId) {
    $.getJSON("/product/jsonproducts", { productId: productId }, function (data) {
        var i = 0;
        $(".section-items-details").empty();
        for (var i = 0; i < data.length; i++) {
            ...
        }
    });
}

And this is SimilarProducts function:

function SimilarProducts(sectionId,productId, minimum, maximum) {
    $.getJSON("/product/getsimilarproducts", { sectionId: sectionId, productId: productId, min: minimum, max: maximum }, function (data) {
        var i = 0;
        for (var i = 0; i < data.length; i++) {
        ...
        }
    });
}

Upvotes: 2

Views: 295

Answers (2)

Richard Schneider
Richard Schneider

Reputation: 35477

Why do you think FetchProducts will call SimularProduction. FetchProducts does nothing with the 2nd argument.

function FetchProducts(productId, then) {
  $.getJSON("/product/jsonproducts", { productId: productId }, function (data) {
    var i = 0;
    $(".section-items-details").empty();
    for (var i = 0; i < data.length; i++) {
        ...
    }
    then();
});

}

Upvotes: 2

Sir McPotato
Sir McPotato

Reputation: 949

Oh well, since your update I can tell you where is the error :)

So, talk about your 'FetchProducts' function :

function FetchProducts(productId) {
$.getJSON("/product/jsonproducts", { productId: productId }, function (data) {
    var i = 0;
    $(".section-items-details").empty();
    for (var i = 0; i < data.length; i++) {
        ...
    }
});

}

As we can see, your 'FetchProducts' function only accept one argument, but in his call, you added an anonymous function.

In order to make it working properly, you shoud edit your 'FetchProducts' function like this :

function FetchProducts(productId, callback) {
    $.getJSON("/product/jsonproducts", { productId: productId }, function (data) {
        var i = 0;
        $(".section-items-details").empty();
        for (var i = 0; i < data.length; i++) {
            ...
        }
        ...
        // Everything is ok, let's call our callback function!
        if ($.isFunction(callback)) callback();
    });
}

Upvotes: 6

Related Questions