Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use the rails remote: true parameter with JSON?

How do I specify that I want a JSON object to be returned when submitting an ajax request with the rails remote: true parameter? And once the JSON object is returned how do I catch and use it?

like image 345
Rebekah Waterbury Avatar asked Jun 13 '12 19:06

Rebekah Waterbury


1 Answers

There are many ways to answer this depending on your specifics (eg: you are using jquery and the UJS adapter) but I'm going to post stuff from a doc I'm using myself to better understand the whole process: I use this Great post to a large degree: I'll update my answer as I am currently working through this stuff myself too.

You can add the data-type attribute to the DOM element like this:

<%= link_to "Add a new task", new_project_task_path(@project), "data-type" => "json", :id => "add_task_btn" %>

You can also define a default dataType in jQuery's global $.ajaxSetup() function. Changes all Ajax requests:

$.ajaxSetup({
      dataType: 'json'
});

And the third way is in the beforeSend callback:

$(“#add_some_button”).live(“ajax:beforeSend”, function(e, xhr, settings){
        new_data_type = “application/json, text/javascript, */*; q=0.01”;
        xhr.setRequestHeader('accept', new_data_type);
})

(the q=0.01 is the preference between 0 and 1)

So you can change that  dataType property and HTTP Headers to fit your needs. For reference here is a list of possible MIME types: Here

And the specific javascript media type list: Here

Overview of data format being sent back from the server: 1.) Ajax sends the request with the Accept header set to the desired MIME type. 2.) Rails Controller checks the Accept header to determine what it should return. 3.) Controller will determine whether the action handles the particular MIME type. In rails 3 we can use respond_with, pre 3.0 its a respond_to block in the controller action.

Overview of the ways Ajax can be used in Rails 3.1:

I believe that the preferred method now is to use the default dataType as script and then handle AJAX requests with either a js.erb or a js.coffee file.

Options:  1.) Click Event: Inserting DOM Elements 2.) Submitting a Form via Ajax 3.) Deleting via Ajax 4.) Client-side Validation with Ajax (Using data-remote on an input field) 5.) Adding Dynamic Selects (Using data-remote on a select field) 6.) Ajax Pagination – Return HTML directly. 

Again what I am including here is my own outline/review, to get details please check out Andrea Singh's great post here.

like image 124
craigmartin Avatar answered Sep 21 '22 02:09

craigmartin