JQuery ajax call to cross-domain webservice - javascript

I would like consume cross-domain web-service from client with jquery
function TestService() {
$.ajax({
url: "http://service.asmx/GetGeoCompletionList",
data: { "prefixText":"eka", "count":"10", "contextKey":"Trace_0$Rus" },
dataType: "jsonp",
type: "GET",
contentType: "application/json; charset=utf-8",
success: function (data) {
alert(data);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest.statusText);
}
});
}
At the error hander I have:
textStatus=parseerror
XMLHttpRequest has status 200 and readyState 4
errorThrown is jQuery16103495572647140...78197139 was not called
I've spent on it for a lot of hours and couldn't make it work. Can u help me?
UPDATED
Thanks, I change to GET, and fix my data string.
Service returns valid JSON object. I can see it at firebug on other site, which consume this service. But that site is getting common json(since it has one domain).
So, if the web-service returns valid JSON(not jsonp), I can't use the same method with jsonp? What can I do for consiming json web-service from other domain?

That string you are passing and claiming is JSON isn't JSON.
Only " characters may be used to quote strings.
Also, you can't make a cross domain JSON-P POST request.

You cannot do cross-domain POST requests using JSONP. JSONP works by adding script tags to the page. script tags always fetch their source using GET HTTP requests. You won't get any data posted.

Summary of problems:
Make sure you're using valid JSON
as #Quentin mentioned.
Make sure you're using GET requests, as
#lonesomeday mentioned
Make sure the response from the server is
JSONP, as seen here

Related

How can i do cross domain query using ajax & jsonp?

I send ajax to url , but i get error.
Here is my code:
$.ajax({
url: "http://webrates.truefx.com/rates/connect.html?q=ozrates&c=EUR/USD&f=csv&s=n",
dataType : 'jsonp',
success: function (data) {
alert(data);
}
})
Maybe i doing something wrong?
In order to access data using JSONP, the server you are requesting the data from must format its response as JSONP.
You are getting an error because the response is not JSONP (it is CSV, which you asked for explicitly when you put t=csv in the query string).
Either:
Use a different method to get the data
Change the server so it responds with JSONP formatted data

Get JSON(P) from other site [duplicate]

This question already has answers here:
Unexpected token colon JSON after jQuery.ajax#get
(2 answers)
Closed 7 years ago.
I am trying to get data with Ajax.
Data is json. I use jquery and angular.
But result is undefined or error.
Here is my jquery code:
$(document).ready(function() {
var url = "http://market.dota2.net/history/json/";
$.ajax({
type: 'GET',
url: url,
async: false,
contentType: "application/json",
dataType: 'jsonp',
success: function(data) {
console.log(data);
}
});
});
In Angular i am usin jsonp method. Whats wrong ?
By the way, in pure Java i can get data from this url...
Whats wrong?
You're trying to call an endpoint that provides JSON as though it provided JSONP. That won't work; they are different (though related) formats.
Example JSON:
{"foo":"bar"}
Example JSONP:
callback({"foo":"bar"})
Note the difference: JSONP is actually a JavaScript function call, wrapped around the JSON.
If the API supports JSONP, call an endpoint that supports it.
If not, you can't query it directly unless the provider supports Cross-Origin Resource Sharing and shares with your origin, because of the Same Origin Policy that applies to ajax calls.
By the way, in pure Java i can get data from this url...
Because the Java code is not running in a context that is controlled by the SOP, and so can get the data from that endpoint (as JSON) and use it. This is also the same reason that just posting that URL into a browser address bar lets us see the data. But ajax calls are governed by tighter rules.
If you expect json, dont use jsonp but json.
$(document).ready(function() {
var url = "http://market.dota2.net/history/json/";
$.ajax({
type: 'GET',
url: url,
async: true, /* it fails with false */
contentType: "application/json",
dataType: 'json',/* <== here */
success: function(data) {
console.log(data);
}
});
});
Are you using jsonp consciously ? Do you know what it is ? If not, use json. Or get informed about JSonP: https://en.wikipedia.org/wiki/JSONP
I tried on Safari:works.
On Chrome & FFox: does not work + Erreur "Cross Domain Origin"
XMLHttpRequest cannot load http://market.dota2.net/history/json/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
That means you cannot get JSon with your client/machine from the API server. So you should indeed use JSonP, but... you miss the callback or something in the API documentation.

Getting 'data is null' on a Twitter API call but displays data in browser

