Magento – Trigger admin controller custom action on button click

ajaxbackendjavascript

I have 2 buttons for my form, currently the main save button works like:

$this->_updateButton('save', 'onclick', 'submitForm()');

and some JS so it shows the "Please Wait" javascript loader:

function submitForm() {
    $('edit_form').request({
         onComplete: function()  { 
             window.location.href = document.URL; 
         }
     })  
}

This works well because it's just posting the form. I need to add another button to post the same form but call a different action other than saveAction, I am currently doing:

$postBackUrl = $this->getUrl('*/mymodule/custom');
$this->_addButton('sync', array(
    'label'     => Mage::helper('adminhtml')->__('My Action'),
    'onclick'   => "submitSyncForm('$postBackUrl')",
    'class'     => 'save'
),3,5);

I then have this Javascript to post the form:

function submitSyncForm(url){
    new Ajax.Request(url, {
        method:'post',
        onComplete: function()  { 
            window.location.href = document.URL; 
        }
    });
}

The form shows the Please Wait and posts to customAction correctly but the post values are empty when I try to access them via $this->request->getPost().

Could someone point me in the right direction on posting the form to a custom action other than saveAction please?

Best Answer

Ok, played around and came up with this solution. If I change my form action in the JS and call the form.Request() it posts the correct values back:

function submitSyncForm(url){
    $('edit_form').writeAttribute('action', url);
    $('edit_form').request({
         onComplete: function()  { 
             window.location.href = document.URL; 
         }
     }) 
}

I'm not sure this is the advised method but it seems to work nicely.