[Django]-Form loses ability to send POST requests after 2 ajax updates

1đź‘Ť

âś…

First of all, you’re doing something slightly weird. You use a jQuery-plugin which is supposed to handle form submission over ajax and repopulate the fields. Still, on success, you replace all the HTML of your form with HTML from the server, negating its work.

This breaks your calendar/time widgets, as you initialize the widgets on page load, telling them to act on some page elements, which you later replace.

But this doesn’t by itself break the form submission.

Firstly, you don’t need a plugin for attaching events “live” if you stop replacing the form HTML. Secondly, you don’t really need a plugin for that anyway as it seems the built-in live() method in jQuery should do the job (that is, if you actually do need this functionality). Thirdly, if you use plugins and they don’t seem to be working properly, update to the latest version. The version you’re using doesn’t support the html() method in jQuery.

The livequery-plugin does its magic by overriding any jQuery-methods which might update the DOM. So when the programmer calls, f.ex, append(), it intercepts the call, calls append() for you, and then checks the document for new or disappeared elements matching your provided selector. The version you’re using is not aware of html() and therefore does not intercept it.

So it works the first time as you initiate a DOM-check on page load. When that result is returned, the event is actually attached to the new submit-button because the calls to html() to set the new form and completion-message internally calls intercepted methods. Therefore, the second submission works as desired. But when the second call comes back, a jQuery cache is used internally, not calling any intercepted methods. So the event doesn’t get attached to the submit-button, making it act as a regular form submission button.

To fix, stop using live-attaching for event-listening if there’s not a non-apparent need for it. If there is, use the built in one or at least update your livequery plugin. Also, don’t replace the whole form HTML. Again, if there’s a non-apparent reason, re-initialize you calendar widget each time after setting the HTML.

Leave a comment