Donato Donato - 3 months ago 19
Javascript Question

Using jquery in ajax request to get javascript response UJS

In Rails, you can respond to different MIME types, including

application/javascript
. You often use this MIME type for ajax requests to send javascript back to the browser to be evaluated. The
respond_to
symbol is
:js
.

I see examples like this:

<%= form_tag('/articles', remote: true) do %>
...
<% end %>

<%= link_to "Delete article", @article, remote: true, method: :delete %>


The rails.js file finds the remote links, forms, and inputs, and overrides their click events to submit to the server via AJAX.

Server has something like this:

respond_to do |format|
format.js
end


In my situation, I need to do the request in jQuery, so I cannot use the remote: true feature.

<%= form_for @tag do |f| %>
<%= f.fields_for :taggings, f.object.taggings.build do |taggings_builder| %>
<%= taggings_builder.hidden_field :tagging_flag, value: @contact.flag %>
<% end %>
<%= f.text_field :name, class: 'form-control', placeholder: 'Add a tag and press enter' %>
<% end %>


My problem is when I specify
contentType
as
'application/javascript'
in jquery
ajax
method, no form data is sent to server. I even inspected it in Network tab on chrome.
When I remove the
contentType
property, the form data is submitted to server but the the content type is not '
application/javascript
'. It is '
application/x-www-form-urlencoded; charset=UTF-8
'.

My jquery looks like this:

$view.on('keypress','form#add-tag input#tag_name', function(e){
var $form = $(this).closest('form');
var key = e.which;

if(key == 13){

$.ajax({
type: "POST",
data: $form.serialize(),
contentType: 'application/javascript',
url: $form.attr('action'),
beforeSend: function() {
$('.loading').show();
},
complete: function(){
$('.loading').hide();
},
success: function(resp){
}
});


return false;
}
})


How can I send the form data to server with the content type of 'application/javascript'?

Answer

The contentType option is used to specify the format of the parameters being sent to the controller. To specify the type of data expected in response, use the dataType option; specifying script means you expect Javascript, and this will send the Accept: application/javascript header that tells the controller which respond_to block should be used.

  $.ajax({
     type: "POST",
     data: $form.serialize(),
     dataType: 'script',
     url: $form.attr('action'),
     beforeSend: function() {
       $('.loading').show();
     },
     complete: function(){
       $('.loading').hide();
     },
     success: function(resp){
     }
  });