Reputation: 461
I've spent way too much time on this, trying to figure out why it isn't working. I've tried two methods with flaws in both. It's driving me nuts. Here's my code.
METHOD 1
Form
<%= form_for @order, remote: true do |f| %>
...
<% end %><br>
Js
$('#new_order').submit(function() {
$('input[type=submit]').attr('disabled', true);
//Some validations
if (validation successful) {
$('#new_order')[0].submit();
return false;
} else {
return true;
}
});
Controller
def create
#if @order.save, the usual
respond_to do |format|
format.js
end
end
Now if there's a format.html there it'll follow the html redirect and if not, it throws a 406 error. It works normally without javascript but it still says html in the header.
METHOD 2
Form
<%= form_for @order, remote: true do |f| %>
...
<% end %><br>
Js
$('#new_order').submit(function() {
$('input[type=submit]').attr('disabled', true);
//Some validations
var form = $(this);
if (validation successful) {
$.ajax({
type: "POST",
url: form.attr('action'),
dataType: "json",
data: form.serialize(),
complete: function(js_data){
alert(js_data);
}
});
return false;
} else {
return true;
}
});
Controller
def create
#if @order.save, the usual
respond_to do |format|
format.json { render json: @order }
end
end
Now this one works a bit better, no redirection or 406 error but it ignores everything in the complete or success block. Hence the page remains the same even when the order was successfully created.
Nb: This page is a subdomain page. e.g. blog1.mysite.com, but it works without js.
My ideal method is the first method. Is there anyway to force the submit to respond to the format.js?
Thanks.
Upvotes: 0
Views: 1084
Reputation: 816
You can manually force the request format to respond to js.
Add a before filter in your controller.
before_filter :default_format_js, only: :create
def default_format_js
reponse.headers['content--type'] = 'text/javascript'
request.format = 'js'
end
Upvotes: 2