Is it possible to make request between two domains? - javascript

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.

Related

How to send OPTIONS Method call to server via ajax jquery/javascript?

I am trying to call an API that accepts OPTIONS method on server, it runs on postman and returns json object but following code is not working on js
I have read that OPTIONS call is a preflight call for CORS calls, so this API is https and on another server. But even then there is no response and it returns 405 method not found
$.ajax({
url: url,
dataType: "jsonp",
method :"OPTIONS",
crossDomain: true,
contentType: 'application/json',
headers: {
"Content-type": "application/json",
"Cache-Control": "no-cache",
"Accept": "application/json,long_format",
"Access-Control-Allow-Origin": "*"
},
success: function (data) {
console.log("success" + data);
},
error: function (data) {
console.log("fail" + data);
}
}).fail(function(data) {
console.log("failed" + data);
});
Extra info :
The API is cross domain and on ssl so to cover cross domain request I had to user dataType: "jsonp"
UPDATED :
This is impossible scenario so I have to get update on server end...
Explanation:
There is some problem with
OPTIONS method that is behind cross domain as well
a/c to some research i have done on internet, CORS request can be accessed with :
dataType: "jsonp",
but with -> dataType: "jsonp"
you can only call GET methods
so we are stuck here that allows that either we call cross domain https request or we can call OPTIONS method,
usually OPTIONS method is a preflight method done automatically by browser
NOW please stop down voting my question
dataType: "jsonp",
Take this out. JSONP requests are always GET requests. This is your main problem.
crossDomain: true,
Take this out. It does nothing unless you are making a same origin request that gets redirected to be a cross origin request.
contentType: 'application/json',
Take this out. You are making an OPTIONS request. There is no request body to describe the content-type of.
"Content-type": "application/json",
Take this out. For the same reason.
"Access-Control-Allow-Origin": "*"
Take this out. It is a response header and has no place on the request.

Instagram API. XMLHttpRequest cannot load URL. Response for preflight has invalid HTTP status code 405

I'm pretty new on using APIs and I am having a problem with Instagram's new api.
For a dislike function, the documentation states to use a delete method, but I keep getting an error: XMLHttpRequest cannot load URL. Response for preflight has invalid HTTP status code 405.
Funny thing is that when I try the exact same thing with curl, it works.
For example, this is a working method: curl -X DELETE https://api.instagram.com/v1/media/{media-id}/likes?access_token=ACCESS_TOKEN
But if I try to use it with javascript
if( user_has_liked ){
$.ajax({
crossDomain: true,
url: "https://api.instagram.com/v1/media/"+ photoId +"/likes?access_token=" + ACCESS_TOKEN,
method: 'DELETE',
success: function(data){
response = data.data;
document.getElementById(photoId).className = "fa fa-heart-o";
document.getElementById(photoId).onClick = function(){
subscribe(photoId, false);
}
}
});
}
All I get is a 405 error.
I've tried enabling CORS but it seem to work either
I would be really grateful if anybody could give me a hand on this.
Many thanks!
I solved this issue sending a request utilizing the POST method and "delete" like a parameter. Then it is looking like this:
$.ajax({
url: "https://api.instagram.com/v1/media/"+ photoId +"/likes?access_token=" + ACCESS_TOKEN,
method: 'POST',
data: {_method: 'delete'},
success: function(data){
console.log(data);
}
});
Font: http://laravel.io/forum/02-20-2014-sending-a-delete-request-via-ajax

$.post (to different domain) not working (node.js / express app on port 8081)

