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.
Related
So I've been trying to use the time_filter parameter to get a list of my current and future Events (so no past events) but instead I'm getting all the events; so that parameter is not working for me. Is weird because other parameters like 'expand=venue' do work, but when I try for example time_filter=current_future it doesn't work and instead I still receive all events including those events that has expired.
Here is the AJAX code I'm using to call the API:
$.ajax({
type: 'GET',
url: 'https://www.eventbriteapi.com/v3/users/me/events/?time_filter=current_future&expand=venue&token=MYTOKEN',
dataType: 'json',
contentType: 'application/json'
}).done(function (result) {
//result code goes here
});
Has anyone here successfully used the time_filter parameter and if so what am I doing wrong? because that parameter is the only one that the GET call ignores cause all the others I've used work. Any help is appreciated.
Thanks!
Found the solution. Removing contentType: 'application/json' solves the issue. I'm not sure why, maybe is cause since I'm not sending data then it perhaps steps in the way of the parameters I'm trying to send. Either way, for those using Eventbride API and are not sending custom data and also want to use the time_filter parameter; then removing contentType: 'application/json' will solve the problem.
Here is the working code:
$.ajax({
type: 'GET',
url: 'https://www.eventbriteapi.com/v3/users/me/events/?time_filter=current_future&expand=venue&token=MYTOKEN',
dataType: 'json'
}).done(function (result) {
//result code goes here
});
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.
I am trying to pull in some external JSON phone list for a test I am doing locally.
JSON = https://www.o2.co.uk/shop/homepage/scripts/phoneList.json
I have read on a seperate thread that to overcome allow origin / cross domain issues you can pass 'callback=?' to the end of the url. This seems to work fine as now in the devtools network tab I can see the file being pulled in fine.
However, I never get it to go into the success callback function. It always brings back a parsererror.
The code is 100% valid according to jsonlint.com
A snippet of the code as below:
$.ajax({
type: 'GET',
url: 'https://www.o2.co.uk/shop/homepage/scripts/phoneList.json?callback=?',
contentType: 'application/json; charset=utf-8',
cache: true,
dataType:'json',
success: function(response) {
console.log(response);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(jqXHR);
console.log(textStatus);
console.log(errorThrown);
}
});
Any ideas welcome as I am well and truly stuck.
Thanks.
JSONP only works if the server supports it. What the server needs to do, is take your callback parameter and wrap the json data in a function call with that name.
So when https://www.o2.co.uk/shop/homepage/scripts/phoneList.json responds with
[{
"handset":"Alcatel 10.30 Black",
"link":"/shop/phones/alcatel/10.30-black/"
}]
https://www.o2.co.uk/shop/homepage/scripts/phoneList.json?callback=MyCallback should respond with:
MyCallback([{
"handset":"Alcatel 10.30 Black",
"link":"/shop/phones/alcatel/10.30-black/"
}]);
If the server doesn't do that, JSONP can't work. Perhaps O2 doesn't want you using their data.
I have to cache json data for my phonegap applicaiton for 10 minutes how to do that?
server response is already with the expiry headers.
Cache-Control: max-age=315360000
Expires: Sun, 12 Sep 2038 20:15:20 GMT
BUT jquery ajax request is not being cached.
[a] Sometimes we need to enable and disable ajax request caching for browsers. can be done via below flag. cache: true
if set to true ajax request will start caching depending upon the content deposition header.
if set to false a unique timestamp will be appended to request so
that request is never cached.
http://www.exp.com/api/get_posts/?count=12&page=1&_=1381305201264
code:
global_xhrAbort = $.ajax({
cache: true,
type: "GET",
timeout: 30000,
async: false,
url: finalurl,
data: null,
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
dataType: "json",
complete: function () {
},
success: function (data) {
console.log('picked from server koimoi: success');
Page_topstoriesJson = GetJSONifNeeded(data); ;
HTMLSTORAGE_SET('landingpage', GetJSONstringfyifNeeded(data)); //will expire in ten mintues
doChangesForMainandTopStoriesSlider();
HideLoading();
}
,
error: function (errmsg) {
alert_dialog('Request failed. Please check your internet connection or Press Refresh Button.',true);
console.log('index_devicreReadyError: ' + errmsg);
}
});
Jquery AJAX cache documentation : (default: true, false for dataType 'script' and 'jsonp')
Type: Boolean
If set to false, it will force requested pages not to be cached by the browser. Note: Setting cache to false will only work correctly with HEAD and GET requests. It works by appending "_={timestamp}" to the GET parameters. The parameter is not needed for other types of requests, except in IE8 when a POST is made to a URL that has already been requested by a GET.
[b] Remember: Ctrl+R on chrome always loads new data from server, even if its cached. Open page in new window to see the results while testing.
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.