ajax function does not work

Asked

Viewed 1,011 times

0

I am using this small function to execute my ajax without mimimi, see

var HTTP = 'http://127.0.0.1/';
function ajax(to, data) {
       $.ajax({
type: "POST",
url: (HTTP + to),
data: data, 
cache: false,
success: function(output) {
alert(output);
}
});
    return false;
};
ajax('ds', null);

but it does not run successfully nor occurs water, the problem is in the URL but do not know how to solve :/

  • 1

    In firefox open the option to inspect element (Ctrl+Shift+i) -> Console -> clear all and leave only rede and js enabled. Update the page and execute the functionality that requires ajax.

  • Run the tests on the console. see if there’s anything in the syntax.

  • @Luanfagundes no error :/

1 answer

1

Try to remove the http://127.0.0.1 and just use the relative url, like this:

var HTTP = '/'; or var HTTP = '/index.php';


That’s a bug?

No, this is because of CORS. This feature prevents AJAX requests to Urls that are not from the same address as your page.

So by using the http:// you defined that you would not be pointing to a URL at the same address as the one on the page (127.0.0.1)


How do I resolve?

For the pages that will respond to your request, add the headers of CORS.

I don’t know which server you’re using, but if you have PHP support you can add the headers as follows in index php.

<?php
header("Access-Control-Allow-Origin: *"); // Aceitar requisições de qualquer endereço

Or else

<?php
header("Access-Control-Allow-Origin: meusite.com"); // Aceitar requisições AJAX de meusite.com

Reference & More on the subject

There are many options for CORS and so I won’t quote them all. My source is below.

Source: http://www.html5rocks.com/en/tutorials/cors/ (in português)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.