Consuming broadbandmap.gov json service errors - json

I'm trying to consume the json services from broadbandmap.gov so that I can display broadband providers and their speeds in an area. Here is a sample url:
http://www.broadbandmap.gov/internet-service-providers/70508/lat=30.1471824/long=-92.033638/%3Ejson
I'm using jquery to consume the service, however it's giving me an invalid label error in firebug:
var url = "http://www.broadbandmap.gov/internet-service-providers/70508/lat=30.1471824/long=-92.033638/%3Ejson";
//var url = "http://www.broadbandmap.gov/broadbandmap/broadband/fall2010/wireline?latitude=" + lat + "&longitude=" + long + "&format=json";
$.ajax({
url: url,
dataType: 'json',
type: 'POST',
contentType: "application/json; charset=utf-8",
success: function (result) {
console.debug("in success");
console.debug(result);
//success, execute callback function.
},
error: function (result) {
console.debug("in error");
console.debug(result);
}
});
The strange thing is that under the Invalid Label error in Firebug it actually has the correct response:
{"status":"OK","responseTime":7,"messa...//www.cscic.state.ny.us/broadband/"}}}
I have tried setting the dataType to json, jsonp, and other types as well to no avail. I have also tried GET instead of POST but that didn't work either. Does anyone know what I'm missing?

That error is occurring because the service is returning JSON and not JSONP. Your browser is not going to let you process straight JSON from a cross-domain source.
In order to make the service return JSONP you have to use a specially formatted URL. If you go to the search results page without the "/>json" modifier (link) you'll see a link on the page that reads "API Call". If you hover over this link it will give you the correct URL to use for the wireless/wired API call. Use one of those URL's in your ajax call with a JSONP return type & callback and you should be all set.
I created an updated fiddle at http://jsfiddle.net/qsY7h/1/.

This is a cross-domain request so you should use JSONP datatype - the API supports this return type. The URL you provided in your example didn't return anything for me so I checked out Broadbandmap's Developer Docs and found an alternate call. Please find an example at http://jsfiddle.net/szCAF/.
The most important point to note is "callback=?" in the URL. jQuery uses this to tell the API what function name to wrap around the output (this is all done transparently by jQuery).

Related

How to request curid or pageid when searching by Wikipedia API?

I am trying to search for a given term on the Wikipedia API and am able to retrieve a list of titles and snippets, but I want the JSON to also include the Wikipedia "curid" or "pageid" so I can use that for links.
Here is the (unhelpful) documentation as far as I can tell, and here is what I have so far:
var jsonresult=null;
$.ajax({
dataType: "jsonp",
url: "http://en.wikipedia.org/w/api.php?action=query&format=json&list=search&utf8=1&srsearch=Einstein&callback=?",
success: function(result){
console.log(result);
jsonresult = result;
printAjax(result);
},
error: function(error){
console.log("oh no");
}
});
}
I don't know how to change the API request URL.
To get "pageid" try query with generator instead list, and use extracts property for text snippet:
https://en.wikipedia.org/w/api.php?action=query&generator=search&utf8=1&gsrsearch=Einstein&prop=extracts&exintro=1&exlimit=20&exchars=200
Alternatively, you could use the url query in the ajax request and append the percent encoded title from the returned object encodeURI(data["query"]["search"][index]["title"]) to "https://en.wikipedia.org/wiki/" and use that for your page links.

how to get json data using ajax in cross domain

