Margo Eastham
Margo Eastham

Reputation: 655

jquery ajax load recursive callback

Here's my jquery function, I'm stuck in a circular callback functions. I'm wondering how do I convert this code to call itself? or is it even possible?

$('#content').load('myurl/items', function() {
    ...
    ...
    $(this).find('form').submit(function(e) {
        e.preventDefault();
        $.ajax({
            type: 'POST',
            url: 'myurl/items',
            context: document.getElementByID('content'),
        }).done(function() {
            $(this).load('/myurl/items', function(){}); // This is recursive
        });    
    }
});

Upvotes: 1

Views: 164

Answers (1)

John S
John S

Reputation: 21482

Declare a function:

function loadItems() {
    $('#content').load('myurl/items', function() {
        ...
        ...
        $(this).find('form').submit(function(e) {
            e.preventDefault();
            $.ajax({
                type: 'POST',
                url: 'myurl/items',
                context: document.getElementByID('content'),
            }).done(function() {
                loadItems(); // Call the function to continue
            });    
        }
    });
}

loadItems(); // Call the function to start

Of course, the loop will end if the ajax call is ever unsuccessful.

Upvotes: 1

Related Questions