How get xml result(cross domain request)? - javascript

I need to make a request to a dedicate website , using jsonp for cross domain reason to get back a XML result and work on it.
So basicly I am doing this to start :
(function($) {
var url = 'http://www.website.....';
$.ajax({
type: 'GET',
url: url,
// async: false,
// contentType: "application/json",
dataType: 'jsonp',
});
})(jQuery);
I can finally get an answer from website, that I can see in the firebug plugin, but in XML tab
such as :
<Results xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://www.website.com">
<ResultSet id="searchResults" numResults="3" >
From my understanding jsonp is a json object and in my case it s returning a XML content.
My problem is how to manage the XML return from the website? I can parse it and play with in the javascript code.

You need to define your jsonpcallback in order to tinker with the return value of the request.
See:
jsonpCallback function not working
http://api.jquery.com/jquery.ajax/

Related

Javascript Cross domain URL request

Is it possible to send the cross domain URL request and read the response using JSONP?
Could you please give me some samples?
I am trying to send URL request to a different domain using xhr but couldn't read the response
Please help
Thanks in Advance
You can check with blow example:
$(document).ready(function(){
$.ajax({ // ajax call starts
//crossOrigin: true,
type: "GET",
url: 'http://www.google.com', // JQuery loads areas
dataType: 'json', // Choosing a JSON datatype
async: false,
success: function(data) // Variable data contains the data we get from serverside
{
console.log(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.

Read RSS XML in javascript (cross domain)

I want to read rss(xml) file but without using google rss feed.
i have try jsonp but it download the file and it throw a error "Uncaught SyntaxError: Unexpected token < "
$.ajax({
type: "GET",
url:'https://news.google.com/?output=rss',
//url: document.location.protocol + '//ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=1000&callback=?&q=' + encodeURIComponent(url),
dataType: "xml",
contentType: "text/xml; charset=utf-8",
headers: { "Access-Control-Allow-Origin":"*",},
success: function(xml) {
alert("success");
}
});
plz guys help me..
$.getJSON("//ajax.googleapis.com/ajax/services/feed/load?v=1.0&callback=?", {
num: 10,
q: url
}).done(function (data) {
console.log(data);
});
Notes:
You're overdoing it. Don't try to specify information on the client side that the server actually has to supply (content type, allow origin headers, data type).
You don't want XML, you want JSON.
The name for cross-origin JSON requests is JSONP.
jQuery implements that for you if you use the getJSON() API method. You don't have to do anything besides adding "callback=?" to the URL.
Use jQuery Deferred callbacks (then, done, fail and always). They allow your code to become a lot more flexible.
Have a look at the documentation, too. https://developers.google.com/feed/v1/jsondevguide
You basically can't implement a web client RSS reader because you can't be sure that content providers will set the correct CORS header for their feed(s) ; My advice would be to not waste your time reading through endless CORS/JSONP lectures (and trying misleading code) but implement a server solution (like, say Pétrolette) and move on.

Jquery unable to get the response from WCF REST service

I have developed WCF rest service and deployed it on a link that can be accessed via the browser because its action is "GET".
I want to get that data using jQuery. I tried my best to get WCf get response using jQuery
but in vain. I also tried $.Ajax with 'jsonp' with no luck. Can any one help me?
The url is: http://www.lonestarus.com/AndroidApp/AndroidLocation.svc/RestService/getLatestLocation
You can check that url response by pasting url in browser.
You need to set Access-Control-Allow-Origin to value [*] in your response header.
this blog gives the more details how it can be done in WCF REST service
if you were to do this in Web API you could have just added
Response.Headers.Add("Access-Control-Allow-Origin", "*")
calling the service using a fiddle
$(function() {
$.ajax({
url: "http://www.lonestarus.com/AndroidApp/AndroidLocation.svc/RestService/getLatestLocation",
datatype: 'json',
type : 'get',
success: function(data) {
debugger;
var obj = data;
}
});
})​;​
I got the error
XMLHttpRequest cannot load
http://www.lonestarus.com/AndroidApp/AndroidLocation.svc/RestService/getLatestLocation.
Origin http://fiddle.jshell.net is not allowed by
Access-Control-Allow-Origin.
I can't make a cross domain example to show you but
$('#a').load('http://www.lonestarus.com/AndroidApp/AndroidLocation.svc/RestService/getLatestLocation​​​​​​​​​​​​​​​​​?callback=run');​
would work had those things been set.
Your service needs to either enable JSONP callbacks or set the Access-Control-Allow-Origin header for cross domain requests to work, or you need to run the script from the same domain. Given that your url says AndroidApp I'm thinking you want cross domain.
Sample code below:
$.ajax
(
{
type: 'GET',
url: http://www.lonestarus.com/AndroidApp/AndroidLocation.svc/RestService/getLatestLocation,
cache: false,
async: true,
dataType: 'json',
success: function (response, type, xhr)
{
window.alert(response);
},
error: function (xhr)
{
window.alert('error: ' + xhr.statusText);
}
}
);

Is this crossdomain issue in jquery?

I'm not sure if this is crossdomain issue or not. I'm trying to use $.ajax to load file. But some file I get readyState=4 and some file I get readyState=1
This is the path where I run my jasmine test
file:///home/myname/development/path1/path2/src/test/java/javascript/jasmine/SpecRunner.html
And in the code I used jQuery.pyte to require relevant file. But it's stuck at readyState:1 when the code comes to $.ajax
if I do something like this, it returns readyState=4 correctly and print out the content inside SpecRunner.html
$.ajax({url: 'file:///home/myname/development/path1/path2/src/test/java/javascript/jasmine/SpecRunner.html', async: false}).responseText
but if I do something like this, I only get readyState=1 and nothing is returned.
$.ajax({url: 'file:///home/myname/development/path1/path2/src/main/webapp/static/js/core/application/FileThatIWant.js', async: false}).responseText
you should avoid file:// URLs in general, because browsers do not allow them in many different places. Try XAMPP it's a simple to use local webserver, you will definitively need one.
Yes, this is a cross-domain issue. You can solve this problem by forcing jQuery to use crossdomain AJAX (JSONP).
$.ajax({
url: "yoururl",
cache: false,
crossDomain: true,
data: {}, //put your GET parameters here or directly into the url
dataType: "jsonp",
processData: true,
success: function(data, textStatus, jqXHR){
//This will be executed if it worked
},
error: function(data, textStatus, jqXHR){
//This will be executed if it failed
},
timeout: 4000, //You can put any value here
traditional: true,
type: "GET"
});
jQuery will automatically add a callback parameter containing a random string (&callback=XXXXXX).
The target URL needs to output the following:
XXXXX(your_output_encoded_in_JSON);
where XXXXX is the random string. The PHP code to do so is:
echo $_GET["callback"]."(".json_encode($myoutput).");";
Make sure that the PHP (or whatever language you're using) page ONLY outputs that!
If, instead, the page you are querying is not built dynamically, such as an HTML page, you need to add the following options to the $.ajax options object:
jsonp: false,
jsonpCallback: "mycallback",
mimeType: "text/javascript",
Your .html file will contain something like this:
mycallback("<html><head></head><body>TEST PAGE. This is a double quote: \" and I didn't forget to escape it!</body></html>");
This technique is very handy to bypass the strict crossdomain restrictions hardcoded in browsers, but it only supports GET parameters. XMLHTTPRequest v2 supports cross-domain requests, but we won't be able to assume that all users have a XHRv2-compatible browser before at least 2016.
http://caniuse.com/xhr2

Categories