Inline Javascript throws an error on drupal_add_js() within an AJAX callback
Quick written code:
      &lt;?php

      /**
        * Form.
        */
      function sample_luhn_form($form, &amp;$form_state) {
        // I don't recommend inline js, prefer usual module js file, attach via $form['#attached'] or in module info file
        // Also I am use jQuery instead of $, but your shown (function ($) { }jQuery)); is preferred, I don't know why it's show errors, try inspect on dev.tools
        drupal_add_js('jQuery(document).ready(function () { jQuery(&quot;.luhn-nums&quot;).keydown(function() { if (jQuery(this).val().length &gt;= 5) { jQuery(&quot;.luhn-check&quot;).mousedown(); } }); });', 'inline');


        // text field that should be checked for Luhn
        $form['luhn_nums'] = array(
          '#type' =&gt; 'textfield',
          '#title' =&gt; t('Luhn numbers'),
          '#prefix' =&gt; '&lt;div class=&quot;luhn-nums-wrapper&quot;&gt;',
          '#suffix' =&gt; '&lt;/div&gt;',
          '#attributes' =&gt; array(
            'class' =&gt; array('luhn-nums'),
          ),
        );
        // hidden ajax button
        $form['luhn_check'] = array(
          '#type' =&gt; 'submit',
          '#ajax' =&gt; array(
            'callback' =&gt; 'sample_luhn_form_ajax_submit',
            'wrapper' =&gt; 'luhn-nums-wrapper',
          ),
          '#attributes' =&gt; array(
            'class' =&gt; array('luhn-check', 'element-invisible', 'hidden'), // set class, that hide this ajax submit button or hide via CSS styles
          ),
        );

        // here goes another form elements
        // ...
        $form['submit'] = array(
          '#type' =&gt; 'submit',
          '#value' =&gt; t('Submit'),
        );
      }

      /**
       * Ajax callback function.
       */
      function sample_luhn_form_ajax_submit($form, &amp;$form_state) {
        if (_sample_luhn_check($form_state['values']['luhn_nums'])) {
          // If luhn not passed
          form_set_message('luhn_nums', t('Luhn error, please fix numbers'));
        }
        // here you can alter luhn_nums textfield value
        return $form['luhn_nums'];
      }

      /**
       * Validate form.
       */
      function sample_luhn_form_validate($form, &amp;$form_state) {
        // Don't allow pass to submit untill luhn will passed
        if (_sample_luhn_check($form_state['values']['luhn_nums'])) {
          // If luhn not passed
          form_set_message('luhn_nums', t('Luhn error, please fix numbers'));
        }
      }

      /**
       * Form submit.
       */
      function sample_luhn_form_submit($form, &amp;$form_state) {
        // save data
      }

      /**
       * Private function that check luhn algorithms.
       */
      function _sample_luhn_check($nums) {
        $result = FALSE;

        // check numns by luhn algorithms
        // lot of code that alter $result

        return $result;
      }