2

How to attach javascripts to form rendered with ajax?

In particular, I have problem with popup calendars in my form. They are not showing, when my form is rendered with ajax.

I am rendering form with javascript as follows:

$.get('/event-form', {}, function(data) {
$('#event-popup-container').html(data);

This code calls ajax callback "/event-form". returned variable 'data' containes my form. This form is displayed on web page in HTML element $('#event-popup-container'). It works OK, just date_popup elements in form don't show popup calendars. Propably I have to attach some javascripts somehow, when the form is not loaded with page load, but with ajax call. But I have no clue how.

I have such a code in my menu callback of path '/event-form':

<?php  
  //...
  $event_form = drupal_get_form('ef_event__form', $event_id, NULL);
  $output .= drupal_render($event_form);
  drupal_json_output($output);
?>

Can anybody help, how to make work all needed javascripts, when the form is loaded with ajax?

1 Answer 1

2

The problem is that you are not using any of AJAX helpers provided by Drupal. When you are using Form API AJAX, for example, all behaviors are re-initialised and functionalities like calendar added to new elements.

If you are not using Drupal-provided AJAX functionality, you need to manually call all behaviors with a proper context after your request is finished and DOM tree updated, probably by calling

Drupal.attachBehaviors(element)

on added DOM element.

4
  • thanks. Now I know where I have to place additional code. But I don't know what I should place there. Is there any general method to ad dall needed javascripts for some form element or should I study date_popup source code and find it there? Commented Oct 23, 2013 at 12:34
  • @tomas.teicher All functions you need to re-execute are attached to Drupal.behaviors. Just loop over them and call them all.
    – Mołot
    Commented Oct 23, 2013 at 12:37
  • thank you. Your answer works. But I am not sure whether it is needed to call all behavior's functions. As it is written in this thread drupal.org/node/1015468#comment-4227872, it is enough to add just form object as parameter. It works for me, too. Commented Oct 23, 2013 at 12:52
  • @tomas.teicher answer updated a bit. That's the best you can get from me, my experience isn't much larger than that :(
    – Mołot
    Commented Oct 23, 2013 at 14:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.