I have a standard controller which is set up to respond to HTML, JS and JSON requests:
def picture
@picture = Picture.new params[:picture]
respond_to do |format|
if @picture.save
format.html do
logger.debug "In the HTML responder"
redirect_to @picture
end
format.json { render json: @picture, status: :created, location: @picture }
format.js { render :nothing => true }
else
# you get the idea
end
end
end
Now I'm trying to send a request to that controller with the $.ajax
function (I can't use :remote => true
in this specific situation - I'm trying to make ajax file upload work).
$.ajax({
url: $("form#new_picture").attr("action"),
type: "POST",
data: formdata,
processData: false,
contentType: false
});
The problem is that my request is being treated as a HTML request for some reason. How do I tell rails that I want a JS response?
By the way, I'm using jquery_ujs in my project so I have access to the methods it provides if necessary. I'm not really good enough at JS to tweak that to do what I need here.
Just add dataType: 'script'
$.ajax({
url: $("form#new_picture").attr("action"),
type: "POST",
data: formdata,
processData: false,
contentType: false,
dataType: 'script'
});
This solution didn't work for me (rails 3.1 + coffeescript). After searching quite a lot, I found the good way to do it and I wanted to share:
Just add ".js" to the end of the url. So simple... ;-)
You have to set the 'accept' header before sending the ajax request so that Rails knows how to respond.
$.ajax({
url: $("form#new_picture").attr("action"),
type: "POST",
data: formdata,
processData: false,
contentType: false,
beforeSend: function(xhr, settings) {
xhr.setRequestHeader('accept', '*/*;q=0.5, ' + settings.accepts.script);
}
});
Add dataType: 'script'
and in data of form add the parameter format: 'js'
like this:
$.ajax({
url: '/manager/consumers/url',
type: 'GET',
dataType: 'script',
data: {
authenticity_token: '<%= form_authenticity_token %>',
param_1: '1',
param_2: '2',
format: 'js'
}
});
also add in the controller to not render layout:
respond_to do |format|
format.xls
format.js { render :layout => false }
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With