create javascript file for use on different servers - javascript

I want to create a JS file that others can include on their websites so they can reference the functions which access my db using an api similar to the facebook like button which shows the total liked and who of your friends like the page. What I've been doing as part of my testing is the following:
JS file
function getItemRating(id){
var result = "";
$.ajax({
type: "POST",
url: "http://siteurl.com/api/rating.php",
data: {i : id},
dataType: "json",
async: false,
success: function(data) { // callback for successful completion
result = data;
},
error: function() { // callback if there's an error
result = 'error';
}
});
return result;
}
Reference file includes:
header("Access-Control-Allow-Origin: *");
and on the other server I've tried a few ways including:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
<script type="text/javascript" src="www.siteurl.com/api/rating-file.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var result = getItemRating(1);
console.log(result);
});
</script>
</head>
<body></body>
</html>
But currently I'm getting the error in console:
VM133:1 Access to XMLHttpRequest at 'http://siteurl.com/api/rating.php' from origin 'http://otherurl.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
siteurl.com = my server where the js file (with function) is located
otherurl.com = different server that the html including the js is located

The error message tells you that the problem is with the response to the preflight request, but you shouldn't be triggering one in the first place.
Remove:
contentType: "application/json; charset=utf-8",
because:
It is a lie. You aren't POSTing JSON in your GET request.
Setting the content-type to that value triggers a preflight request.

Related

Unable to parse the json from url

