Search code examples
jqueryruby-on-railsajaxprototypejs

Converting Prototype AJAX Call with RJS to just jQuery


I am running a Rails 3.0 Application with Prototype and RJS. I want to convert over to just use jQuery.

My questions are

1. Is it possible to just get rid of RJS completely when using jQuery?

and

2. If not, how do I convert the following:

I have the following DIV element in my index.html.erb:

<div id="students"></div>

I have a ajaxCalls.js.erb containing the following:

$.ajax({
    url: '<%=populate_students_path()%>',
    type: 'POST',
    data: 'authenticity_token=' + AUTH_TOKEN,
    dataType: 'html', // Consider changing to HTML if this doesnt work
    beforeSend: function (xhr) {
      xhr.setRequestHeader("Accept", "text/javascript");
    }
  }).done(function (data) {

    // TODO Populate table with populate function
    var users_table = $('#students').dataTable({
      'aData': data
    });
  });

In which I get the following response:

try {
populate("{\"54\":{\"section\":\"-\",\"filter_table_row_contents\":\"<td>\\n  c5leharf\\n</td>\\n<td>\\n  Lehar\\n</td>\\n<td>\\n  Franz}")
}

I have a populate.rjs which contains:

page.call "populate", @students.to_json

Which may call the following, but I am unsure:

function populate(json_data) {
  users_table.populate(json_data);
  users_table.render();
}

So, the question here is**

How do I make my response render correctly? How do I remove the populate function from the data retrieved from the AJAX call? How do I get just plain JSON?

Edit: Kaeros's answer worked, with my controller looking like:

respond_to do |format|
  format.json { render :json => @students_data } 
end

Solution

  • You can use an ajax method like the one you are using (expecting json from the server):

    $.ajax({
        url: '<%=populate_students_path()%>',
        type: 'POST',
        data: 'authenticity_token=' + AUTH_TOKEN,
        dataType: 'json',
        beforeSend: function (xhr) {
          xhr.setRequestHeader("Accept", "text/javascript");
        }
      }).done(function (data) {
        //Do something with the data received as json
      });
    

    And in you controller method you just have to return json.

    respond_to do |format|
      format.json { render json: @some_instance_variable }
    end