I'm trying to display the follow count of a twitter account, but when I hook into the API using this code:
$.getJSON("https://api.twitter.com/1/users/show.json?screen_name=uswitchTech&include_entities=true", function(data) {
console.log(data);
if (!data.error) {
$("#followers").html(data.followers_count);
}
});
I get a 200 ok report but with Data is null message.
But if I download the json file to my local machine and change the getJSON call accordingly, it works straight away.
Has anyone got any ideas on what could be causing this?
Thanks
Also just to add, if I put the Twitter API url into my browser it displays all the data, which makes it even weirder.
Maybe the problem lies with jsonP, since you are calling a remote server and you must specify you should use jsonP. Have you tried adding callback=? as a parameter
$.getJSON("https://api.twitter.com/1/users/show.json?screen_name=uswitchTech&include_entities=true&callback=?", function(data) {
if (!data.error) {
$("#followers").html(data.followers_count);
}
});
Taken from jQuery docs
JSONP
If the URL includes the string "callback=?" (or similar, as
defined by the server-side API), the request is treated as JSONP
instead. See the discussion of the jsonp data type in $.ajax() for
more details.
$.ajax({
url: 'https://api.twitter.com/1/users/show.json?screen_name=uswitchTech&include_entities=true',
dataType: 'jsonp',
success: function(data){
console.log(data.followers_count);
}
});

GET ajax request

I'm sending GET request (which returns JSON).
The code looks like:
$.ajax({
url: "http://www.new.marketprice.ru/retrieveRegions.html",
dataType: "jsonp",
data: {
searchStr: request.term
},
error: function() {
console.log('epic fail');
},
success: function( data ) {
console.log(data);
}
});
It returns (into console);
Resource interpreted as Other but transferred with MIME type undefined.
epic fail
But in Network tab I see GET request with returned data:
[
{ "region":"Московская область","countryId":1,
"cityId":23,"regionId":12345,"city":"Москва","country":"Россия"},
{"region":"Ленинградская область","countryId":1,"cityId":453,
"regionId":54321,"city":"Санкт Петербург","country":"Россия"}
]
Why does error callback is called?
UPD
Okay, I set json and now no warning but error:
XMLHttpRequest cannot load http://www.new.marketprice.ru/retrieveRegions.html?searchStr=test. Origin http://new.marketprice.ru is not allowed by Access-Control-Allow-Origin
It's so strange because running script is located at same domain :(
It is only a json response not JSONP. Generally for JSONP the request will have callback method and response will be wrapped in that function name
Your headers don't specify the correct mime-type (application/json-p) and jQuery(?) is confused because it's not sure if it should process it as json or not.
See if you can get your server to respond with the correct type. The appropriate header is called Content-Type.
EDIT: whoops, and the OP is right, its not even JSON-P. Try changing what jquery is expecing to just 'json' first.
i was also in problem like this just try by using one more argument callback=? or json=jsonp

How do I pass or parse that access_token from the Dom to a Variable I can then Store and call for access_token?

With help from others I've gotten to the point where I can see the json return from foursquare but any attempts to call it yield an error.
Essentially, if I'm in Firebug and look at the net objects I see the status 200
If I click on the JSON tab I can see my access_token, but how do I extract it from there so I can use for API calls?
Here's the latest code tried.
var jsonUrl = url +"&callback=?";
var access_token;
$("#getJSON").click(function() {
$.getJSON(jsonUrl, { dataType: "JSONP" }, function(json){
...
access_token = json.access_token;
...
});
});
also tried
$.ajax({
dataType: 'jsonp',
jsonp: 'callback',
url: url,
success: function (json) {
console.log(json.access_token);
},
});
But when I try and alert(access_token); or run a foursquare api call I get the following errors
Resource interpreted as Script but transferred with MIME type application/json.
Uncaught SyntaxError: Unexpected token :
checkinsGET https://api.foursquare.com/v2/users/self/checkins?oauth_token=undefined&format=json 401 (Unauthorized)
I feel like its ready and waiting for me to call it, but how on earth do I print it from the Dom into a var that I can use? Been fighting for hours and been trying all my research techniques for some reason this one's elluding me. Thanks for everyone's help so far, I'm really hoping to get passed this!
Try removing the "&callback=?" from the url. I think jQuery adds that for you if you set the dataType to jsonp.
EDIT:
from the jquery ajax documentation describing the dataType parameter:
"jsonp": Loads in a JSON block using
JSONP. Will add an extra "?callback=?"
to the end of your URL to specify the
callback.

Categories