Search code examples
cakephppostcakephp-2.1formhelper

Intercept cake2 postLink() form posts with jQuery


Has anyone found a way to intercept the default Form::postLink() forms with Jquery? I would like the form to work without JS (therefore the postLink). But with JS enabled I want to intercept the post and call it via AJAX.

<?php echo $this->Form->postLink('Delete', array('action'=>'delete', $prospect['Prospect']['id']), array('class'=>'postLink', 'escape'=>false), __('Sure you want to delete # %s?', $prospect['Prospect']['id'])); ?>

generates:

<form action="/admin/prospects/delete/4f61ce95-2b6c-4009-9b89-07e852b0caef" name="post_4f648f773923b" id="post_4f648f773923b" style="display:none;" method="post">
    <input type="hidden" name="_method" value="POST"/>
</form>
<a href="#" class="postLink" onclick="if (confirm('Sure you want to delete # 4f61ce95-2b6c-4009-9b89-07e852b0caef?')) { document.post_4f648f773923b.submit(); } event.returnValue = false; return false;">
    Delete
</a>

The main problem is that the js is placed inline here. Therefore always triggers even if I try to intercept the click event (or the post event - tried that too):

<script>
$(document).ready(function() {
    $('table.list a.postLink').click(function(e) {
        e.preventDefault();
      alert('Handler for .submit() called.');
      // TODO: do ajax request here and return false
      return false;
    });
});
</script>

So in the end the form always submits normally and redirects - either ignoring any ajax call (catching the form submit) or posting/redirecting regardless of an ajax call just made (catching the click event).

I would like to delete this record via AJAX and - if successful - just remove that table row from DOM. It would be great if one doesn't have to modify all 300+ "delete buttons" in the application for it, though.

If everything fails I could probably still override the FormHelper (extend it and alias it). But I was hoping on a less invasive solution here.


Solution

  • I know this is old, but for any of those searching:

    • You need to first remove the 'onclick' attribute added to the delete link.
    • Then, you add a .click function to the delete link
    • You need the url (which can be hardcoded or retrieved from the form, which is always the prev element in cakephp Form->postLink

    Here is the code:

    
    $(function(){
    
        $('a:contains("Delete")').removeAttr('onclick');
    
        $('a:contains("Delete")').click(function(e){
            e.preventDefault();
            var form = $(this).prev();
            url = $(form).attr("action");
            $.post(url);
            return false;
        });
    
    });