M
M
Maxim2016-05-12 11:14:49
JavaScript
Maxim, 2016-05-12 11:14:49

How to send a request to another server/domain using ajax post?

I try like this

var data = {
    name: 'test',
    surname: 'test',
    hobbies: ['hobby1','hobby2','hobby3','hobby4'],
    location: 'test'
};
$.ajax({
                type: "POST",
                url: "http://myothersite.com/ajaxService/DoWork",
                data: JSON.stringify({data: data}),
                success: function (response) {
                    // some code
                },
                error : function (response) {
                    
                    if (typeof response !== 'undefined' && response)
                    {
                        reason = $.parseJSON(response.responseText).Message;
                    }
                    console.log(reason);
                },
                dataType: "json",
                contentType: "application/json; charset=utf-8"
            });


But I get this:
Request URL:http://myothersite.com/ajaxService/DoWork
Request Method:OPTIONS
Status Code:405 Method Not Allowed

In console:
XMLHttpRequest cannot load myothersite.com/ajaxService/DoWork . Response for preflight has invalid HTTP status code 405


If I send the same request from a domain with myothersite.com, then everything is ok.
And by the way, for some reason the request is sent OPTIONS, not POST, is that normal?
Headers are registered on the server:
Access-Control-Allow-Headers:Content-Type, Authorization, Accept, X-Requested-With
Access-Control-Allow-Methods:OPTIONS, TRACE, GET, HEAD, POST, PUT
Access-Control-Allow-Origin:*


Thanks in advance.

Answer the question

In order to leave comments, you need to log in

4 answer(s)
_
_ _, 2016-05-12
@AMar4enko

OPTIONS is a so-called preflight request that precedes any requests to third-party domains, as required by CORS.
The server must be able to respond to it (and not just the method must be written in the headers).
At a minimum, the server should respond to OPTIONS with 200 OK and send CORS policy headers.
Based on the response to OPTIONS, the browser decides whether to send data or not. Your server is responding with an error.

E
Eugene, 2016-05-12
@Nc_Soft

ok google "CORS"

A
Andrey Pavlenko, 2016-05-12
@Akdmeh

It is not possible to make an AJAX request to another domain, this is the browser's security system.
You need to use jsonp technology: https://learn.javascript.ru/ajax-jsonp
(well, it’s possible, but it’s easier to make jsonp, plus it is supported by all browsers, there may be certain problems with CORS).

O
OlegLustenko, 2016-05-14
@OlegLustenko

The server responds with 405 and the method is not available, so it is. Something is not spelled out, or spelled out incorrectly

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question