Submit webform 4 with ajax

Public

Submit webform with ajax. There is module for this webform_ajax https://www.drupal.org/project/webform_ajax but that didn't work as expected for me with webform version 7.x-4.0-rc3. Because i want to display the confirmation when user submit the webform. webform_ajax was submitting the the webform with ajax but reloading the webform again rather then showing the confirmation message, Even if "No redirect" option was checked and under ajax setting "Ajax mode" and "Show confirmation screen" option were checked.

</> CopyGet raw version
php
  1. function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  2. if ($form_id == 'webform_client_form_ID') {
  3. $form['actions']['submit'] = array(
  4. '#type' => 'submit',
  5. '#ajax' => array(
  6. 'callback' => 'webform_client_form_ID_ajax_callback',
  7. 'wrapper' => str_replace('_','-',$form['#form_id']),
  8. 'effect' => 'fade',
  9. ),
  10. '#value' => t('Submit'),
  11. );
  12. }
  13. }
  14.  
  15. function webform_client_form_ID_ajax_callback($form, &$form_state) {
  16. if(form_get_errors()){
  17. return $form;
  18. }
  19. }
  20. //Note: Under "Redirection location" NO redirect option should be select to get the confirmation message with ajax.
  21.  
  22. UPDATE: 18 july 2014
  23.  
  24. you can use this trick to make it generic for all webforms those have No redirect settings enabled under "Redirection location" setting.
  25.  
  26. function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  27. // do ajax submit generic for all the webform those have no redirect option enabled.
  28. if($form['#node']->webform['redirect_url'] == "<none>"){
  29. $matches = array();
  30. //check whether the form id have nid at the end like _nid
  31. preg_match('/[\d]+$/', $form_id, $matches);
  32. $nid_match = $matches[0];
  33. if(strpos($form_id, 'webform_client_form_') == 0 && !empty($nid_match)){
  34. $form['actions']['submit'] = array(
  35. '#type' => 'submit',
  36. '#ajax' => array(
  37. 'callback' => 'webform_client_form_ajax_callback',
  38. 'wrapper' => str_replace('_','-',$form['#form_id']),
  39. 'effect' => 'fade',
  40. ),
  41. '#value' => t('Submit'),
  42. );
  43. }
  44. }
  45. }
  46.  
  47. function webform_client_form_ajax_callback($form, &$form_state) {
  48. if(form_get_errors()){
  49. return $form;
  50. }
  51. else{
  52. return $form['#node']->webform['confirmation'];
  53. }
  54. }

Comments

pari's picture

Don't forget to check if form with webform exists like this

  1. if(isset($form['#node']) && isset($form['#node']->webform)) {
  2. ... ...
  3. }

Also it's not good solution to ovewrite button text because it cannot be changed per webform, use this:

  1. $form['actions']['submit']['#ajax'] = array(
  2. 'callback' => 'webform_client_form_ajax_callback',
  3. 'wrapper' => str_replace('_','-',$form['#form_id']),
  4. 'effect' => 'fade',
  5. );