Problems reading json data with jquery. - javascript

I am having problems using jquery to grab json data from a web service that lies on a different subdomain from where my client side code is. When I access the exact same json data from a local text file, my code works fine.
The json data is coming from this address
var jsonFeed = https://crm.bmw.ca/webservices/RetailerLocator.ashx?language=en&callback=?
The MIME type of the data is text/html, however I have also tried application/json.
Here is one method of access
$.getJSON(jsonFeed, function (data) {
$.each(data, function (i, item) {
alert(item);
});
});
I've also tried this method, which came back with a parsererror. I've also tried this with a jsonp datatype
$.ajax(jsonFeed, {
crossDomain: true,
dataType: "json",
success: function (data, text) {
$.each(data, function (i, item) {
alert(item);
});
},
error: function (request, status, error) {
alert(status + ", " + error);
}
});
My code has to be entirely client side so a proxy isn't an option right now.
An example of someone with a very similar problem can be found here.
jQuery AJAX JSON dataType Conversion

You can only work within the confines of what is possible. Same-origin policy can't be subverted, although you can use things like cross-domain policy headers on each of your servers to essentially link them together. However, that's only supported in the newer crop of browsers, and you have to control all the servers in the network.
See: http://en.wikipedia.org/wiki/Same_origin_policy for more information on what you're up against.

While the returned JSON data should probably be of type text/json, the bigger problem is that the API call is not respecting your "callback" parameter. Since you're calling the API cross-domain you have to use JSONP which means your data should be returned inside of a function call. For example, if you navigate to https://crm.bmw.ca/webservices/RetailerLocator.ashx?language=en&callback=mycallback you should see something like this returned:
mycallback([{"RetailerID":1110,"Name":"BMW St. John's","Address":"120 Kenmount Road"...)
The fact that the callback function name specified in the "callback" argument isn't showing up as part of the returned data probably means that you're using an incorrect name for that parameter. Or, it could be that the system is not configured to allow cross-domain requests. You should contact the system admin and make sure the API allows cross-domain requests and also check the docs for that API and make sure you're using the correct callback parameter name.

So far as I can tell from playing with JSFiddle (http://jsfiddle.net/CEDB5/), the question/answer you mentioned is correct: unless crm.bmw.ca starts sending the correct MIME type you are stuck.

Related

How I get respone text in application and bind to the label in cross ajax call

I am calling the web service from other domain using Ajax call and I want to get returned response from server in my application by using following code I get response text in firebug but not in my JavaScript code. Control are not showing success and error response it goes out directly.
I want response in my success or error section but both not handling in this.
I am trying lot but not finding any solution please any one help me.
I am in a trouble. I hope somebody can help me for calling cross domain web service by using Ajax call. I am trying from 1 week but didn't find any solution till. I am getting response on browser but not getting it on my actual code.
My JavaScript code.
crossdomain.async_load_javascript(jquery_path, function () {
$(function () {
crossdomain.ajax({
type: "GET",
url: "http://192.168.15.188/Service/Service.svc/GetMachineInfo?serialNumber="+123,
success: function (txt) {
$('#responseget').html(txt);
alert("hii get");
}
});
crossdomain.ajax({
type: "POST",
url: "http://192.168.15.188/Server/Service.svc/GetEvents/",
// data: "origin=" + escape(origin),
success: function (txt) {
$('#responsepost').html(txt);
alert("hii post");
}
});
});
});
</script>
You can't simply ignore the Same Origin Policy.
There are only three solutions to fetch an answer from a web-service coming from another domain :
do it server-side (on your server)
let the browser think it comes from the same domain by using a proxy on your server
change the web service server, by making it JSONP or (much cleaner today) by adding CORS headers

"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.

Why does this $.getJSON request error?

I have the following script that call a http handler. It calls the http handler, and in fiddler, I can see the JSON returned correctly, however this script always ends up in the error block. How can I determine what is wrong?
<script type="text/javascript">
function GetConfig() {
$.getJSON("http://localhost:27249/Handlers/GetServiceMenuConfiguration.ashx", function(d) {
alert("success");
}).success(function(d) {
alert("success");
}).error(function(d) {
alert("error");
}).complete(function(d) {
alert("complete");
});
}
</script>
I see that you're including the server name (localhost) and port (27249). Ajax requests are controlled by the Same Origin Policy, which forbids cross-origin requests in the normal case. (If you're not doing a cross-origin call, you don't need to include the http://localhost:27249 portion of your URL, which is what makes me think you might be doing one.)
You can do cross-origin calls if the browser supports them and if your server code handles the CORS requests properly. Alternately, you might look at using JSON-P.
JQuery's built-in JSON parser is rather picky, even well formatted JSON can sometimes fail if the headers are not set perfectly. First try to do a $.ajax request with type:text property and log the response. This will differentiate between a connection problem and parse problem.
$.ajax({
dataType:'text',
url: '/Handlers/GetServiceMenuConfiguration.ashx',
success: function(data) {
console.log(data.responseText);
}
});
If the problem is the connection, and you do need to request JSON across domains, then you could also use a library loader like LAB, yep/nope or Frame.js.

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'

jQuery JSONP, only works with same site URLs

I need to make a request to an API which returns json formatted data. This API is on a sub-domain of the domain this script will run off (although at the moment it's on a totally different domain for dev, localhost)
For some reason I thought that jsonp was supposed to enable this behavior, what am I missing?
Using jQuery 1.4.2
$.ajax({
url:'http://another.example.com/returnsJSON.php',
data: data,
dataType:'jsonp',
type: "POST",
error: function(r,error) {
console.log(r);
console.log(error);
},
success:function(r){
console.log(r);
}
});
Change your type from "POST" to "GET".
That is, only if you intend to retrieve data.
You'll need a combination of Arnaud's answer (don't use POST) and R. Bemrose's answer (make sure server-side returns JSONP), with the added specification of a callback function.
In other words, here's your modified request code:
function dosomething(data) {
console.log(data);
}
$.ajax({
url: 'http://another.example.com/returnsJSON.php',
data: data,
dataType: 'jsonp'
});
Helpful to note that in the generated code you'll see that when the dataType is "jsonp", jQuery outputs a script tag pointing at the url; it's not a typical XHR. You could also use jQuery's getJSON() here.
Then your response will have to be formatted as such:
dosomething({
test: 'foo'
});
When the call is complete, your specified callback will fire.
Did you modify the server-side component to use JSONP?
You can't just tell the client to use JSONP and suddenly expect a JSON script on the server-side to return the correct result.
Specifically, JSONP requires the server to return a JavaScript string that calls a specific function (whose name is passed in with the other arguments) with the return results, which the client then evals.

Categories

Resources