tatty27 tatty27 - 3 months ago 12
Ajax Question

call function within ajax success

I am trying to call a function from within an AJAX success handler, but it is being ignored

$.ajax({
url: '../ajax/create_audit_standard_carosel.php',
type:'POST',
data: 'audit_id='+audit_id+'&user_id='+user_id,
dataType: 'json',
success: function(response){
$('#num').html(response.standards_count);
$('#standards_list').html(response.output);
jQuery(function($) {
$("#selected_standards").touchCarousel({
itemsPerPage: 4,
scrollbar: true,
scrollbarAutoHide: true,
scrollbarTheme: "dark",
pagingNav: false,
snapToItems: true,
scrollToLast: true,
useWebkit3d: true,
loopItems: false
});
});
}, // End of success function of ajax form
error:function (xhr, ajaxOptions, thrownError){
alert(thrownError);
}
}); // End of ajax call


The responses are correct and the contents of
#standards_list
are amended with the correct content so I know that the AJAX call is working correctly, but the function within the success call is completely ignored.

Answer

If you mean the function beginning directly after where you update the #standards_list element, it's because you are trying to bind to an event that has long since fired.

Passing a function to the global jQuery function is a shortcut for binding to the document.ready event. This event is fired when the page loaded and will not fire again as a result of the AJAX call.

Just remove the wrapping function and call the touchCarousel method after updating the #standards_list element, e.g:

$.ajax({
    url: '../ajax/create_audit_standard_carosel.php',
    type:'POST',
    data: 'audit_id='+audit_id+'&user_id='+user_id,
    dataType: 'json',
    success: function(response){
        $('#num').html(response.standards_count);
        $('#standards_list').html(response.output);
        $("#selected_standards").touchCarousel({
            itemsPerPage: 4,             
            scrollbar: true,
            scrollbarAutoHide: true,
            scrollbarTheme: "dark",              
            pagingNav: false,
            snapToItems: true,
            scrollToLast: true,
            useWebkit3d: true,               
            loopItems: false         
        });
    }, // End of success function of ajax form
    error:function (xhr, ajaxOptions, thrownError){
        alert(thrownError);
    }
}); // End of ajax call`