Ajax Cross-domain Php proxy 403 error - javascript

I'm trying to consume a third party Api using javascript and a PHP proxy as seen in this Tread, i'm able to use the proxy but the response I get, is always:
Failed to load resource: the server responded with a status of 403 (Forbidden)
http://MYDOMAIN.co/php/ba-simple-proxy.php?url=http://jsonplaceholder.typicode.com/posts&_=1471620448707
my javascript code is:
function getLocationSimple(){
var proxy = 'php/ba-simple-proxy.php',
url = proxy + '?url=' + 'http://jsonplaceholder.typicode.com/posts';
console.log(url);
// Make JSON request.
$.getJSON( url, function(data){
console.log(data);
});
}
I thought it was about permissions on the third party server, so i decided to change it to an open one - http://jsonplaceholder.typicode.com/posts -, but i still get the same error, it might be permissions in my own server? -my host is hostgator-

Let's try once this piece of code
function getLocationSimple(){
$.ajax({
type: 'POST',
dataType: 'jsonp',
url: "http://jsonplaceholder.typicode.com/posts"
}) .done(function( data ) {
console.log( data);
});
}
this happens due to Cross-Domain Policy. Cross site access is not available in the api side . So we can use dataType: 'jsonp' to overcome this issue

This has something to do with the Cross-Domain Policy. You can't do ajax requests to another domain due to security reasons, because a malicous attack could also involve to do a request via ajax to load additional script to hack you.
Even though Wikipedia might not be the best link to provide, it'll give you an idea.
https://en.wikipedia.org/wiki/Same-origin_policy

Related

Why does my API call work in chrome but not in my code?

