Using both cached and non-cached JSON from an Ajax request - javascript

I have two JSON sources: getCachedJSON.php and getNotCachedJSON.php. As suggested by the names, the client should cache the results from the first but not the second. Both of these files will issue the appropriate headers to tell the client to cache or not cache the data.
How is this best accomplished?
I came up with the following, but don't know if this is how it should be done. And if it is the right way, should the cached JSON be first requested and then the non-cached JSON, or the other way around?
$.ajax({
//cache: true,
url: "getCachedJSON.php",
dataType: "json",
success: function(cachedJSON) {
$.ajax({
//cache: false,
url: "getNotCachedJSON.php",
dataType: "json",
success: function(notCachedJSON) {
var allJSON = $.extend({}, cachedJSON, notCachedJSON);
console.log(allJSON);
}
});
}
});

Browser manages caching for you. Each time when you're making GET request the browser check if it has this resources in its cache. If it has it then request is not made. To tell browser how to control caching you have to use http headers like cache-control and max-age (try to google for details). You have to set these headers when browsers access you server. You can use chrome's dev tools (network) to inspect if there is any requests made. There you will see if resource is obtained from cache or from request.
If you want event better cache control I recommend you to use service workers or browser sql databases.
Hope I understood your question right.

If you want to make a server request and cache it on the client side, you can make use of the browser's local storage.
You could do something along the lines of this:
var allData = cached(nonCached);
function cached(callback){
var cachedData = localStorage.getItem('cached');
// if locally stored data is found, pass it to the callback
if(cachedData){
callback(JSON.parse(cachedData));
} else {
// Else get it from php script, store it, and pass to callback
$.ajax({
url: "getNotCachedJSON.php",
dataType: "json",
success: function(cachedData) {
var key = 'cached';
localStorage.setItem(key, JSON.stringify(cachedData));
callback(cachedData);
}
});
}
}
function nonCached(cachedData){
$.ajax({
url: "getNotCachedJSON.php",
dataType: "json",
success: function(nonCachedData) {
return $.extend({}, cachedData, nonCachedData);
}
});
}

Related

How to get a json response from yaler

I create an account with yaler, to comunicate with my arduino yun. It works fine, and i'm able to switch on and off my leds.
Then i created a web page, with a button that calls an ajax function with GET method to yaler (yaler web server accept REST style on the URL)
$.ajax({
url: "http://RELAY_DOMAIN.try.yaler.net/arduino/digital/13/1",
dataType: "json",
success: function(msg){
var jsonStr = msg;
},
error: function(err){
alert(err.responseText);
}
});
This code seem to work fine, infact the led switches off and on, but i expect a json response in success function (msg) like this:
{
"command":"digital",
"pin":13,
"value":1,
"action":"write"
}
But i get an error (error function). I also tried to alert the err.responseText, but it is undefined....
How could i solve the issue? Any suggestions???
Thanks in advance....
If the Web page containing the above Ajax request is served from a different origin, you'll have to work around the same origin policy of your Web browser.
There are two ways to do this (based on http://forum.arduino.cc/index.php?topic=304804):
CORS, i.e. adding the header Access-Control-Allow-Origin: * to the Yun Web service
JSONP, i.e. getting the Yun to serve an additional JS function if requested by the Ajax call with a query parameter ?callback=?
CORS can probably be configured in the OpenWRT part of the Yun, while JSONP could be added to the Brige.ino code (which you seem to be using).
I had the same problem. I used JSONP to solve it. JSONP is JSON with padding. Basically means you send the JSON data with a sort of wrapper.
Instead of just the data you have to send a Java Script function and this is allowed by the internet.
So instead of your response being :
{"command":"digital","pin":13,"value":0,"action":"write"}
It should be:
showResult({command:"analog",pin:13,value:0,action:"write"});
I changed the yunYaler.ino to do this.
So for the html :
var url = 'http://try.yaler.net/realy-domain/analog/13/210';
$.ajax({
type: 'GET',
url: url,
async: false,
jsonpCallback: 'showResult',
contentType: "application/json",
dataType: 'jsonp',
success: function(json) {
console.dir(json.action);
},
error: function(e) {
console.log(e.message);
}
});
};
function showResult(show)
{
var str = "command = "+show.command;// you can do the others the same way.
alert (str);
}
My JSON is wrapped with a showResult() so its made JSONP and its the function I called in the callback.
Hope this helps. If CORS worked for you. Could you please put up how it worked here.

Sending data to server using get request header

