I am using ajax to get cross domain data.
Due to browser security restrictions, most Ajax requests are subject to the same origin policy; the request can not successfully retrieve data from a different domain, subdomain, port, or protocol (Details) .
So i am using YQL https://code.tutsplus.com/tutorials/quick-tip-cross-domain-ajax-request-with-yql-and-jquery--net-10225 to get html data.
My question is how to make call using external proxy server. For example https://www.pinterest.com/ , so i am using external proxy server with direct url access like https://www.filterbypass.me/s.php?k=https://www.pinterest.com/ .
But the problem is yql query return to null, no response data.
$.ajax({
url: 'http://query.yahooapis.com/v1/public/yql?q=' + encodeURIComponent('select * from html where url="https://www.filterbypass.me/s.php?k=https://www.pinterest.com/"') + '&format=json&diagnostics=true&callback=',
dataType: 'json' ,
success: function(data) {
console.log(data);
}
});
If you are planning to use JSONP you can use getJSON which made for that. jQuery has helper methods for JSONP
$.getJSON( 'http://someotherdomain.com/service.php', function( result ) {
console.log(result);
});
Read the below links
http://api.jquery.com/jQuery.getJSON/
Basic example of using .ajax() with JSONP?
Related
I'm trying to obtain a json object from an api endpoint using jquery and ajax. This is my code:
$.ajax({
url: 'https://this-specific-website.com/customers.json',
type: 'GET',
contentType: 'application/json'
}).done((response)=> {
console.log('HELLLLLO INSIDE response')
console.log('response', response)
})
I also tried the same with the $.getJSON like this:
$.getJSON('https://this-specific-website.com/customers.json', (response)=> {
console.log('HELLO INSIDE response')
console.log('response', response)
})
but I keep getting the following error:
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
Is there a way to fix this issue?
Thank you in advance!!
UPDATE:
I finally did get it to work. Instead of using jquery and ajax on the front end, I created a seperate .js file and used http.get() like this:
Calling a JSON API with Node.js
Use JSONP in case your server supports this, below is the sample. ALternative is do a call to servelet or PHP in same domain which do a backend call and return you the response to your normal AJAX (or AJAX JSON_P)
$.ajax({
url:"testserver.php",
dataType: 'jsonp', // Notice! JSONP <-- P (lowercase)
success:function(json){
// do stuff with json (in this case an array)
alert("Success");
},
error:function(){
alert("Error");
}
});
You can not do a CORS request from the browser if the server you are requesting the JSON from does not have it enabled. You can try JSONP if they support that.
If you are running on a backend then you can do a server-to-server request and that should work.
For example if you are on a PHP server use:
<?php echo file_get_contents("https://this-specific-website.com/customers.json"); ?>
I'm trying to use the deezer api to look up artists and display their name and image using Jquery. Here's my code:
$.getJSON('http://api.deezer.com/search/artists?q='+q+'',
function(data) {
$("#artists").empty();
$.each(data, function(i,item){
var y=item.picture;
var z=x+y;
$("#artists").append("<div id='card_artist'><div id='cardimg' style='background-image: url("+ z +");'></div><div id='artistname' class='jtextfill'><span>" + item.name + "<span></div></div>");
});
});
but it just won't work. The code seems fine, but it keeps throwing up this error message, which I haven't a clue about or how to fix:
XMLHttpRequest cannot load http://api.deezer.com/search/artists?q=whatever. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
How do I get it to work?
The error is thrown because your browser is blocking the request. Because you execute this from javascript from your own site or maybe localhost, you do a cross-site request by calling a different url (the Deezer url). There are multiple ways to solve this problem.
Try the following 'hack' with jsonp:
// Using YQL and JSONP
$.ajax({
url: "http://api.deezer.com/search/artists?q="+q,
// the name of the callback parameter, as specified by the YQL service
jsonp: "callback",
// tell jQuery we're expecting JSONP
dataType: "jsonp",
// tell YQL what we want and that we want JSON
data: {
format: "json"
},
// work with the response
success: function( response ) {
$("#artists").empty();
$.each(data, function(i,item){
var y=item.picture;
var z=x+y;
$("#artists").append("<div id='card_artist'><div id='cardimg' style='background-image: url("+ z +");'></div><div id='artistname' class='jtextfill'><span>" + item.name + "<span></div></div>");
}
});
Source: https://learn.jquery.com/ajax/working-with-jsonp/
Or 2. You route the request through your own server.
With a server side language like php you do the request to the Deezer Api, and with jQuery you call that php page.
I had read earlier that cross domain requests are not possible through AJAX (since XHR is bound to same origin policy)... Hence we use JSONP, which uses dynamic script injection (since script tag is not bound by same origin policy).
However, I was going through the jQuery AJAX documentation and saw one setting saying "crossDomain".
So, is Cross domain requests now supported through jQuery/AJAX? Is it the same as what we get through JSONP?
I made a project that use cross domain requests. You have few examples.
It is here, on Github.
Use this function in your client-side code (javascript):
function getHTML(url, callback){
url = url.trim();
$.ajax({
url: url,
type: 'GET',
success: function(res) {
var headline = res.responseText;
if(headline === ""){
callback("There was a problem with the page. Be sure that your url is correct.");
return;
}
callback(null, headline);
}
});
}
I want to READ JSON data using Jquery ana Ajax from this link
http://praytime.info/getprayertimes.php?lat=31.950001&lon=35.9333&gmt=180&m=3&y=2013&school=0&format=json&callback=?
and this is my code:
$(document).ready(function() {
var strUser ="http://praytime.info/getprayertimes.php?lat=31.950001&lon=35.9333&gmt=180&m=3&y=2013&school=0&format=json&callback=?";
$.ajax({
url: strUser ,
dataType: 'jsonp',
success: function(data){
jQuery.each(data, function(){
alert("yes");
});
}
});
});
I tried this code with other links , and it's correct, but from the specified link I don't get any out put, can you help me??
The url you are trying to access with JSONP doesnot support it. The server will need to return the response as JSON, but also wrap the response in the requested call back. So a way to solve this problem is using a server side proxy, which fetches the response from the specified url and passes it on to your client side js, like:
$.ajax({
type: "GET",
url: url_to_yourserverside_proxy,
dataType: "json",
success: function( data ) {
console.log(data);
}
});
where
url_to_yourserverside_proxy is a server side file that fetches response from the url specified
URL is outputting json but for cross domain need jsonp.
Not all API's provide jsonp. If cross domain API doesn't provide jsonp and isn't CORS enabled you will need to use a proxy to retrieve data due to same origin policy
So i have a json file named array.json on my web-server i intend to read this file in my web-application locally (for now) and then on a different domain once i go live, i have created this json file myself and here is the data it contains.
{"h1": "cmPanel", "h2" : "cmAuto", "h3": 0}
When i am trying to read the file I am not getting back a response, why would this be?
Here is my code for reading the file;
$.getJSON('http://www.foobar.com/array.json', function(data){
alert(data);
});
I have also tried adding &callback=? and still i receive nothing, could you please assist !
Quoting official docs:
Due to browser security restrictions, most "Ajax" requests are
subject to the same origin policy; the request can not successfully
retrieve data from a different domain, subdomain, or protocol.
Script and JSONP requests are not subject to the same origin
policy restrictions.
More info about Same Origin Policy
To work around it, look into JSONP.
In order to do cross-domain ajax calls you will either need to use a proxy or JSONP. Since you're setup for JSON already JSONP might be the easiest alternative. In short, JSONP entails wrapping your JSON data in a function call so it can be passed back to the calling script in a way that circumvents the Same Origin Policy.
In your case, you could wrap your json data with function named "myjsoncallback" so that it looks like this:
myjsoncallback({"h1": "cmPanel", "h2" : "cmAuto", "h3": 0})
And then change your ajax call to something like the following:
$.ajax({
url: 'http://www.foobar.com/array.json',
dataType: 'jsonp',
jsonpCallback: 'myjsoncallback', // Specify our callback function name
success: function(data) { console.log(data); }
});
Have you got access to the server from your web application? (same origin policy)
To use jsonp you could not simply add callback to the URL of the json file. The server should deliver a function that return the data. This file you could include with the default html script tag and execute the returned function afterwards.
To see the returned json you need to itterate the result
$.getJSON('array.json', function(data){
var items = [];
$.each(data, function(key, val) {
items.push('Key = ' + key + '<br/>Value = ' + val + '<br/><br/>');
});
alert(items.join(''));
});
array.json shoud be served with proper Content-Type:
text/javascript; charset=utf-8 if callback is used
application/json; charset=utf-8 if it is plain json
see here Best content type to serve JSONP?
to avoid problems from 'same origin policy'