Questions tagged as ['ajax']

Use it for questions about JavaScript/PHP code to create asynchronous web applications.
Score: 1
Interlated avatar
How to filter autocomplete on a dependent field?
km flag

Goal - How to filter autocomplete based on a related field? In this domain, an organisation is selected and then the autocomplete should only allow items created by that organisation to be selected.

The setup involves an

  • inline entity form to select the organisation. This is the triggering field.
  • auto complete field to select a related bond by that organisation

The triggering element is called 'issue ...

Score: 0
sndr avatar
Load view form with ajax missing ajax functionality
us flag

When clicking an element I get a form which is generated by a view (using https://www.drupal.org/project/editablefields module). The problem is that the ajax functionality of the form is lost (no ajax-processed classes are present). This is the working js code to retrieve the view:

(function($,Drupal) {
  Drupal.behaviors.MODULE = {
    attach:function (context, settings) {   
      $('#test').cl ...
Score: 0
Run php code on text field in variation possible?
cn flag

Is it possible - anyone know how - to run php code on a commerce 2 variations created field to check the data in that field maybe using Ajax to make the field typingsensitive in the checkout?? I read through https://www.drupal.org/project/commerce/issues/3103537 but but the code there. The field would be used to verify an imei or Vin number before the purchase can be made. ( I have code to count k ...

Score: 0
Update body field from ajax callback
cn flag

I need to update the common "body" field when I change some paragraph fields value.

Here is my hook_form_alter :

$form["body"]["#prefix"] = "<div id='body__update_real_time_seo'>";
$form["body"]["#suffix"] = "</div>";

$form["field_content_edito"]["widget"][3]["subform"]["field_paragraph_subtitle"]["widget"][0]["value"]["#ajax"] = [
    "callback"  => "_update_real_time_seo",
    "event"  ...
Score: 0
Need help with AJAX calls within Drupal.behaviors
in flag

I'm having some issues getting the following code to work correctly:

(function($) {
'use strict';
Drupal.behaviors.mybehavior = {
    attach: function(context, settings) {

        // Click on a placeholder image, this should open a form and then
        // replace the image with a video resource (gated content)
        $(document).once('abc').on('click', '.image_class', function() {
            va ...
Score: 0
Use ajax to save modal / dialog form instead of page reload
kr flag

I'm looking for a way to save modal & dialog forms through ajax instead of redirecting the user after the form submit. Ajax is quite unknown territory to me.

I've found several interesting topics here already:

jQuery UI Dialog attempt to submit a form using AJAX redirects me to the actual form page instead of AJAX submitting

How to close modal after form submit?

I tried all answers shown there,  ...

Score: 0
Interlated avatar
Can I bind ajax to form or document?
km flag

I would like to bind an update to entity browser select.

It is a standard ajax form response. Update the default value of another field.

If I apply the ajax to the inline entity browser form field it breaks the entity browser.

The trigger field is 'field_bond_issuer' the target is 'field_bond_country'. Setting the trigger to the trigger field breaks the selection. The target doesn't work:

 $form['f ...
Score: 0
Tommy Styrbæk avatar
Ajax message after node save
cn flag

I am trying to add a Ajax Alert or popup message inside a hook_node_presave or hook_node_update, but it is not working.

My current code look like this, but I have tried a lot of other ajax

$response = new ajaxResponse();
$response->addCommand(new AlertCommand('Ajax test'));
return $response;

The node is saved but no alert and no errors in the console. Drupal 9

Score: 0
Controlling dropdown field visibility using #states API for dependent dropdown
cn flag

I have the following setup.

dropdown_one

[
    '#type' => 'select',
    '#title' => $this->t('Dropdown one'),
    '#options' => $dropdownOneOptions,
    '#empty_option' => '---',
    '#weight' => 1,
    '#ajax' => [
      'event' => 'change',
      'callback' => [$this, 'getDropdownTwoOptions'],
      'wrapper' => 'dropdown-two',
      'progress' => [
        'type' =& ...
Score: 0
john Smith avatar
entity_form how to programmatically add references and update the form visually (entity_browser)
gr flag

I´m having an fieldable entity with a reference field to paragraphs field_paragraphs and a paragraph_type with a reference field to content_type event field_events.

What i am trying in the entity form is to have a button in the paragraph_type event subform which on click prefills the field_events of the paragraph_type with content. The form display of field_events uses an entity_browser to let the user  ...

Score: 0
madhukar avatar
Is there any way to add JS to form only when loaded using ajax-api in modal?
my flag

I have one page on which there is a button. On click of that button I am opening a webform in modal popup (Ajax dialog). What I need is to add a GA script to the form. I have tried using hook_preprocess_page and hook_form_alter to attach the script but none of these 2 works. However script gets attached to form if opened directly with URL.

   /**
 * @param $form
 * @param FormStateInterface $form_s ...
Score: 0
How to configure a custom POST api to accept a request with Content-Type as "application/x-www-form-urlencoded" in the header?
bw flag

I created a controller in a custom module that accepts a POST request.
I have a setup such that I get a POST request from a third-party application server to this API. But the POST request has a Content-Type: "application/x-www-form-urlencoded" in the header.
And because of this I get the following error in the recent log messages:

Symfony\Component\HttpKernel\Exception\UnsupportedMediaTypeHttpException ...

Score: -2
Md. Shafiq Hossain avatar
How to open a form in modal from controller while redirect
cn flag

I can open a form in modal when click on a link (and there are lot of examples in the net as well).

What I like to do: When some one go to a url in browser or redirect to a url, it will open a dialog/modal form.

-I have defined a controller for a url -In the controller function I placed the code like this:

  $response = new AjaxResponse();
  $title = $this->t('Confirmation');
  $form = $this->formB ...
Score: -1
ashique avatar
How do I add ajax callback to a form element which is created in a foreach loop
cn flag

Please see the following code:

foreach ($formaddresses as $key => $val) {
  // Add edit buttons to custom client-side created addresses.
  if (!isset($val['accountnumber'])) {
    $form['orderinfo']['billshipaddresses']['billingaddresses'][$key]['#description'] = '<a class="edit-stored-address edit-stored-address-target-' . $key . '">Edit</a>';
    $form['orderinfo']['billshipaddress ...
Score: 0
Interlated avatar
How to see if ajax has been added to a simple node form?
km flag

This very simple #ajax customisation to a node form is not working. How can I tell whether the callback has been added? I want to calculate a field if the first field is changed.

function cbi_currency_form_node_bond_edit_form_alter(&$form, FormStateInterface 
   $form_state, $form_id) {

    $form['field_bond_amt_issued']['#ajax'] = [
    'callback' => 'cbi_currency_convert_usd',
    'event' ...
Score: 0
How disable submit button after call OpenModalDialogCommand in Ajax callback?
us flag

I have a block that has a button, when pressing that button an ajax is triggered that shows a popup with the OpenModalDialogCommand event, after closing the popup I want to deactivate the submit button, does anyone know how to do that?

The form

    $form['actions']['submit'] = array(
      '#type' => 'submit',
      '#value' => $this->t('Get cupon'),
      '#prefix' => '<div id="cupon_f ...
Score: 0
Ajax form ReplaceCommand functionality breaks after first fire
cn flag

I Have a form on a page which updates a single field of a Node. The form uses ajax to update the field and returns the newly saved entity and replaces the current HTML so the new field is showing up correctly.

This works fine the first time the form is fired, but breaks after that with the following error in my console:

An AJAX HTTP error occurred

There's no further error report which would tell me mor ...

Score: 1
Refresh view using ajax with parameters
ni flag

I use this code to refresh a view, but It reloads the view ignoring neither page number nor filters.

$('.view-id-name').trigger('RefreshView');

How could I pass parameters (page number, query filters, etc) to this call?

Score: 1
vyshnavi avatar
AJAX callback is fired only once
eg flag

I am using hook_form_alter() hook to add an Apply button to the node edit form.. When users click on that button, an AJAX callback replaces the text field value.

It works fine the first time, but the second time it doesn't replace the value.

function course_form_node_items_edit_form_alter(&$form, FormStateInterface $form_state) {

  $form['apply'] = array(
    '#type' => 'submit',
    '#value' ...
Score: -1
vyshnavi avatar
drupal custom callback in node edit form is not firing
eg flag

i am fairly new to drupal , i have custom button added to one the content type edit page , when i click on that button i want to call a function but it seems like it is not calling function when i see the console i see drupa ajax error coming whenever i click the button . please let me know what i am doing wrong here .

function mymodule_form_node_program_edit_form_alter(&$form, FormStateInterf ...
Score: 1
Серёжа Попырин avatar
Send an AJAX response and rebuild a form in a single AJAX callback
us flag

I need to execute multiple AJAXCommands and rebuild form in one AJAXCallback function, but the documentation says the AJAXCallback function should return AjaxResponse OR FormElement.

Using ReplaceCommand to replace an element is difficult because after the AjaxCallback SubmitButton should be searched, and its #Submit function.

How can I do this?

Score: 2
Chris Happy avatar
Custom Submit Callback only triggering when Form is Valid when in Dialog
cg flag

I'm trying to create a node in a dialog with the following link:

Enter the title of a registration form or <a class="use-ajax" 
    data-dialog-options="{&quot;width&quot;:800}" 
    data-dialog-type="modal" 
    href="/node/add/mycontenttype?enableAjaxSubmit=true">
    create a new registration form.
</a>

The callback _mymodule_close_dialog() runs perfectly when there are no va ...

Score: 0
tonytheferg avatar
How to close a modal with a submit form and implement a CloseModalDialogCommand?
cn flag

I saw this issue here, but I wanted to post this question as the answers seem incomplete and the question is not specific to closing a modal with a submit form.

In my .module file, I am using a my_module_form_alter and using ajax to open up a modal dialog:

$form['actions']['submit']['#ajax'] = [
  'callback' => 'my_module_form_submit',
  // prevent jump to top of page.
  'disable-refocus' => TRUE ...
Score: 0
Harshit Thakore avatar
Admin custom configuration form add more field issue
cn flag

I have created below admin custom configuration form by taking a reference of below examples:

  1. https://git.drupalcode.org/project/examples/-/blob/8.x-1.x/form_api_example/src/Form/AjaxAddMore.php
  2. How do I add a "Add more" button?

My custom form is rendered correctly on first time load but when i click on "Add Product" button nothing happen. As per example the form should rebuild again and prepend the ...

Score: 0
Form API States required don't seem to work on a custom form with ajax
us flag

I can't get form states required to work on an ajax submitted form.

Here is some example code. It is taken from the examples module and slightly modified to illustrate the problem.

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    // This container wil be replaced by AJAX.
    $form['container'] = [
      '#type' => 'container',
      '#at ...
Score: 0
Add rows to form tableselect with AJAX
na flag

I would like to:

1.) Add rows to a tableselect form element when a user clicks on a button.

2.) See which rows are selected when a user clicks on another button.

Part one is complete (I've only included relevant code):

public function buildForm(array $form, FormStateInterface $form_state) {

  //Tableselect
  $header = [
    'first_name' => $this->t('First Name'),
  ]

  $form['results'] = [ ...
Score: 1
Chris Roditis avatar
Ajax form inside custom system.404 route controller doesn't work
in flag

I need to display custom logic in 404 pages so I have overridden the route controller of the system.404 route like this:

class RouteSubscriber extends RouteSubscriberBase {

  protected function alterRoutes(RouteCollection $collection) {
    if ($route = $collection->get('system.404')) {
      $route->setDefault('_controller', '\Drupal\mymodule\Controller\myController::on404');
    }
  }
}
Score: 0
Rog Boy avatar
Checkbox Ajax call back giving me error
ma flag

New to drupal 7, following code should work fine according to my knowledge can someone help me why ajax give me error in console ? and what the solution

Code

function user_activity_tree_structure_showoptional_form($form, &$form_state, $base_nid) {
      $form['enablecond'] = array(
        '#type' => 'checkbox',
        '#title' => "Checkbox  ",
        '#ajax' => array(
        'callba ...
Score: 0
beltouche avatar
How to add a secondary Ajax submit to a regular node form?
cn flag

I'm trying to add an Ajax submit to a regular node edit form (Drupal 9). I'm using Field Groups so that there's a series of tabs, and I've added a pair of "buttons" (Right now they're just markup <div>s, but I could change them to real buttons if that's recommended) that users can use to move forward and back through the tabs with some Javascript.

The ask now is that each time the tab focus change ...

Score: -1
Why do I get "An invalid selection has been identified." from the form my code creates?
ng flag

I am using the following code for a form.

public function buildForm(array $form, FormStateInterface $form_state) {
  $region_options = static::getFirstDropdownOptions();
  $form['vvv_region'] = [
    '#type' => 'select',
    '#title' => $this->t('region select field'),
    '#options' => $region_options,
    '#empty_option' => t('- Select region -'),
    '#ajax' => [
      'callback' ...