I have to dynamically get data from another domain dynamically and I want to use ajax and jquery.I have done the following.
<script type="text/javascript">
$(document).ready(function(){
$('#getdata').click(function(){
var sitename = $('#sitename').val();
var listname = $('#listname').val();
getdata(sitename, listname);
})
});
function getdata(sitename, listname){
$.ajax({
url : 'http://192.168.10.34:8576/home/GetJsonData?site='+sitename+'&listname='+listname+'&viewname=',
datatype : 'JSON',
type : 'GET',
crossDomain: true,
contentType: "application/json; charset=utf-8",
success : function(data){
console.log(data)
},
error : function(){
alert('error');
}
})
}
</script>
But it's just returning error. why? Have I done anything wrong?
any help/suggestions are welcome. thanks.
You cannot request data from any domain other than the domain from where your JavaScript has originated from. For cases like this you should use JSONP(JSON with Padding). Change the dataType to JSONP in jQuery ajax function. Like this...
datatype : 'JSONP'
Also, your cross domain(http://192.168.10.34:8576/home/GetJsonData) should support jsonp or else your request will fail.
The alternative to using the JSONP hack is to allow for Cross-Origin Resource Sharing on your application.
It's painfully simple to handle this, but understand that this opens up minor to intermediate security issues at scale, so make sure to take care of them appropriately.
Simply set the Access-Control-Allow-Origin response header in your server application to *. CORS requests also issue OPTIONS preflight requests, so you can choose whether or not to handle those as well.

Chrome API responseHeaders

Based on this documentation: https://developer.chrome.com/extensions/webRequest.html#event-onHeadersReceived
I tried to display the response via the console like:
console.log(info.responseHeaders);
But its returning undefined.
But this works though:
console.log("Type: " + info.type);
Please help, I really need to get the responseHeaders data.
You have to request the response headers like this:
chrome.webRequest.onHeadersReceived.addListener(function(details){
console.log(details.responseHeaders);
},
{urls: ["http://*/*"]},["responseHeaders"]);
An example of use. This is one instance of how I use the webRequest api in my extension. (Only showing partial incomplete code)
I need to indirectly access some server data and I do that by making use of a 302 redirect page. I send a Head request to the desired url like this:
$.ajax({
url: url,
type: "HEAD"
success: function(data,status,jqXHR){
//If this was not a HEAD request, `data` would contain the response
//But in my case all I need are the headers so `data` is empty
comparePosts(jqXHR.getResponseHeader('redirUrl')); //where I handle the data
}
});
And then I silently kill the redirect while scraping the location header for my own uses using the webRequest api:
chrome.webRequest.onHeadersReceived.addListener(function(details){
if(details.method == "HEAD"){
var redirUrl;
details.responseHeaders.forEach(function(v,i,a){
if(v.name == "Location"){
redirUrl = v.value;
details.responseHeaders.splice(i,1);
}
});
details.responseHeaders.push({name:"redirUrl",value:redirUrl});
return {responseHeaders:details.responseHeaders}; //I kill the redirect
}
},
{urls: ["http://*/*"]},["responseHeaders","blocking"]);
I actually handle the data inside the onHeadersReceived listener, but this way shows where the response data would be.

Jquery ajax call: how to parse results?

I have a modal dialog (done through jquery UI) that submit a form to a remote controller Action.
This is the jquery function called:
$("fpForm").submit(function() {
$.ajax({
type: "POST",
url: "ForgotPassword",
data: $("#fpForm").serialize(),
success: function(response) {
alert(response);
},
error: function(response) {
alert(response);
}
});
});
The action does some verification on the data and then send back a response in JSON format. Let's say, for example, that this is a sample response:
{"result":"NOK","message":"The user is not registered on the system"}
My questions are:
Why the debug alert that I have set in the "success" and "error" block does not are get executed?
How I can write my code to parse the response while remaining in wait for it on the dialog?
How can I write code to block the form elements during the ajax call?
I am sorry if the question could seem stupid for most of you but I am completely new to ajax and I am trying to learn throgh some experienced pattern that I know.
Thank you for your responses
The first error is the usage of $("fpForm").submit instead of $("#fpForm").submit.
If the server sand back JSON data, for example as JsonResult, you should include dataType: "json" to convert result to the object in object. After that you can replace alert(response); to
alert('Result: ' + response.result + ', Message: ' + response.message);
To block the form element I'll recommend you to use jQuery BlockUI Plugin. On the demos you will find different examples of usage and find the way which you like.
My questions are:
Why the debug alert that I have set in the "success" and "error" block
does not are get executed?
How I can write my code to parse the response while remaining in wait
for it on the dialog?
How can I write code to block the form elements during the ajax
call?
If you meant to use the id then you missed the # designator:
$("#fpForm")
Add the sync : true option on the call?
You could either: set the disabled attribute on the form elements AFTER posting the request, or else mask the page with an element (possibly semi-transparent) to divert the inputs.

Using jQuery to get json data returns invalid label error

I have this code, and have also tried something similar using the $.getJson function:
jQuery(document).ready(function(){
var kiva_url = "http://api.kivaws.org/v1/loans/newest.json";
jQuery.ajax({
type: "GET",
url: kiva_url,
data:"format=json",
success: function(data){
alert("here");
jQuery.each(data.loans, function(i, loan){
jQuery("#inner_div").append(loan.name + "<br />");
});
},
dataType: "jsonp",
error: function(){
alert("error");
}
});
});
When I look in Firebug it is returning an "invalid label" error. I've searched around a bit some people refer to using a parser to parse the results. I can see the results coming back in Firebug. Can someone point to an example of what I should be doing?
The Firebug error:
invalid label
http://api.kivaws.org/v1/loans/newest.json?callback=jsonp1249440194660&_=1249440194924&format=json&
Line 1
Sample output of what the json looks like can be found here:
http://build.kiva.org/docs/data/loans
Well I found the answer...it looks like kiva does not support jsonp which is what jquery is doing here -
http://groups.google.com/group/build-kiva/browse_thread/thread/9e9f9d5df821ff8c
...we don't have plans to support JSONP.
Supporting this advocates poor
security practices and there are
already some good ways to access the
data from JavaScript that protect your
application and your users. Here's a
great article on the subject:
http://yuiblog.com/blog/2007/04/10/json-and-browser-security/
While the risk to Kiva lenders is low
now since we are only dealing with
public data, allowing private lender
data to be imported via script tags is
a risk further down the road. Our
thought is the risk (and complexity
added to create secure applications)
is not worth the benefit to
developers.
Writing a server-side proxy for the
feeds you need is the most common
solution to accessing data in
browser-based applications. Some
other tricks exist using iFrames. The
best hope is the new breed of client-
based technologies/standards that will
let browser-based JavaScript access
cross-domain resources securely (
http://dev.w3.org/2006/waf/access-control/
http://json.org/JSONRequest.html ).
Some tools like BrowserPlus and Gears
let you play with these today, but you
won't be able to depend on these in
the wild for a while.
As a final note, I'll point out that
anyone using JSON responses in
JavaScript should either parse JSON
explicitly or validate the JSON before
taking eval() to it. See here:
http://www.JSON.org/js.html
Linked from the page is a great
reference implementation of the
proposed ECMAScript JSON parser
interface, JSON.parse().
Cheers, skylar
maybe this can help with jsonp:
http://remysharp.com/2007/10/08/what-is-jsonp/
When you return the data, are you returning it with the correct content type and as a method?
You should return your data as follows (php 5 example):
$return = "my_callback_method(" . json_encode( array('data'=>'your data etc') ). ")";
while (#ob_end_clean());
header('Cache-Control: no-cache');
header('Content-type: application/json');
print_r($return);
In your calling javascript code, you must have a method to match the callback method you returned, in this case:
function my_callback_method( returned_data ){
}
So, your complete calling js should look something like the following
jQuery(document).ready(function(){
var kiva_url = "http://api.kivaws.org/v1/loans/newest.json";
jQuery.ajax({
type: "GET",
url: kiva_url,
data:"format=json",
dataType: "jsonp",
error: function(xmlhttp,error_msg){
alert("error"+error_msg);
}
});
function my_callback_method( data ){
alert("here");
if( data && typeof(data) == 'object') ){
jQuery.each(data.loans, function(i, loan){
jQuery("#inner_div").append(loan.name + "<br />");
});
}
}
});
Where does the error occur? Does error occur when you try to loop through the ajax data and append it to the inner_div? If yes, please show us what the data.loans look like.
Also, there is a typo in your code:
jQuery.each(data.loans, function(i, loan){
jQuery("#inner_div").append(loan.name + "<br />"); //It should be loan.name and not laon.name
});
},
This is the answer
http://forum.jquery.com/topic/jquery-getjson-invalid-label
Simply wrap your Json response with your callback request
E.g. jQuery16203473509402899789_1315368234762({"Code":200,"Message":"Place added successfully","Content":""});
where
jQuery16203473509402899789_1315368234762 is your callback request (you can get it via querystring)
{"Code":200,"Message":"Place added successfully"} is your JSON response