1
function _ajax_ticket_info($form,&$form_state)
{
    $subscriber = $form['info']['ticket']['subscribe'];
    _ticket_subscribe($subscriber['#value'],$subscriber['#name']);

    // Dunno if this is needed or not
    $form_state['rebuild'] = TRUE;


    return $form;
}
function _ticket_info($form,&$form_state,$node) {

    $is_subscribed = _ticket_is_subscribed($node->nid);
    $subscriber_count = count(_ticketsys_get_subscribers($node));

    $form = [
        '#prefix' => "<div id='ticket-info-form'>",
        '#suffix' => '</div>',
    ];
    // other form fields here not that important 
    // just focusing on my problem 
    $form['info']['ticket']['subscribe'] = [
    '#type' => 'button',
    '#value' => $is_subscribed,
    '#name' => $node->nid,
    '#id' => 'ticket-subscribe',
    '#ajax' => [
        'callback' => '_ajax_ticket_info',
        'wrapper' => 'ticket-info-form',
        'effect' => 'fade',
    ],
];
return $form;
}

So the problem is i'm using that code to update my form without reloading the page and when i do that it only executes the replacement on the second time i clicked the button $form['info']['ticket']['subscribe'] and i notice using inspect element on chrome that the form id and other form fields have --2 on their ids and increasing every time i click the Subscribe button

Any ideas whats wrong here. I really need to fix this thanks

0

Try changing the button type to "submit", and specifying a custom submit handler:

$form['info']['ticket']['subscribe'] = [
    '#type' => 'submit',
    '#submit' => [['ticket_submit_handler']]
    '#ajax' => [
        'callback' => 'ticket_ajax_callback',
        'wrapper' => 'ticket-info-form',
    ],

    // ...
];

In the submit handler:

  • Change any variables in form_state storage that need to persist.
  • Tell the form to rebuild itself (instead of doing a redirect after submission), in order to keep the form state.
  • Do other stuff.

e.g.

function ticket_submit_handler(&$form, &$form_state) {
    $form_state['storage'][] = ;
    $form_state['rebuild'] = TRUE;
    // ...
}

In the AJAX callback:

  • Return the part of the form that will replace the 'wrapper'. In your case, it seems to be the entire form.
  • Don't do anything else here.

e.g.

function ticket_ajax_callback(&$form, &$form_state) {
    return $form;
}

AFAIK, when the user clicks your AJAX button, the following functions will run, in order:

  1. Form validation (if any).
  2. ticket_submit_handler
  3. Form builder, to rebuild the entire form, even if we only need a part.
  4. ticket_ajax_callback, which returns a part of the form, which is sent to the browser.

For more information, see the example code in the Drupal 7 documentation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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