jQuery.ajax cannot find server when use an alias defined in "hosts" file, but can with ip address - how fix?

StackOverflow https://stackoverflow.com/questions/23176394

  •  06-07-2023
  •  | 
  •  

Question

I have defined an alias in my hosts file (on linux): 192.168.1.123 mysite-example.com. When I go to this in a web browser, it works. But when my JavaScript calls for a jquery ajax post, it doesn't work.

THIS DOES NOT WORK

$.ajax({
        url: "http://mysite-example.com/mypage.php",
        data: { "test": "test" },
        success:function(data) {
            console.dir(data);
        },
        error: function(errorThrown){
            console.dir(errorThrown);
        }
});

THIS DOES WORK

$.ajax({
        url: "http://192.168.1.123/mypage.php",
        data: { "test": "test" },
        success:function(data) {
            console.dir(data);
        },
        error: function(errorThrown){
            console.dir(errorThrown);
        }
});

What is causing this? How do I fix this?

Was it helpful?

Solution 2

The error was due to how domains are interpreted. When I was loading the client-side page, I loaded it from 192.168.1.123, the actual ip address of the server. But it was requesting the server by domain name. Since multiple domains can be on the same server, this (I believe) causes the browser to interpret them as cross-origins and thus rejects it.

When I visited the client page (with the ajax call) at the domain name (http://mysite-example.com), the ajax call works.

(I can also make it work by adding the header header('Access-Control-Allow-Origin: *'); on the server, but that's not a good idea.)

OTHER TIPS

Check main domain. In question is other that your JS ajax

question: mysite-example.com js: mysite.example.com

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top