How to get JSON with jQuery from another domain - javascript

I have a little page and I need to get JSON from another domain. If make this:
$.get( "http://dev.frevend.com/json/users.json", function( data ) {
console.log(data);
alert( "Load was performed." );
});
I get an error. I understand why it throws this error, but I don`t know how to aviod it. I have not acces to the server.
XMLHttpRequest cannot load http://dev.frevend.com/json/users.json. No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://localhost:3000' is therefore not allowed
access.
I also tried to use JSONP, but as I understand in that case server should wrap response with callback function, because I got a SyntaxError.
Is it possible to make this request with JSONP?
I tried
$.ajax({
url: "http://dev.frevend.com/json/users.json",
dataType: "jsonp",
jsonpCallback: "logResults"
});
function logResults(data) {
console.log(data);
}
But got
Uncaught SyntaxError: Unexpected token :
JSON is valid, I checked.

You need to allow access in your project configuration.
Below site has more information
http://enable-cors.org/server.html
Thanks,

Use JSONP in jquery for this purpose JSONP reference

Try to add a header into your PHP file which is responsible for executing every request.
header('Access-Control-Allow-Origin', '*');

Related

Obtaining json from api with jquery ajax not working

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"); ?>

Access-Control-Allow-Origin issue and angular $http service

Sorry for duplicating a question for this issue but I really tried to seek for a solution but I could not find it. So I use angular $http.get xhr request to retrieve data from the public api. I have next code
$http.get('http://www.carqueryapi.com/api/0.3/?callback=?&cmd=getMakes&year=2000&sold_in_us=1')
.success(function(d){ console.log(d); })
.error(function(d){ console.log( "nope" );
});
this returns in console:
XMLHttpRequest cannot load http://www.carqueryapi.com/api/0.3/?callback=?&cmd=getMakes&year=2009. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'blah-my-localhost-blah' is therefore not allowed access.
However if I user jquery getJson method it works just fine:
$.getJSON("http://www.carqueryapi.com/api/0.3/?callback=?", {cmd:"getMakes", year:"2009"},
function(data) {
console.log(data);
});
So obviously I can configure angular to send correct request since jQuery works fine?
Thank you for the response.
Use the $http.jsonp method to do a jsonp request along with JSON_CALLBACK as the callback name:
$http.jsonp('http://www.carqueryapi.com/api/0.3/?callback=JSON_CALLBACK&cmd=getMakes&year=2000&sold_in_us=1')
.success(function(d){ console.log(d); })
.error(function(d){ console.log( "nope" ); });

What is the difference between $.ajax with type: post and $.post

Consider this code:
$.ajax({
url: "http://x.com/api/AnnouncementCategory/Save",
type: "Post",
success: function (data) {
//Grab our data from Ground Control
alert(data);
},
error: function (event) {
//If any errors occurred - detail them here
alert("Transmission failed. (An error has occurred)");
}
});
With above code we can post data cross domain an everything is ok. But when i use this code:
$.post(' http://x.com/AnnouncementCategory/Save')
I get this error:
OPTIONS http://x.com/AnnouncementCategory/Save Request
header field X-Requested-With is not allowed by
Access-Control-Allow-Headers. jquery-1.9.1.js:8526 XMLHttpRequest
cannot load http://x.com/AnnouncementCategory/Save. Request
header field X-Requested-With is not allowed by
Access-Control-Allow-Headers.
I see the jquery source code:
function ( url, data, callback, type ) {
// shift arguments if data argument was omitted
if ( jQuery.isFunction( data ) ) {
type = type || callback;
callback = data;
data = undefined;
}
return jQuery.ajax({
url: url,
type: method,
dataType: type,
data: data,
success: callback
});
}
Jquery also use ajax in post.
**I know what is my error and just want to know:**What is the difference between $.ajax with type: post and jquery post?
jQuery's $.ajax method always sends the "x-requested-with" header for any cross domain requests, unlike the $.post. The error you are getting is because of the way external server is handling the external request. Please look here to get more info how the CORS (Cross Origin Resource Sharing – i.e. cross domain Ajax) is being handled. Also here you will find the similar problem and the solution.
The simple answer to the question you have asked is, a shorthand version of $.ajax, as described in the documentation:
http://api.jquery.com/jQuery.post/
The docs do state that:
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.
The question that you didn't ask, but perhaps is what you would really like to ask, is "why does cross-domain request work for me using $.ajax with a simple POST type, but not with $.post?". For that you would probably need to provide a bit more information.

"Security Err: Dom Exception" thrown when nesting ajax calls

Here's the issue. I'm extracting gmail contacts through an ajax call in javascript/jquery like this:
function getUserInfo() {
var xml_parse = "";
$.ajax({
url: SCOPE + '?max-results=9999&access_token=' + acToken
data: null,
success: function (resp) {
xml_parse = $.parseXML(resp);
callGmailHelperWebService(xml_parse);
},
dataType: "jsonp"
});
}
function callGmailHelperWebService(xml_parse) {
GmailHelperService.ConvertXMLToList(xml_parse, onSuccess, onFailed, null);
}
So, as you can see, if the initial ajax call is successful, i call a function which calls a web service that sits on the save server as my project (in fact, it's part of the project).
My web service (GmailHelperService) is wired up correctly, as I can definitely call it in other places (like right after this ajax call, for example). However, when I try to call it within the "success" portion of the ajax call, i get the following error:
Uncaught Error: SECURITY_ERR: DOM Exception 18
My theory is that this has something to do with cross-domain issues, but I can't understand why. And I certainly can't figure out how to fix this.
I'd appreciate any help.
JSONP is a data transfer method that involves sending your data in this format:
callback({"foo":"bar"});
As you can see, this is NOT xml. It is JSON wrapped in a callback method that will get executed when the request is done loading, thus allowing it to be cross-domain because it can be requested using a <script> tag.
You cannot simply change your dataType to JSONP and return xml, expecting it to work. XML != JSONP. You can however return XML in jsonp, for example, callback({"xml","... xml string here "}) but be mindful of quotes, all json keys and values must be wrapped in double quotes, inner-quotes need to be handled appropriately.
If your request is a same domain request (Same protocol, same subdomain, same domain, and same port,) then you can change your dataType to "XML" if you are returning XML. Otherwise, you need to either setup a proxy script to get the xml for you, or have your webservice return JSONP.
For example, the following urls are all considered cross-domain from each other.
http://example.com
http://www.example.com
https://example.com
https://www.example.com
http://example.com:8080
All of the above urls would be considered cross-domain, even if they are on the same server.

Cant read a json file on my local server from my web-server

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'

Categories

Resources