Consuming web weather service in javascript - 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.

Related

create javascript file for use on different servers

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.

Uncaught SyntaxError: Unexpected token < in <!DOCTYPE html>

i am sending a ajax request to external domain. Here is my code,
There might be an issue on JSONP response while converting the html data to jsonp. I have tried so many solution because i am requesting to cross domain so i have to use JSONP else i have to face cross domain error. Error when Use simple JSON ERROR: " XMLHttpRequest cannot load http://www.blink.com.kw/search-result.aspx?text=apple&searchfor=all. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'localhost:49324' is therefore not allowed access."
Response error:
Uncaught SyntaxError: Unexpected token <
<script type="text/javascript">
$(document).ready(function(){
$("#bt").click(function(){
$.ajax({
type: 'GET',
url: 'http://www.blink.com.kw/search-result.aspx?text=apple&searchfor=all',
dataType: 'jsonp',
success: function (data) {
console.log(data);
//$("#data").html(data);
}
});
});
});
</script>
This is probably happening because you are specifying it as JSONP, which executes the data as a script in order to execute a callback function. If it sends back a normal HTML document with the doctype being the first line it sees, this would occur.
Try this code, basically we should not use url like this.
Also, this url is not return any json or jsonp format, please check your link as well
<script type="text/javascript">
$(document).ready(function(){
$("#bt").click(function(){
$.ajax({
type: 'GET',
url: 'http://www.blink.com.kw/search-result.aspx',
dataType: 'jsonp',
data:{
text: apple,
searchfor: all
}
success: function (data) {
console.log(data);
}
});
});
});
</script>
Hope this helps :)

ajax GET - XMLHttpRequest cannot load

I'm trying to get data from a external api, but
I keep getting the error message:
XMLHttpRequest cannot load... No 'Access-Control-Allow-Origin' header is present on the requested resource.
here is my code:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<script type="text/javascript">
(function () {
$.support.cors = true;
$.ajax({
type: "GET", url: "http://zhettoapi.azurewebsites.net/api/Values?product=Coca Cola", success: function (data) {
window.alert("" + data);
//example of setting innerHTML of object
document.getElementById("myElement").innerHTML = "The number is:" + data;
}, error: function (xhr, status, error) {
// Display a generic error for now.
alert("Error: " + xhr + " " + status + " " + error);
}
});
})();
</script>
</head>
<body>
<div id="myElement"></div>
</body>
</html>
Since i can see that use have used azurewebsites mentioned in Get url ( "http://zhettoapi.**azurewebsites**.net/api/Values.... ), and i have some experience on that, i thought of solving your problem, even if this question was not tagged with Azure.
Assumption : You have used WebAPI.And deployed on Azure as website. ( i am sure, it is).
Since you are trying to access Azure Web API url from other domain in form of ajax.get request, it gets blocked because of cross domain ( CORS) security. So first thing here, is to make it(hosted WebAPI project) CORS enabled.
Steps to make it CORS enabled:
Install this - Install-Package Microsoft.AspNet.WebApi.Cors using NuGet
Open the file App_Start/WebApiConfig.cs. Add the following code to the WebApiConfig.Register method.
Next, add the [EnableCors] attribute to the Controller class:
With following params
[EnableCors(origins: "http://zhettoapi.azurewebsites.net", headers: "", methods: "")]
Redeploy your WebAPI project.
SOURCE - http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api
More links - http://www.codeproject.com/Articles/742532/Using-Web-API-Individual-User-Account-plus-CORS-En
Thanks!
Also this tutorial was helpful(describing):
http://www.codeguru.com/csharp/.net/net_asp/using-cross-origin-resource-sharing-cors-in-asp.net-web-api.html

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.

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