Darme
Darme

Reputation: 7083

Rails form with ajax and non-ajax buttons

I have a form_for an @object with two buttons.

While the first button renders the 'show action', the second button renders the same form again. So I'd like the latter to be ajax-handled.

Is it possible to have a non-ajax button and an ajax button in the same form or do I have to change strategy?

Maybe I need a form_for with 'remote: true' so that both the buttons are ajax but then, how would I manage the first button to render the proper 'show view'?

Or maybe the only real solution is to have two different forms?

Thank you.

Upvotes: 3

Views: 447

Answers (2)

tsherif
tsherif

Reputation: 11710

I think the easiest approach would be to use the jQuery Form plugin. Then you can just create the form to submit to your non-ajax action, and the ajax functionality will be attached to the submit button itself:

$(".ajax_submit_button").click(function() {
  $(this).closest("form").ajaxSubmit({
    // options go here
    ...
  });
  return false;
});

Upvotes: 0

klump
klump

Reputation: 3269

You could try to hook onto the buttons onClick event, remove the data-remote="true" attribute, submit the form and add data-remote="true" again. I dont know if this is really the best way but it should work.

function sendWithoutAjax() {
  $('my_form_id').removeAttr("data-remote");
  $('my_form_id').submit();
  $('my_form_id').data( "remote", "true" );
}

Something like this...

Upvotes: 2

Related Questions