1

OK, I'm doing some basic validation inside of an ajax form callback. I'd like to use the result to execute some javascript. What I've tried looks something like this:

inside my form alter:

if (isset($form_state['values']['field_temp_age'])) {
  if (validate())
  {
    //...return product information
  } else {
    drupal_add_js('alert("Validation fails!");', 'inline');
  }
}

This doesn't work. In this case, nothing is returned.

Also, tried this from inside the ajax callback:

function my_ajax_callback(&$form, &$form_state) {
  if (!validate()) drupal_add_js('alert("Foo!");', 'inline');
}

Not sure what's the approach here. How can I execute arbitrary javascript based on information returned from an ajax request?

Thanks.

3
  • Are you using CTOOLS? if not you should be.. there is a great validation library at your disposal. Dec 23, 2011 at 22:45
  • Drupal. behaviors is the proper method for handling JS events as of D7. A little bit of a learning curve.. but it is the proper way to have your code interact with the client layer effectively. Not without mention it is extremely robust. Dec 23, 2011 at 22:56
  • PhiloSurfer - I'm checking out ctools - thanks. What I'm trying to do is dynamically load product information based on a form field. I have this working but the ajax-returned data won't reload when the field is updated. I'm thinking ctools may offer some help getting the html in and out of the ajax wrapper, but I haven't found it... thanks for the tips! Dec 24, 2011 at 16:12

2 Answers 2

1

Not sure of how you are making the AJAX call, but jQuery AJAX calls such as $.ajax let you execute a callback after the result has been returned. I recommend returning FALSE or a code indicating an error to your calling function and placing your "validation failed" logic inside of that in the success handler.

1

drupal_add_js doesn't work properly in an AJAX callback. If you need to execute a JavaScript function within an AJAX callback, here's the way :

First, in your form, you have to create the JavaScript function :

function my_module_form($form, &$form_state) {
// [...]
  drupal_add_js(
    'Drupal.ajax.prototype.commands.myFunction = function(ajax, response, status) {
      // Whatever you want to do. i.e. :
      window.open("http://www.google.com")
    }',
    'inline'
  );
// [...]
  return $form;
}

Then, in your AJAX callback, you need to call this function you created :

function my_module_my_ajax_callback($form, &$form_state) {
// [...]
  $commands[] = array("command" => 'myFunction',);
// [...]
  return array('#type' => 'ajax', '#commands' => $commands);
}

Hope it helps !

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.