<html>
<body>
<script src='http://code.jquery.com/jquery-1.10.2.min.js'></script>
<script>
$(document).ready(function () {
$.ajax({
type: 'GET',
async: false,
contentType: "application/json",
url: "http://www.XXX.XXX.in/api/categories",//url:"dir/categories",
dataType: "jsonp", //dataType: "jsonp",
success: function (data) {
$.each(data, function(i,data) {
var det="<div>id :"+data.categoryId+" Name "+ data.categoryName+"</div></br>";
$(det).appendTo("#display");
//alert(det);
});
alert(data);
},
error: function (data) {
alert("this is error "+data);
}
});
});
</script>
<div id="display"></div>
</body>
</html>
In the above code I am trying to access the categories json and print the details.
I am doing it in two ways:
I have kept the categories file in dir/ folder and accessing it which shows me result properly.
When I try to access it online it gives me an error:
When I give dataType:"json" instead of jsonp I gives following error:
OPTIONS http:// XXX.XXX.in/api/categories 404 (Not Found)
XMLHttpRequest cannot load http:// XXX.XXX.in/api/categories. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http:// localhost:8080' is therefore not allowed access.
I dont know whether the server has cross platform ref. added.
You can't access data of another domain from your domain using JAVASCRIPT. It is a security rule known as the "Same origin Policy"
So, to get data of another domain, you could write server side script (maybe in PHP or some other language you're familiar with.), then you can make ajax request from your script to the server.
The same origin policy is enforced by the browser to protect websites from other websites making xhr requests and displaying their content as if it was their own.
So site A.com cannot connect to B.com with XHR or:
http://A.com cannot connect to http://sub.A.com
localhost:80 cannot connect to localhhost:8080
Edit
As you requested, here is the solution using PHP script.
get_json_from_url.php
<?php
header("Content-type: text/json");
$response = fopen('http://www.eazydial.logicengine.in/api/categories', "rb");
echo stream_get_contents($response);
?>
HTML page
<html>
<body>
<script src='http://code.jquery.com/jquery-1.10.2.min.js'></script>
<script>
$(document).ready(function () {
$.ajax({
type: 'GET',
url: "get_json_from_url.php",
dataType: "json",
success: function (data) {
$.each(data, function(i,data) {
var det="<div>id :"+data.categoryId+" Name "+ data.categoryName+"</div></br>";
$(det).appendTo("#display");
});
console.log(data); //alert can't print [object] so always use console.log() to inspect object and it values. (see output in browser console)
},
error: function (data) {
console.log("Err:");
console.log(data);
}
});
});
</script>
<div id="display"></div>
</body>
</html>
The solution provided here in PHP script will work only for GET request method. If you want to use POST request for any API then look for cURL library to get data from api.

Ajax request to GAE not working?

I have a GAE app which accepts JSON requests and replies with JSON in the response. I know it works as I have an Android app that works with it. I'm trying to set up a JavaScript browser based interface as well. To do this I'm trying to send a request via JQuery from a page hosted on a different GAE domain. However, as far as I can see the ajax is not sent at all.
<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc() {
alert("before ajax.....");
$.ajax({
type: "POST",
url: "CORRECT URL HERE",
data: {
type:"GAMES_LIST"
},
jsonpCallback: function(){
alert("success");
},
async: false,
crossDomain : true,
dataType: 'jsonp'
});
alert("after ajax...");
}
</script>
</head>
<body onLoad="loadXMLDoc()">
<div id="myDiv"></div>
</body>
</html>
Only the first 'before ajax' alert is fired.
Has anyone got an idea what I'm doing wrong?
By making an AJAX request to a different domain, you are violating the Same-origin policy.
If you have access to the JSON endpoint, you can allow specific domains to access your endpoint in the Access-Control-Allow-Origin HTTP header.
If you don't have access to the endpoint e.g. it's a third-party provider, you can make a JSONP request if the provider supports it.

How can I get jQuery .get to return JSON data?

I am trying to fetch information using AJAX from a URL. This URL will return a JSON response but I am having a great deal of trouble getting this to work. I am fairly new to using both AJAX and JSON so I am not quite sure as to what I am doing wrong. I am not receiving any output. Here's what I have so far:
HTML:
<!doctype html>
<html>
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content - Type">
<meta content ="utf-8" http-equiv="encoding">
<title>My Javascript Practice</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<noscript>JavaScript Must Be Enabled</noscript>
</head>
<body>
<div id="pub">Parent Div</div>
<script type="text/javascript" src="getList.js"></script>
</body>
</html>
JavaScript:
var teamId = 883455;
var myUrl = "https://apps-internal.attributor.com/guardianapi/service/csadminservice/csteams/" + teamId + "?view=PUBLISHERS_FOR_TEAM";
$.get(myUrl, function(data){
$("#pub").html(data);
alert("load was performed");
});
May I suggest to use something like this:
$.ajax({
type: 'GET',
url: myURL,
data: yourDAta,
dataType: 'jsonp',
success: function(jsonData) {
alert(jsonData);
},
error: function() {
alert('Error loading ');
}
});
Note the usage of jsonp over json
just add json as the third parameter, the data passed to the callback will be an object representation of the received json string
this should work,
var teamId = 883455;
var myUrl = "https://apps-internal.attributor.com/guardianapi/service/csadminservice/csteams/" + teamId + "?view=PUBLISHERS_FOR_TEAM";
$.get(myUrl, function(data){
//data here will be object, should not used directly
$("#pub").html(data);
alert("load was performed");
}, 'json');
if you are on different domain, you could setup a server side script to grab that data, say it is php file called api.php
<?php
$teamId = $_GET['teamId'];
//php.ini should allow url fopen
$response = file_get_contents("https://apps-internal.attributor.com/guardianapi/service/csadminservice/csteams/". $teamId ."?view=PUBLISHERS_FOR_TEAM");
echo $response;
?>
and call it in your js file
var teamId = 883455;
var myUrl = "path/to/api.php?teamId="+teamId;
$.get(myUrl, function(data){
//data here will be object, should not used directly
console.log(data);
}, 'json');
Try using the getJSON() method instead if you're only interesting in getting back a JSON response.
The .get, .load, .getJSON are all just extensions that use the .ajax method underneath, if you can't get the extension method working it sometimes helps to just use straight .ajax()
Essentially the getJSON() method is just this:
$.ajax({
dataType: "json",
url: url,
data: data,
success: success
});
Note the explicit use of the dataType: "json".
Since this looks like a cross-domain call you will need to use something like jsonp (JSON with padding) or CORS (Cross-origin resource sharing) if your endpoint supports it. If jsonp is supported by your endpoint you can set the dataType: "jsonp" but it needs to be explicitly supported by the server see this post for more details on jsonp.
Note: your server API must support jsonp or CORS for this to work.

Consuming web weather service in javascript

I would like to use javascript to consume the web weather service provided by cdyne.
This is my code:
<html>
<head>
<title>weather app</title>
</head>
<body>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script language="JavaScript">
function CallService() {
var DTO = "{ 'ZIP': '85281' }";
$.ajax({
type: "POST",
url: "wsf.cdyne.com/WeatherWS/Weather.asmx/GetCityWeatherByZIP",
data: JSON.stringify(DTO),
contentType: "application/json; charset=utf-8",
dataType: "json",
processData: true,
success: function (msg) {
alert(msg);
},
error: function (req, status, error) {
alert(req + "# " + status + "# " + error);
},
complete: function (req, status) {
alert(req + "% " + status);
}
});
}
CallService();
</script>
</body>
</html>
When I ran the code, it shows the [object Object]#error# and [object Object]%error in the alert, which means the error: function() and complete: function rather than success: function() are called. Is there anyone who used javascript to consume this weather service?
Any help will be greatly appreciated.
There are a few problems there:
Your URL should start with http://. Without it, the URL you have is resolved relative to the document the code is in.
You're sending JSON in the POST. The odds are very high that the service doesn't expect to receive a POST containing JSON.
You're expecting JSON back from the service, but it appears to reply with XML.
You're trying to do a cross-origin call, but that's prevented by the Same Origin Policy, and the service you're trying to use doesn't appear to support Cross Origin Resource Sharing. (When I tried it fixing the issues above, I got the error saying that the cross-domain request wasn't allowed from my origin [which was http:/jsbin.com]).
Looking at the service description for the page you're trying to use, it doesn't look like it supports JSON-P, either, which means you can't use it from a different domain. You'll have to use a server-side process to query it.
You cannot do ajax requests to a different domain, fiddle http://jsfiddle.net/wAt45/
XMLHttpRequest cannot load
http://wsf.cdyne.com/WeatherWS/Weather.asmx/GetCityWeatherByZIP. Origin
http://fiddle.jshell.net is not allowed by Access-Control-Allow-Origin.

API call over jQuery

I'm trying to build a .js file that sends data to an external API, waits for a response and interprets the results. The external API is XML-based and accepts an HTTPS Post with the XML as body (content-type; text/xml). I can call the API correctly via cURL.
This is what I have so far:
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body onload="CallService()">
<script type="text/javascript">
var webServiceURL = 'https://www.url.com';
var xmlString = '<xml><parameter1>value1</parameter1>
<parameter2>value2</parameter2></xml>';
function CallService() {
$.ajax({
url: webServiceURL,
type: "POST",
dataType: "xml",
data: xmlString,
processData: false,
contentType: "text/xml; charset=\"utf-8\"",
success: OnSuccess,
error: OnError
});
return false;
}
function OnSuccess(data, status) {
alert(data.d);
}
function OnError(request, status, error) {
alert('error');
}
$(document).ready(function() {
jQuery.support.cors = true;
});
</script>
</body>
</html>
When I open the HTML I get an alert saying "error" and nothing appears on the other end (the external API's). Is there a way to do this using just JavaScript/Ajax/jQuery or do I need a "supporting" code that receives the JS call?
When you want to make cross domain queries, you have basically 3 types of solution :
1) use JSONP, which won't interest you if you're using XML and not JSON
2) not really do cross-domain, by setting a kind of proxy (or any type of get) on the server serving the main html page
3) changing headers on the server to specify to the browser that you accept cross-domain queries. This is new but yet accepted by all major browsers. That's called CORS. It's easy to change the headers ("Access-control-...") in all server-side languages so that should now be the preferred way (if you have issues (security, rights, bandwidth, ad, etc.) with cross-domain access to the data you serve, you can restrain the allowed origins).

Categories

Resources