theyworkforyou API coming back empty in Javascript Ajax - javascript

I am really getting confused. If I post into a browser the following link, it works, no problem, but when I ask jQuery do to it, it comes back blank, but no error.
Link:
http://www.theyworkforyou.com/api/getConstituency?key=FU8MWTEQnvVsHC6GM7B82zie&postcode=BS345NT
Code:
$.ajax({
url: 'http://www.theyworkforyou.com/api/getConstituency?key=FU8MWTEQnvVsHC6GM7B82zie&postcode='+postcode+'&output=js',
type: 'POST',
success: function(response) {
console.log(response);
}
});
I can change the Key, so don't worry about the fact I posted it.
Any ideas why it's not working?

Your javascript is running in the context of a web page downloaded from an origin server into a browser. It tries to request a page from a different server, but this is a violation of the same origin policy. Javascript cannot make requests to servers other than the origin server.
The JSONP technique can be used to get around this, but only if the non-origin server supports it. In this technique the javascript code dynamically creates a script tag whose src element 1) points to the non-origin server, and 2) passes (as a query parameter) the name of a function which exists in the local javascript. The non-origin server returns the source code of a script which merely invokes the function on data provided by the non-origin server. In this way the javascript can request data from a non-origin server.
If the non-origin server does not support JSONP, then you won't be able to do what you want.

Related

Scrape info from external XML url with jQuery

I need to scrape/parse some info from an external XML file (xml hosted on other domain) and place that info on my site.
I tried this, and didn't succeed:
jQuery(document).ready(function()
{
jQuery.ajax({
type: 'GET',
url: 'http://42netmedia.com/smart/signal_onAir10.xml',
crossDomain: true,
dataType: 'jsonp',
success: parseXml
});
});
function parseXml(xml)
{
jQuery(xml).find('nowOnAirTitle').each(function()
{
jQuery(".my-site-element").append(jQuery(this).find('nowOnAirTitle').text());
});
}
I hope I managed to explain properly.
PS. I am using jQuery because my site is hosted on WordPress
The short answer is that you cannot do what you're trying to do from Javascript running in a browser.
The same origin policy will block AJAX requests for URLs on different domains. There are a couple of exceptions to this policy:
If the target server supports CORS, it can indicate that cross-origin requests are OK. The URL you are trying to reach is on a server that does not support CORS.
If the target server supports JSONP, your script can retrieve data from the target server by using a <script> tag in your page with a src attribute pointing to the target URL and including a callback parameter to tell the server to wrap the data in a javascript function that returns the data. The URL you are trying to reach is on a server that does not support JSONP.
Yes, jQuery does allow you to make a JSONP request across to the other domain, but the response is not Javascript but XML. Your browser is trying to execute the XML as if it was Javascript and fails with a syntax error.
Any solution to this will require server-side support on the server which hosts your code. You could set up a proxy URL on your web server, but you'd need to do that very carefully because you don't want your server to be used as an open proxy. You could also use a cron job to grab the URL using curl and save it to a static file on your server, but that's probably a bit rude.

Cross domain ajax GET parameters not allowed

I'm trying to get data from an API with javascript but i'm getting an error on the request.
$.ajax({
dataType: "jsonp",
url: "https://www.bitstamp.net/api/ticker/",
type: "GET",
succes: myfunction
});
result:
{"error": "GET parameters not allowed for this request."}
I use Jsonp because its another domain.
Why can't I get the data with Jquery?
If I just browse to the link I can see the Json.
I just tried getting data from the url you provided using AJAX. The server did not return any data using the $.ajax and this clearly shows that the server does not support cross domain requests. That is why I asked you if you had access to code because you have to manually specify if you want API to support cross domain requests.
One way around to this is using some server side language to access this API. I once had similar problem and the used PHP CURL to access the API. The php code then served data to JQuery to be used on frontend. So you can write relay code to solve this problem.
Because, as the error message says, bitstamp do not allow it.
If they get a JSONP request for the data, they respond with the error instead of the normal response.

External HTML retrieval

