Search code examples
ajaxrestcross-domainrestler

Restler 2 cross domain POST AJAX call


I've built my server with a simple REST API using Restler 2. Now I'm trying to do a POST request to that API from my localhost with AJAX, and I see that a OPTIONS request is being sent before, and Restler doesn't handle it.

I added this

header('Access-Control-Allow-Origin:  *');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, PATCH, DELETE');
header('Access-Control-Max-Age: 1000');
header('Access-Control-Allow-Headers: *');

to the index.php of my server, as suggested here for Restler 3, but that didn't solve it. I also took a look at this question and tried what the last 2 answers suggest (almost same thing as before), but didn't work too. Do I really need to use jsonp (first answer referred question)? Isn't that awkward to actually be sending GET requests instead of POST?

My AJAX call:

$.ajax({
    type: "post",
    url: "http://{MY_URL}/index.php/paint", 
    dataType: "json",
    contentType: "application/json",
    data: JSON.stringify(data), 
    success: function(data){ 
        console.log("post success " + data);
    },
    error: function(xhr,err){
            console.log("readyState: "+xhr.readyState+"\nstatus: "+xhr.status);
            console.log("responseText: "+xhr.responseText);
            console.log(err);
    }
});

and the output is:

OPTIONS http://{MY_URL}/index.php/paint 404 (Not Found) jquery-1.10.2.js:8706
XMLHttpRequest cannot load http://{MY_URL}/index.php/paint. Invalid HTTP status code 404 

Solution

  • For a future reference for someone ending up here with the same problem.

    Simply adding this headers on the index.php didn't work.

    header('Access-Control-Allow-Origin:  *');
    header('Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, PATCH, DELETE');
    header('Access-Control-Max-Age: 1000');
    header('Access-Control-Allow-Headers: *');
    

    However, found a solution in this post. So, I added the following code to the beggining of index.php and it works with a simple json request (don't need jsonp).

    // Allow from any origin
    if (isset($_SERVER['HTTP_ORIGIN'])) {
        header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
        header('Access-Control-Allow-Credentials: true');
        header('Access-Control-Max-Age: 86400');    // cache for 1 day
    }
    
    // Access-Control headers are received during OPTIONS requests
    if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    
        if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
            header("Access-Control-Allow-Methods: GET, POST, OPTIONS");         
    
        if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
            header("Access-Control-Allow-Headers:        {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
    
        exit(0);
    }