Is it right to make a request in the request? I need to wait until the first Ajax request returns the values ​​from the database and provides input and buttons, and after that clicking the button I send another Ajax request.

$('#dep-box').on('click', '.show-holidays', function(){ var btn = $(this); var id = btn.parents('form').data('dep-id'); $.ajax({ url : '/settings/get_holidays', method: 'POST', dataType: 'json', data: { id : id }, success: function(data){ var holidaysForm = $('#holidaysFormTpl').render(data); $('.display-table .tbody').append(holidaysForm); initializeDtepicker2(); $('.add-holiday').click(function(){ var btnSaveHol = $(this); $.ajax({ url : '/settings/add_holidays', method : 'POST', data : btnSaveHol.parents('form').serialize(), dataType : 'json', success : function(data){ } }); }); } }); }); 

    1 answer 1

    No, wrong.

    In general, the “request in request” is acceptable by itself, but you have no “request in request”. The click event of the new button and, accordingly, the second ajax request will occur later, when the success handler of the first request has long been processed. You, however, have another problem.

    If your page contains other elements with the add-holiday class (and not just a new one, just created), then you will re-attach additional click handlers to them, which everyone will shoot when you click these buttons.

    Do the same delegation of handling click event for '.add-holiday' as for '.show-holidays' .

     $('#dep-box').on('click', '.show-holidays', function(){ var btn = $(this); var id = btn.parents('form').data('dep-id'); $.ajax({ url : '/settings/get_holidays', method: 'POST', dataType: 'json', data: { id : id }, success: function(data){ var holidaysForm = $('#holidaysFormTpl').render(data); $('.display-table .tbody').append(holidaysForm); initializeDtepicker2(); } }); }); $('.display-table .tbody').on('click', '.add-holiday', function(){ var btnSaveHol = $(this); $.ajax({ url : '/settings/add_holidays', method : 'POST', data : btnSaveHol.parents('form').serialize(), dataType : 'json', success : function(data){ } }); }); 

    Yes, and it seems to me that in your case the jQuery closest method is more appropriate, rather than parents .

    • I will not be able to attach a click on .add-holiday in this way, since the button appears after the first ajax request, and in this way I will look for the button before it appears, the selector will simply not find it. - quaresma89
    • @ quaresma89 - And you try. - Igor
    • It works, thanks. - quaresma89