I have an application with following coffeescript jquery code to do some ajax calls :
$('#records-filter-date').submit ->
$.get(@.action, $(@).serialize(), null,'script')
return false
$('#records-delete').submit ->
$.post(@.action, $(@).serialize(), (data)->
$('.check-for-delete:checked').parent().parent().hide(600,'swing')
$('#alert-div').html("<div class='alert alert-success '><button class='close' data-dismiss='alert' type='button'>x</button><div id='flash_notice'>"+data+ " record(s) successfully deleted!</div></div>")
$.get('#records-filter-date'.action, $('#records-filter-date').serialize(), null,'script')
,'text')
return false
Now the page lists certain records. the first call is to submit search fields via ajax. The second one is to delete selected records (using check boxes). Now I could just delete the records and redirect to the action that lists the records but the search params will be lost (if the user filtered records before deleting them) and they would have to filter records again.
So what I did was after the delete was called successful i called submitted the date in the search fields and thought of updating the records.
but… when there is no search params (when no search was done) the deletion works wel. but when I do a search and then I do a delete… the request is processed as a normal http request..
is there anyway to maintain the search params? or do I need to do anything to fix this?
EDIT: the form that submits records to be deleted is within the div updated by search call. could it be that the binding with the ajax call be broken when the div is updated?
Yes, that’s the problem. When you replace the HTML content of an element, all the existing elements inside it are removed from the DOM and their associated data and event handlers will go with them. Even if you’re replacing it with identical content, the resulting elements are new ones.
You’ll need to use event delegation. Here’s the regular jQuery version of the code:
Ideally, rather than
document, you’d use a static element that’s closer in the heirarchy to the dynamic element (your#records-deleteform would be the dynamic element here). In your case, that would be the selector for the<div>that contains that form.