0

I'm new to Rails and I was trying to right very simple ajax call in application.js.

Here's the code:

function login(loginUrl) {
    alert(loginUrl);

    $.ajax('http://www.w3schools.com/jquery/demo_test.txt', {success: function (result) {
        alert(result);
    }});
}

When the function is called, the first alert works well. However, it seems that the following ajax call never gets through and the second alert never executes. I tried the code at w3school.com and it works well. I'm really confused why this simple code doesn't work with Rails.

Could anyone please help me?

doppelgreener
  • 4,809
  • 10
  • 46
  • 63
user2142709
  • 2,523
  • 4
  • 16
  • 12

2 Answers2

0

This is because of a browser restriction called Same Origin Policy. It prevents javascript from sending ajax request to a domain different from where it is loaded.

In your case you are trying to access a resource (http://www.w3schools.com/jquery/demo_test.txt) hosted at http://www.w3schools.com but page which send the request is not from the same domain that is why the ajax request is not working.

If you look at your browser's console, you may be able to see an error saying the same.

A solution for Same Origin Policy is to use jsonp (What is JSONP all about?), but the constraint is the server should support jsonp.

Community
  • 1
  • 1
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
0

replace 'http://www.w3schools.com/jquery/demo_test.txt' this by your loginUrl

Sachin R
  • 11,606
  • 10
  • 35
  • 40