Multiple Different AJAX Enabled Forms on the Same Page

I currently have a form that is being loaded by AJAX and is working perfectly. I now need to add a second form (Add Single Stat) to the same page via AJAX as well. The Add Single Stat form is being loaded to the page perfectly but when the AJAX callback is fired for the db_selection select list, I get “An AJAX HTTP error occurred. HTTP Result Code: 200” AJAX error. I’m really not sure where this error being caused from and would like to find a fix to this issue.

The Add Single Stat Form is being built with the following code:

public function buildForm(array $form, FormStateInterface $form_state) {     $form['db_selection'] = array(     '#title' => t('Data Location'),     '#title_display' => 'invisible',     '#type' => 'select',     '#options' => array("" => "Select", "enrollmentdata" => "Student Enrollment Data", "summerenrollmentdata" => "Summer Enrollment Data"),     '#prefix' => '<div id="db_selection" class="AddQueryFormElement">',     '#suffix' => '</div>',     '#ajax' => array(         'callback' => 'DrupaldashboardControllerDashboardController::SingleStatOnDBSelection',         'effect' => 'fade',         'event' => 'change',         'progress' => array(             'type' => NULL,             'message' => NULL,             ),         ),    );    $form['term_selection'] = array(     '#title' => t('Select Term'),     '#title_display' => 'invisible',     '#type' => 'select',     '#prefix' => '<div id="term_selection">',     '#suffix' => '</div>'    );    $form['ss_id'] = array(     '#title' => t('Single Stat ID'),     '#type' => 'hidden',     '#prefix' => '<div id="ss_id" class="AddQueryFormElement">',     '#suffix' => '</div>',     );    return $form; } 

I am then loading The Add Single Stat Form to the page via this ajax callback:

public static function AddSingleStatToPanel(array &$form, FormStateInterface $form_state){     $ajax_response = new AjaxResponse();       //Generate a Unique ID for the single stat     $SingleStatID = self::GenerateRandomID(15, 'single_stat_info', 'single_stat_id');      //Add The "Add Single Stat" To the correct DIV     $AddSingleStat = Drupal::formBuilder()->getForm('DrupaldashboardFormAddSingleStat');     self::SetUniqueAddSingleStatFormDivIDs($AddSingleStat, $SingleStatID, TRUE);     $ajax_response->addCommand(new AppendCommand('#AddSingleStatForm_'.$SingleStatID, $AddSingleStat));        return $ajax_response; } 

I handle updating the form to contain unique element id values as well as unique ids for the divs surrounding the form elements in this function:

private function SetUniqueAddSingleStatFormDivIDs(&$FormRenderArray, $SingleStatID, $HideFields = TRUE){     $FormFields = array('term_selection', 'ss_id');       $FormRenderArray['db_selection']['#prefix'] = '<div id="db_selection_'.$SingleStatID.'" class="AddQueryFormElement">';       foreach($FormFields as $FormField){         //Set Each DIV's ID to the Form Field ID_SingleStatID         if($HideFields || $FormField == 'chart_type'){             $FormRenderArray[$FormField]['#prefix'] = '<div id="'.$FormField.'_'.$SingleStatID.'" class="hide" style="display:none" >';         } else {             $FormRenderArray[$FormField]['#prefix'] = '<div id="'.$FormField.'_'.$SingleStatID.'" class="AddQueryFormElement">';          }     }      $FormRenderArray['ss_id']['#value'] = $SingleStatID;     $FormRenderArray['#attributes'] = array('id' => array('ss_'.$SingleStatID));   } 

Inside of the dashboard controller I have the AJAX callback that I would like to be called when the user changes an option in the db_selection select list.I have reduced the code here to just a simple JS alert.

public static function SingleStatOnDBSelection(array &$form, FormStateInterface $form_state){      $ajax_response = new AjaxResponse();      $ajax_response->addCommand(new AlertCommand('It Works!'));      return $ajax_response; } 

Update: I have done a little more debugging and the only way I can make this form work correctly is if I pass the form’s render array to twig file and load it that way. The form doesn’t seem work at when using AJAX to loads the form’s HTML.

This article was republished from its original source.
Call Us: 1(800)730-2416

Pixeldust is a 20-year-old web development agency specializing in Drupal and WordPress and working with clients all over the country. With our best in class capabilities, we work with small businesses and fortune 500 companies alike. Give us a call at 1(800)730-2416 and let’s talk about your project.

FREE Drupal SEO Audit

Test your site below to see which issues need to be fixed. We will fix them and optimize your Drupal site 100% for Google and Bing. (Allow 30-60 seconds to gather data.)

Powered by

Multiple Different AJAX Enabled Forms on the Same Page

On-Site Drupal SEO Master Setup

We make sure your site is 100% optimized (and stays that way) for the best SEO results.

With Pixeldust On-site (or On-page) SEO we make changes to your site’s structure and performance to make it easier for search engines to see and understand your site’s content. Search engines use algorithms to rank sites by degrees of relevance. Our on-site optimization ensures your site is configured to provide information in a way that meets Google and Bing standards for optimal indexing.

This service includes:

  • Pathauto install and configuration for SEO-friendly URLs.
  • Meta Tags install and configuration with dynamic tokens for meta titles and descriptions for all content types.
  • Install and fix all issues on the SEO checklist module.
  • Install and configure XML sitemap module and submit sitemaps.
  • Install and configure Google Analytics Module.
  • Install and configure Yoast.
  • Install and configure the Advanced Aggregation module to improve performance by minifying and merging CSS and JS.
  • Install and configure Schema.org Metatag.
  • Configure robots.txt.
  • Google Search Console setup snd configuration.
  • Find & Fix H1 tags.
  • Find and fix duplicate/missing meta descriptions.
  • Find and fix duplicate title tags.
  • Improve title, meta tags, and site descriptions.
  • Optimize images for better search engine optimization. Automate where possible.
  • Find and fix the missing alt and title tag for all images. Automate where possible.
  • The project takes 1 week to complete.