picardo
picardo

Reputation: 24886

How do I make AJAX request to actions that require authentication in Rails?

I am trying to send an AJAX request to a Rails controller that uses before_filter to authenticate the user. The problem is when the request gets sent, the server asks for authentication even if the user is already logged in.

Here is my AJAX request:

$.ajax({
  type: 'DELETE',
  url: "/messages/delete_all",
  data: [1,2,4],
  success: function() {
        console.log("Your request is received.")
    }
});

When the user hits delete_all from the browser, it works, but with AJAX it doesn't. What gives?

EDIT: could it be related to the authenticity_token?

Upvotes: 0

Views: 2299

Answers (1)

polarblau
polarblau

Reputation: 17734

Maybe this question will help: Using javascript with the twitter API

The solution proposed there should look something like this in your case

$.ajax({    
  type: 'DELETE',
  url: "/messages/delete_all",
  data: [1,2,4],
  beforeSend: function(xhr) {
    xhr.setRequestHeader("Authentication", "Basic  " + encodeBase64(username + ":" + password)
  },
  success: function() {
    console.log("Your request is received.")
  }
});

Upvotes: 1

Related Questions