I'm trying to call the Binance API to get the LTC price in BTC and I tested the link on my browser "https://api.binance.com/api/v1/ticker/price?symbol=LTCBTC" How do i get the json file from that link into my javascript file?
$(document).ready(function() {
var url = 'https://api.binance.com/api/v1/ticker/price?symbol=LTCBTC';
$.ajax( {
url: url,
dataType: 'jsonp',
type: 'GET',
success: function(data) {
console.log(data); //returns nothing
}
});
})
As mentioned in other answer, there is CORS issue. So you can try with proxyURL from client side as below,
$(document).ready(function() {
var url = 'https://api.binance.com/api/v1/ticker/price?symbol=LTCBTC';
const proxyURL = "https://cors-anywhere.herokuapp.com/";
$.getJSON(proxyURL + url, function(playerData) {
console.log(playerData);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Hope it helps.
The request to https://api.binance.com/api/v1/ticker/price?symbol=LTCBTC provides json data this uses CORS policy
{"symbol":"LTCBTC","price":"0.01520100"}
JSONP would look like
myCallback({"symbol":"LTCBTC","price":"0.01520100"})
This looks like and works like a Javascript / PHP function.
The URL for a jsonp includes a callback in the URL ... https://api.binance.com/api/v1/ticker/price?symbol=LTCBTC&callback=myCallback
But is not supported on this site
{"code":-1101,"msg":"Too many parameters; expected '1' and received
'2'."}
It might be openable with php on your site? I can not test from the system I'm on I don't have socket transport "ssl" setup on my tablet to test.
Yes it works from a PHP wrapper.
myJSONP(<?php echo file_get_contents('https://api.binance.com/api/v1/ticker/price?symbol=LTCBTC');?>);
If you check on console after change dataType: 'jsonp' to dataType: 'json', you will get the following as your code and their script not on same host and they need to enable Access-Control-Allow-Origin to access from other domain. You may use cur if you use php.
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://api.binance.com/api/v1/ticker/price?symbol=LTCBTC. (Reason: CORS header 'Access-Control-Allow-Origin' missing).
While performing the request from your browser or postman or fiddler you will get the result
But while performing a request from the application you will be failed with error message
Access to XMLHttpRequest at 'https://api.binance.com/api/v1/ticker/price?symbol=LTCBTC' from origin 'http://127.0.0.1:5500' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
The issue has to be fixed from your server side end.
Please refer
Cors understanding
Also, find the solution to the problem if you're using C# .Net as your backend
Solution for cors

How to set up CORS in an AJAX request

I have been working on a personal webapp and have hit a little snag. My API calls only work for some APIs and not for others. For the ones it doesn't work with I will usually get an error message like so.
XMLHttpRequest cannot load https://api.meetup.com/2/cities. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
After doing some research I know it is to do with CORS not being setup. I was wondering if it would be possible to set this up in the client when making an AJAX request. The current way I am doing this is like so
var handleRequest = function(request){
$.ajax({
type: "GET",
url: request,
success: function(data) {
var rawJSON = JSON.stringify(data, null, 2);
editor.setValue(rawJSON);
},
dataType: 'json'
});
The server you're trying to access has to grant you permission to access it. An IT admin has to provide you with a URL that grants you permission to hit their external server. The server you are trying to hit has to setup CORS. http://enable-cors.org/
According to their docs they support JSONP.
https://www.meetup.com/meetup_api/
This is your way around CORS.

I thought ajax was same orgin policy?

I'm confused about the same domain orgin policy with jquery ajax. If i make a get request to a url with jquery, I can get the results back. What am I missing? I thought it was restricted to same orgin policy.
$(function () {
var data;
var x = $.ajax({
dataType: 'json',
url: 'http://jsonplaceholder.typicode.com/posts',
data: data,
success: function(){ console.log("true");},
failure: function(){console.log("failed");}
});
console.log(x);
});
See this page.
API can be accessed from your development environment through CORS or JSONP.
Yes, it is, but the website you are requesting specifically allows CORS (cross-origin resource sharing) as well as JSONP requests, meaning you can request the data from another origin using either one of those methods. Using the .ajax() method with dataType: 'json' means you are using CORS. You could also make a JSONP request with dataType: 'jsonp'.
Both CORS and JSONP are specific server options that can be enabled to allow users to request data from another origin. Keep in mind that the data could be modified on the server to be malicious, so it could be a potential security hole if you begin using that data. Be sure to only use CORS or JSONP with a service you trust.

consuming PHP service returning valid json with $.ajax

I've been stuck on consuming a web service created in PHP, not sure what I'm doing wrong.. Ive created a fiddle example here : http://jsfiddle.net/e97AV/
I've tried various combinations of things but keep on getting 404 not found feedback, when I specify jsonp i get no error message, but in the web console i can see a 404 error.. in the browser when I visit the url it is returning valid json
My question is how would I know when to use jsonp or json? Also these service have been provided to me from an external source other than agreeing on json being returned how would I know if the problem is on my side or theirs?
heres the ajax code
baseUrl = "http://exclusivegetaways.co.za/api.php";
$.ajax({
type: "GET",
url: baseUrl,
data: {something : "something"},
//contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
alert("works");
alert(result);
},
error: function (a,b,cc) {
alert(a+b+cc);
}
});
I've since been able to pull json data from the ajax error object?? like so:
baseUrl = "http://exclusivegetaways.co.za/api.php?something=something";
$.ajax({
type: "GET",
url: baseUrl,
dataType: "json",
success: function (res) {
alert("worked");
//alert(res);
},
error: function(jqxhr) {
try {
f = JSON.parse(jqxhr.responseText);
...valid json returned here
} catch(err) {alert(err);}
}
});
This is because of a security restriction that prevents Ajax from querying remote locations.
As a workaround to enable access to a remote location via Ajax, you could build a custom URL in your webApp (in PHP for instance) which queries the distant API and returns JSON.
Then, in your JavaScript, you call this URL (from your application) via Ajax.
First: Always look at your JavaScript error console.
XMLHttpRequest cannot load http://exclusivegetaways.co.za/api.php?location=provinces.
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'http://fiddle.jshell.net' is therefore not allowed access.
See also Ways to circumvent the same-origin policy
I've tried various combinations of things but keep on getting 404 not found feedback, when I specify jsonp i get no error message, but in the web console i can see a 404 error. in the browser when I visit the url it is returning valid json
This suggests that:
They don't support JSONP
They look at the HTTP headers and 404 your request to block access from Ajax (this isn't a good way to do that, the error code is misleading)
My question is how would I know when to use jsonp or json?
Usually by reading the documentation for the server you are trying to use
Also these service have been provided to me from an external source other than agreeing on json being returned how would I know if the problem is on my side or theirs?
Usually by working with whatever support is provided by the API provider (i.e. start with their documentation, then fall back to whatever means they provide for communicating with a human).
Due to Same Origin Policy your ajax request is allowed only if:
domain name, application layer protocol, and (in most browsers) port
number of the HTML document running the script are the same
In your case the application layer protocol is different, that's why your script fails.
Possible solutions are:
JSONP, which has to be provided by the server
CORS, which is a more 'elegant' and clean solution, but is not yet fully supported by IE (IE7 doesn't support it, IE8 has some limitations)
Answer taken from this link

Cross domain ajax GET parameters not allowed

I'm trying to get data from an API with javascript but i'm getting an error on the request.
$.ajax({
dataType: "jsonp",
url: "https://www.bitstamp.net/api/ticker/",
type: "GET",
succes: myfunction
});
result:
{"error": "GET parameters not allowed for this request."}
I use Jsonp because its another domain.
Why can't I get the data with Jquery?
If I just browse to the link I can see the Json.
I just tried getting data from the url you provided using AJAX. The server did not return any data using the $.ajax and this clearly shows that the server does not support cross domain requests. That is why I asked you if you had access to code because you have to manually specify if you want API to support cross domain requests.
One way around to this is using some server side language to access this API. I once had similar problem and the used PHP CURL to access the API. The php code then served data to JQuery to be used on frontend. So you can write relay code to solve this problem.
Because, as the error message says, bitstamp do not allow it.
If they get a JSONP request for the data, they respond with the error instead of the normal response.

Categories