Topic: Classic AJAX calls

Hello to the forum. I am new to RoR and i am trying to make ajaxfy things.

I read some articles about Unobtrusive javascript. I see that remote attribute works ok.
My question is.
Is it a bad practice to use classic AJAX calls for forms.links etc.. ??

To do that i have to write an if statement about request.xhr. As far i read in rails 3 we dont use that anymore.

So if i use it what am i missing??

I hope i didn't confuse you

Last edited by dianikol (2013-02-03 13:27:31)

Re: Classic AJAX calls

Can you give me an example?

Learning rails, one day at a time.

Re: Classic AJAX calls

Let's say in my Controller i have an index action  about users

def index
  @users = params for a search fields)
  if request.xhr?
    # render a partial
    # redirect to index

In my view

<%= form_for @users, :url => { :action => 'index' },:id => "form-id" |f| %>
  <%= f.text_field :username %>
  <%= f.submit "Search", :name => nil %>
<% end %>

In my js file

(function ($) {
    $.ajax(# make the AJAX call to the form's url with the values from this form  )
    return false;

A very simple example without using the

 :remote => true 

which i believe it works ok.

In this example i use 


in the controller to see if the call was done via ajax.

What do you think about this technique. Is this approach considered as a good practice or i should use the jquery-ujs??

I hope it is clear noe smile

Re: Classic AJAX calls

I would assume you would still use request.js.

Check out this stack overflow question: … controller

You have to set the 'accept' header before sending the ajax request so that Rails knows how to respond.

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

Not sure if that is correct, but at least it is a start.

Learning rails, one day at a time.