I receive the error POST https://thewebsite.com 400 (Bad Request) when using $.post that way:
$.post("https://website.com/blabla",
{
domain: "infoinfo.com",
room: "someInfo",
application: "someInfo",
ident: "someInfo",
},
function (data,status) {
alert("Data: " + data + "\nStatus: " + status);
});
I tried setting res.header('Access-Control-Allow-Origin', "*"); in my route but that didn't work.
Any ideas on how I could fix this?
Ps.: The server I am posting to is service website (xirsys.com), I am pretty sure they allow external domains already. I'll contact them during the day if I can't find a solution (I am using the jQuery post as they suggested :/
Try to add this to your AJAX call:
contentType: "application/json; charset=utf-8",
dataType: "json"
Another reason maybe because of the same origin policy:
In computing, the same origin policy is an important security concept
for a number of browser-side programming languages, such as
JavaScript. The policy permits scripts running on pages originating
from the same site to access each other's methods and properties with
no specific restrictions, but prevents access to most methods and
properties across pages on different sites.
You can find out more informations about this issue from MDN docs or doing some research on Google about this topic.
You can try to use $.axax() like this:
$.ajax({
type: 'POST',
url: "https://website.com/blabla",
data: {
domain: "infoinfo.com",
room: "someInfo",
application: "someInfo",
ident: "someInfo"
},
dataType: "json",
contentType: "application/json",
success: function (e) {
alert("Data: " + data + "\nStatus: " + status);
}
});
This is due to the Same-origin policy. All the browsers as a security measure would not allow any cross domain requests.
http://en.wikipedia.org/wiki/Same-origin_policy
Like in your case you are posting to thewebsite.com domain from a different domain. A work around is to use the jsonp (the server should support json padding) from the jquery.
Check these sites for more info
http://www.jquery4u.com/json/jsonp-examples/
http://en.wikipedia.org/wiki/JSONP
http://stackoverflow.com/questions/6871021/how-to-enable-cross-domain-request-on-the-server
SAMPLE REQUEST:
$.ajax({
url: "http://yoururl",
type: "POST",
crossDomain: true,
data: JSON.stringify(somejson),
dataType: "json",
success: function (response) {
alert("success");
},
error: function (xhr, status) {
alert("error");
}
});
SAMPLE RESPONSE IN PYTHON:
response = HttpResponse(json.dumps('{"status" : "success"}'))
response.__setitem__("Content-type", "application/json")
response.__setitem__("Access-Control-Allow-Origin", "*")
return response
The link I was posting to was actually not good. The service I am using updated the link in their API to reflect the right one.

Jquery unable to get the response from WCF REST service

I have developed WCF rest service and deployed it on a link that can be accessed via the browser because its action is "GET".
I want to get that data using jQuery. I tried my best to get WCf get response using jQuery
but in vain. I also tried $.Ajax with 'jsonp' with no luck. Can any one help me?
The url is: http://www.lonestarus.com/AndroidApp/AndroidLocation.svc/RestService/getLatestLocation
You can check that url response by pasting url in browser.
You need to set Access-Control-Allow-Origin to value [*] in your response header.
this blog gives the more details how it can be done in WCF REST service
if you were to do this in Web API you could have just added
Response.Headers.Add("Access-Control-Allow-Origin", "*")
calling the service using a fiddle
$(function() {
$.ajax({
url: "http://www.lonestarus.com/AndroidApp/AndroidLocation.svc/RestService/getLatestLocation",
datatype: 'json',
type : 'get',
success: function(data) {
debugger;
var obj = data;
}
});
})​;​
I got the error
XMLHttpRequest cannot load
http://www.lonestarus.com/AndroidApp/AndroidLocation.svc/RestService/getLatestLocation.
Origin http://fiddle.jshell.net is not allowed by
Access-Control-Allow-Origin.
I can't make a cross domain example to show you but
$('#a').load('http://www.lonestarus.com/AndroidApp/AndroidLocation.svc/RestService/getLatestLocation​​​​​​​​​​​​​​​​​?callback=run');​
would work had those things been set.
Your service needs to either enable JSONP callbacks or set the Access-Control-Allow-Origin header for cross domain requests to work, or you need to run the script from the same domain. Given that your url says AndroidApp I'm thinking you want cross domain.
Sample code below:
$.ajax
(
{
type: 'GET',
url: http://www.lonestarus.com/AndroidApp/AndroidLocation.svc/RestService/getLatestLocation,
cache: false,
async: true,
dataType: 'json',
success: function (response, type, xhr)
{
window.alert(response);
},
error: function (xhr)
{
window.alert('error: ' + xhr.statusText);
}
}
);

How can I use make HTTP calls to an API in Javascript?

How can I use public APIs in a Javascript application? For example I want to make a call to the Zillow API using JQuery AJAX.
When issuing the request in JQuery AJAX (shown below) I get the following error:
XMLHttpRequest cannot load "MY HTTP REQUEST URL". Origin "MY WEB DOMAIN" is not allowed by Access-Control-Allow-Origin.
var requesturl = "http://www.zillow.com/webservice/GetRegionChildren.htm?zws-id="+zwsid+"&state="+state+"&city="+city+"&childtype=neighborhood";
Code:
var jqxhr = $.ajax({
url: requesturl
})
.done(function(data) {
console.log(data);
});
I've also tried adding crossDomain, dataType and headers params (shown below), but they haven't helped.
var jqxhr = $.ajax({
url: requesturl,
crossDomain: true,
dataType: 'xml',
headers: { 'Access-Control-Allow-Origin': '*' },
beforeSend: setHeader
})
.done(function(data) {
console.log(data);
});
Most popular public API's support JSONP request. Refer API documentation for details.
Cross ajax domain request is restricted. So you will be needing to make JSONP request. Don't worry JQuery will handle most of it.
Sounds like you need to register your url with Zillow, maybe contact them / hunt around on their doc pages. Also jquery has a get method which makes ajax requests even simpler. There's also getJSON if that is the return format.

Categories