how to get json data using ajax in cross domain - json

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.

Related

how to process json post request with nodejs http (no express framework)? [duplicate]

Can someone explain in an easy way how to make jQuery send actual JSON instead of a query string?
$.ajax({
url : url,
dataType : 'json', // I was pretty sure this would do the trick
data : data,
type : 'POST',
complete : callback // etc
});
This will in fact convert your carefully prepared JSON to a query string. One of the annoying things is that any array: [] in your object will be converted to array[]: [], probably because of limitations of the query sting.
You need to use JSON.stringify to first serialize your object to JSON, and then specify the contentType so your server understands it's JSON. This should do the trick:
$.ajax({
url: url,
type: "POST",
data: JSON.stringify(data),
contentType: "application/json",
complete: callback
});
Note that the JSON object is natively available in browsers that support JavaScript 1.7 / ECMAScript 5 or later. If you need legacy support you can use json2.
No, the dataType option is for parsing the received data.
To post JSON, you will need to stringify it yourself via JSON.stringify and set the processData option to false.
$.ajax({
url: url,
type: "POST",
data: JSON.stringify(data),
processData: false,
contentType: "application/json; charset=UTF-8",
complete: callback
});
Note that not all browsers support the JSON object, and although jQuery has .parseJSON, it has no stringifier included; you'll need another polyfill library.
While I know many architectures like ASP.NET MVC have built-in functionality to handle JSON.stringify as the contentType my situation is a little different so maybe this may help someone in the future. I know it would have saved me hours!
Since my http requests are being handled by a CGI API from IBM (AS400 environment) on a different subdomain these requests are cross origin, hence the jsonp. I actually send my ajax via javascript object(s). Here is an example of my ajax POST:
var data = {USER : localProfile,
INSTANCE : "HTHACKNEY",
PAGE : $('select[name="PAGE"]').val(),
TITLE : $("input[name='TITLE']").val(),
HTML : html,
STARTDATE : $("input[name='STARTDATE']").val(),
ENDDATE : $("input[name='ENDDATE']").val(),
ARCHIVE : $("input[name='ARCHIVE']").val(),
ACTIVE : $("input[name='ACTIVE']").val(),
URGENT : $("input[name='URGENT']").val(),
AUTHLST : authStr};
//console.log(data);
$.ajax({
type: "POST",
url: "http://www.domian.com/webservicepgm?callback=?",
data: data,
dataType:'jsonp'
}).
done(function(data){
//handle data.WHATEVER
});
If you are sending this back to asp.net and need the data in request.form[] then you'll need to set the content type to "application/x-www-form-urlencoded; charset=utf-8"
Original post here
Secondly get rid of the Datatype, if your not expecting a return the POST will wait for about 4 minutes before failing. See here

Partial HTML caching

I have javascript code, which calls to server to get json and then generates HTML and append it to body tag:
$.ajax({
url: '/myController/myJsonMethod',
type: 'POST',
data: JSON.stringify(requestData),
dataType: 'json',
contentType: 'application/json; charset=utf-8',
error: function (xhr) {
alert('Error: ' + xhr.statusText);
},
success: function (result) {
var myHTML='<div>'+result.text+'</div>'+.....
$( "body" ).append(myHTML);
},
async: true,
processData: false
});
This code is mostly static. The value of json result is changing couple of times in a year. Is there any way to cache this html part of the page?
Caching the generated HTML hardly makes sense, since it is trivial. What does make sense is to cache the actual ajax request, which is a normal http request.
For that you the normal points apply that control caching of request results. Actually the default behavior is that such results are cached, unless you took special precautions to prevent that. Take a look at the http headers you send first.
However there is one issue with such strategy: even if the requests result changes only rarely, still you have to consider what actually happens in that case: if you cache the request, then the client is unable to see the change until the cache is outdated.

JSON works Locally but not with Servers

Here is my little first project as practice, having real trouble figuring out how to use JSON, took me a while to get it work locally but still no luck with servers, and tried few a including one i hosted, and even tried it with other hosted json files.
http://jsfiddle.net/Atlas_/Mgyc5/1/
$.ajax({
dataType: "json",
async: false,
url: "package.json", //https://www.dropbox.com/s/fmw63i4v7dtnx6t/package.json
'success': function (json) {
theQuiz = json.quiz;
console.log(json);
console.log(theQuiz);
}
});
When you access another domain be carefully with "Crossdomain".
To use with dropbox, try changing the URL to:
https://dl.dropboxusercontent.com/s/fmw63i4v7dtnx6t/package.json
Your code will be like this:
$.ajax({
dataType: "json",
async: false,
url: "https://dl.dropboxusercontent.com/s/fmw63i4v7dtnx6t/package.json",
success: function (json) {
theQuiz = json.quiz;
console.log(json);
console.log(theQuiz);
}
});
When you request 'dl.dropboxusercontent.com', you have this:
Access-Control-Allow-Origin: *
https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS?redirectlocale=en-US&redirectslug=HTTP_access_control
"In this case, the server responds with a Access-Control-Allow-Origin:
* which means that the resource can be accessed by any domain in a cross-site manner."
Another options: Some websites (twitter, for example) work with "jsonp". http://en.wikipedia.org/wiki/JSONP or ..you can create your own proxy.

Posting parameters in one URL and getting JSON from another URL

Am working in jQueryMobile and PhoneGap.
Currently am facing an issue that; For get the details in JSON format ; I post parameters into an URL (URL1) and I get the JSON response from another URL (URL2)
Currently i cant access the JSON data from the second URL.
My code is ;
function proceed_payment(){
var cardholder_= $('#input_Cardholder_name_').val();
var card_num_ = $('#input_CreditCard_').val();
var payment_ =$('#card_type_').val();
var cvv2_=$('#input_cvv2_').val();
var url;
url='https://www.sample.com/json/save_pament.php?json=1&rcg_mobile=2&reserv_num='+reservation_number+'&callback='+reservation_carcompany+'&cardholder='+cardholder_+'&payment='+payment_+'&card_num='+card_num_+'&card_cvv2='+cvv2_+'&card_expire_mon='+expire_month+'&card_expire_year='+expire_year+'&org_deposit='+sCarDeposit+'&org_cur='+currency+'&mond='+company_Show_mond+''
$.ajax({
url:url,
data:'',
contentType: "application/json; charset=utf-8",
type: "POST",
dataType: "json",
crossDomain:true,
cache: false,
async:false,
success:function(data)
{
alert(data.Status);
$.mobile.changePage( "#reservation_status", {reverse: false, changeHash: true});
event.preventDefault();
},
error: OnError
});
};
Here I Post the parameters to URL1 : - https://www.sample.com/json/save_pament.php?
and get the JSON result in URL2 : https:// www.sample.com /result_bank_eup6.php?app=1
But My problem is i cant access the result from URL2.
Is there any method for solve this?
Please HELP :-(
Ullas Mohan V.
As per our discussion in comments and the error you mentioned
( [object Object]-parseerror-SyntaxError: Unexpected token < ).
The issue is related to web service/server side
Web service is not sending the desired response.
So client side/$ajax is not able to parse it.
You can check the actual response using Google Chrome's Advance REST Client.
To resolve this issue, you should contact the company
which is developing server side for you.

Consuming broadbandmap.gov json service errors

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).