I use jQuery to contact my REST service on server side. The URL looks like this:
http://bla.com/?userid=1,2,3,4,5,6...
The userid string could be very long and it could happen that the max url size will be exceeded.
I can't do a post request, so my question is, whether it would be a good solution to send the userid data within the header? Something like this:
$.ajax({
url: 'someurl',
headers:{'foo':'bar'},
complete: function() {
alert(this.headers.foo);
}
});
Would this be possible?
Thanks
Yes you can send header using Ajax request
$.ajax({
type: "GET",
beforeSend: function(request) {
request.setRequestHeader("Authority", authorizationToken);
},
url: "entities",
data: "json=" + escape(JSON.stringify(createRequestObject)),
processData: false,
success: function(msg) {
$("#results").append("The result =" + StringifyPretty(msg));
}
});
you can read more about header on jQuery AJAX page
Also check this example here
This is totally possible, alhough it would be advisable to just use POST, because it was meant to transfer lots of data.
Using headers is a workaround which results in the same results as POST; losing the ability to navigate forward and back without re-submitting (or re-sending headers in this case, will be impossible if the data is gone).

Wrong additional parameters in $.ajax

I'm trying to call a web service to get some data. I need pass this URL in a GET method:
http://localhost/ecosat/ws/api.php?t=vw_motorista
But, when I look in Chrome Developer Tools, the link is:
http://localhost/ecosat/ws/api.php?t=vw_motorista&_=1397500899753
I'm not passing this parameter: &_=1397500899753
With this additional parameter, I received a 500 error. I can't change the web service to handle this.
What's going on? Is Chrome is changing my code?
This my Ajax
function get(pURL, pToken) {
var ret = null;
$.ajax({
type: "GET",
dataType: "json",
async: false,
timeout: globalTimeOut,
cache: false,
url: pURL,
headers: {"Token": pToken},
error: function(request, status, error) {
ret = null;
},
success: function(data) {
ret = data;
}
});
return ret;
}
You're probably using cache: false setting in your ajax query. It adds a _ parameter with a timestamp value, to make sure that your ajax call doesn't get cached by the browser.
Remove this setting, if you don't need it. But if you need make sure caching is disabled, you could try two things:
add your own parameter with a timestamp to your query, e.g. {ts: new Date.getTime()}, or
if possible, add headers to the web server response. See this question

How do I do an ajax call to a database using Javascript, a URL and a key

I have been given a url of type xxxx.xxxxx.com as well as a key of type FGHyehgvc787vbhj
in order to gain read-only access to an sql database and retrieve data from it using javascript.
I have no prior experience with databases and maybe my question will sound completely stupid but I was wondering how can I combine the above information in order to get access to the database (e.g. do an ajax call and retrieve data from it..)
I'm familiar with doing ajax calls to a webpage and getting data from it using jQuery, as in :
$.ajax(/*url of website*/, function (data)
{
var dataRetrieved = $(data);
// do something with the data retrieved...
});
so I was wondering whether there is something equivalent to the above when it comes to making an ajax call to a database, using however a key.
Thank you for any help, and please delete this post if you find it completely pointless and excuse me in advance for that by the way.
It is usually very bad design to allow client side code to interact with your database in any way. This can be a huge security issue. Generally you will want your server side code to do this (e.g PHP, node, etc.). You would send a request to your server with client side code, and the server side code would do the actual work of updating the database.
you can create a wcf service and call that service through ajax, that wont be huge security issue.
try this
$.ajax({
cache: false,
type: "GET",
async: false,
data: {},
url: http:xxxxxxxxxxxx.svc/webBinding/Result?metaTag=" + meta,
contentType: "application/json; charset=utf-8",
dataType: "json",
crossDomain: true,
success:function(result){},
error: function(){alert(err);}
});
Use this
$.ajax({
url: 'path/to/server-side/script.php', /*url*/
data: '', /* post data e.g name=christian&hobbie=loving */
type: '', /* POST|GET */
complete: function(d) {
var data= d.responseTXT;
/* Here you can use the data as you like */
$('#elementid').html(data);
}
});
Hope this helps...

Get prayer time JSON data using JQUERY and Ajax

I want to READ JSON data using Jquery ana Ajax from this link
http://praytime.info/getprayertimes.php?lat=31.950001&lon=35.9333&gmt=180&m=3&y=2013&school=0&format=json&callback=?
and this is my code:
$(document).ready(function() {
var strUser ="http://praytime.info/getprayertimes.php?lat=31.950001&lon=35.9333&gmt=180&m=3&y=2013&school=0&format=json&callback=?";
$.ajax({
url: strUser ,
dataType: 'jsonp',
success: function(data){
jQuery.each(data, function(){
alert("yes");
});
}
});
});
I tried this code with other links , and it's correct, but from the specified link I don't get any out put, can you help me??
The url you are trying to access with JSONP doesnot support it. The server will need to return the response as JSON, but also wrap the response in the requested call back. So a way to solve this problem is using a server side proxy, which fetches the response from the specified url and passes it on to your client side js, like:
$.ajax({
type: "GET",
url: url_to_yourserverside_proxy,
dataType: "json",
success: function( data ) {
console.log(data);
}
});
where
url_to_yourserverside_proxy is a server side file that fetches response from the url specified
URL is outputting json but for cross domain need jsonp.
Not all API's provide jsonp. If cross domain API doesn't provide jsonp and isn't CORS enabled you will need to use a proxy to retrieve data due to same origin policy

Categories

Resources