I am trying to get the contents of http://en.wikipedia.org through an ajax call. For this, I am using jQuery. Here is the code:
jQuery.ajax({
url:"http://en.wikipedia.org",
crossDomain: true,
dataType: "jsonp",
jsonpCallback: "myCallback"
});
function myCallBack(data){
console.log("ok");
}
The problem is that I get in Firebug this error:
SyntaxError: syntax error
<!DOCTYPE html>
So I would say that the html content is fetched, although the callback function is not run. At some point it encounters the specified tag, throws this error and stops running the script.
Do you have any idea where the problem might lie?
Is there any other way to get the contents of a html page? I do not want to use iframes, because that means I will not be able to use or modify its contents.
Its because you're Ajax function expects a json response from the provided url and it gives an html response, thats the reason you are getting a syntax error, the same error you will get from the Chrome debugger as well.
Updated:
What you're trying to do is called a Cross-Domain Request.
"For security reasons scripts aren't able to access content from other domains. Mozilla has a long article about HTTP access control, but the bottom line is that without the website themselves adding support for cross-domain requests, you're screwed."
Reference
Solution:
You can resolve this issue by having a backend script which will the external pages for you. Like a proxy server, which resides the same domain, so you wont have to face the Cross domain issues.
And you can load them, by
$.get(url, success: function(data) { // the url that will fetch the external html page for you, located on the same domain
console.log("ok");
});
Your issue your having here is that you are calling across domains. Allthough you seem to have realised this and are using jsonp for your request, the document you are trying to pull ie wikepedia is not a jsonp document. So as soon as the ajax finds the html tags it will throw an arror, as you have defined that you are expecting a jsonp response.
You cannot just pull other websites data across domain with javascript due to the cross domain issues, if you want to accomplish what you are doing here you will need to use a back end language to get the data.
Usefull link is http://json-p.org/
Hope that helps

Jsonp cross-domain ajax

I'm working on an application which use ajax call to get html from the server.
When I run it on the server, everything works fine.
But when I'm running on a localhost, I've a 'Access-Control-Allow-Origin' error.
I looked arround and it seems like using jsonp could be the solution.
So, my ajax call looks like that:
$.ajax({
url: url,
dataType: 'jsonp',
crossDomain: true,
type: 'GET',
success: function(data){
// should put the data in a div
},
error: function(){
//do some stuff with errors
}
});
I get html from the server, but I always have this error:
Uncaught SyntaxError: Unexpected token <
Is there a way to wrap the jsonp response in html?
Thanks!
You can't use JSONP to grab an HTML document. You need to wrap your HTML in a JavaScript variable. JSONP has some very specific requirements to make it work properly, including a callback function/attribute. If you're not in control of the server hosting the target page, you won't be able to make it work. This is a security precaution to prevent a random page from being able to steal your personal information from sites you're logged into via an AJAX call.
UPDATE
I read your question more thoroughly. It sounds like your problem is that you're in a development environment that doesn't have the resource in question. JSONP isn't the answer because it's a lot of trouble to get running just to make your page work in development. You should create a local copy of the target HTML and grab it using a relative or server-absolute URL such as "/the/page/i/need.html" instead of "http://myserver.com/the/page/i/need.html"
If you want to get the data by jsonp, then the server side need to support jsonp.
There is no way just change the dataType to get the data.
If the server side doesn't support jsonp, then you need to make a proxy in your localhost.

Difference jsonp and simple get request (cross domain)

I have to send (and receive) certain data to a server using JQuery and JSON.
Works so far, but not cross domain, and it has to be cross domain.
I looked how to solve this and found JSONP. As far as I see, using JSONP I have to send the callback and the data using GET (JQuery allows to use "POST" as method, but when I inspect web traffic I see it is sending actually GET and everyting as parameter).
JSONP also requires changes in the server, because they are expecting a POST request with JSON data, and they have to implement something to process the JSONP GET request.
So I'm wondering what's the difference between this and sending the data as key value parameters in GET request?
Is the difference the possibility to use a callback? Or what exactly?
Sorry a bit lost... thanks in advance
JSONP is not a form submission. It is a way of telling the server via a GET request how to generate the content for a script tag. The data returned is a payload of JavaScript (not just JSON!) with a function call to a callback which you (by convention) reference in the GET request.
JSONP works because it is a hack that doesn't use AJAX. It isn't AJAX and you should not confuse it for such because it does not use a XMLHttpRequest at any point to send the data. That is how it gets around the Same Origin Policy.
Depending on the browsers you have to support, you can implement Cross-Origin Resource Sharing headers on the server side which will let you use normal AJAX calls across trusted domains. Most browsers (IE8, Firefox 3.5+, etc.) will support CORS.
Another solution you can use if you don't want to use CORS or JSONP is to write a PHP script or Java servlet that will act as a proxy. That's as simple as opening a new connection from the script, copying all of the incoming parameters from your AJAX code onto the request and then dumping the response back at the end of your script.
I found an answer that worked for me with the cross-domain issue and JSON (not JSONP).
I simply used:
header('Access-Control-Allow-Origin: *');
inside my json file (file.php) and called it like this:
var serviceURL = 'http://your-domain.com/your/json/location.php'
$.getJSON(serviceURL,function (data) {
var entries = data;
//do your stuff here using your entries in json
});
BTW: this is a receiving process, not sending.

Categories