Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery ajax request not triggering JS response from rails controller?

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.

like image 858
David Tuite Avatar asked Aug 02 '11 23:08

David Tuite


4 Answers

Just add dataType: 'script'

$.ajax({
  url: $("form#new_picture").attr("action"),
  type: "POST",
  data: formdata,
  processData: false,
  contentType: false,
  dataType: 'script'
});    
like image 45
shlensky Avatar answered Nov 10 '22 16:11

shlensky


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... ;-)

like image 132
ndemoreau Avatar answered Nov 10 '22 16:11

ndemoreau


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);
  }
});
like image 7
David Tuite Avatar answered Nov 10 '22 15:11

David Tuite


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
like image 6
overallduka Avatar answered Nov 10 '22 16:11

overallduka