5

I am trying to perform an AJAX post on node edit pages in a new module I created Proofread Bot. This module adds a button and clicking it performs an AJAX post to a URL for processing text. When I do this on node edit, it seems the whole page gets submitted. I tried adding an event.preventdefault call, but also returning false for the button doesn't work. Let me add the same code works like magic on node view. Here is the code:

function proofread_bot_node_prepare($node)  {

drupal_add_js('
    jQuery(document).ready(function(){
    jQuery("#edit-body").before(\'<div id="proofread_bot-button-holder"><button type="button"  id="proofread_bot-submit" onclick="return false;">Check with Proofread Bot</button></div>\');      
    jQuery("#proofread_bot-submit").click(function(event){
      event.preventDefault();
      jQuery.ajax({
         type: "POST",
         url: "proofread_bot/check",
         dataType: "html",
         data: {"text": jQuery("#edit-' . variable_get('proofread_bot_field') . '").html()
          },
         success: function(proofread_result){
            jQuery("#proofread_bot-submit").after(proofread_result);
         }
        });    
      });
    });
    ', 'inline');

}
0
1

The Drupal Ajax call is not affected by event.preventDefault in the above code, as neither the Click() or on('click') Jquery function gets executed on Drupal Ajax call. Please refer the link below

Jquery gobal ajax events

In the above code the ajaxSend() function can be used to stop the Ajax call even before getting started. And use event.preventDefault in the function to stop the Drupal Ajax Call before getting executed.

For Example:

$( document ).ajaxSend(function() { event.preventDefault(); //add you code here. });

Please check if this code will work in the function your calling, i am not sure (may work) or else call this code directly in you attached JS file.

0

Try changing the button to an anchor.

4
  • Thanks for the tip replaced the button with a link like this, but still the same: <a href="#Proofreadbot" id="proofread_bot-submit" onclick="return false;">Check with Proofread Bot</a>
    – giorgio79
    Nov 14 '11 at 9:31
  • the id for the onclick event is wrong, or should for shure not be the same like the one of the form used.
    – rémy
    Nov 17 '11 at 15:18
  • The form is a standard node add form. The id of the click is set to #proofread_bot-submit a custom button I add to the form with jquery
    – giorgio79
    Nov 17 '11 at 16:03
  • i don't get why the whole form is submitted .., maybe check when and why forms are submitted ..
    – rémy
    Nov 22 '11 at 10:10

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.