Is it possible to make xhr
request between domains www.site.mySiteName.com
and api.mySiteName.com
using JavaScript?
I need to get data from my API in real-time but I don't know how to do it.
Is it possible to make xhr
request between domains www.site.mySiteName.com
and api.mySiteName.com
using JavaScript?
I need to get data from my API in real-time but I don't know how to do it.
Making it possible (Opening your API to your webpage):
You can do ajax requests between domains, however, the host has to allow your origin.
You need to append the header to the response (this needs to be done on the API):
Access-Control-Allow-Origin: *
Or something like:
Access-Control-Allow-Origin: site.mySiteName.com
The API will technically respond to any origin unless you specify otherwise regardless of the header; however, the browser will say the request failed if your origin is now allowed.
Additionally, you should be aware that depending on the request your API will have to support preflight "OPTIONS" requests
See:
https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
How does Access-Control-Allow-Origin header work?
To actually make the request in javascript:
You can use jQueries "ajax" to make the request: http://api.jquery.com/jquery.ajax/
Simple get request:
$.ajax({
method: "get",
url: "test.html",
}).done(function(data) {
console.log('got data:' + data);
});
Simple post request:
$.ajax({
method: "post",
url: "test.html",
data: {somekey: 'somevalue'}
}).done(function(data) {
console.log('got data:' + data);
});
Format response as JSON:
$.ajax({
method: "get",
url: "test.html",
dataType: "json"
}).done(function(data) {
console.log('got data:' + data);
});
Note(edit): You could do this in native javascript; on the other hand, using jQuery or AngularJS(a full application framework..) is simpler and adds other useful tools.