Enable cache for load function - javascript

I have this code for loading a page in another :
$(".container").load(url, function () {
// do stuff
});
When this code executes, all of GET requests has _={timestamp} at the end of their links, like this : http://localhost:2208/Scripts/jquery-1.9.1.min.js?_=1399788658418
I want to enable cache for my requests, also i need this only for this line.
I searching for some solutions and i guess using ajaxSetup do this, but i need to enable only for 1 request in my website.
What's your idea?

You need to use $.ajax() if you want to use extra settings.
$.ajax({
url: url,
dataType: 'html',
success: function (data) {
$(".container").html(data);
// do stuff
},
cache: false
});

Related

AJAX multiple responses

I'm diving into JavaScript and AJAX technologies now, and I understand AJAX and POST well with it. Now I wonder whether there's something like a broadcasting channel that my PHP code (in this case, Laravel controller) broadcast to, which then is received by JavaScript on the client side in order to manipulate something, say a process like this:
User clicks a button, a spinner is shown inside the button. Next to the button, there's a status label indicating the current process/task being processed. Finally, the button becomes a link or something else. So, what I want now is that I can update the status multiple times, since my current AJAX code will only receive one message, or one status, at the end of the process and that's it, nothing in between:
$.ajax({
url: "/admin/test",
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
method: 'POST',
dataType: 'json',
data: {
id: whatever
},
success: function(result)
{
console.log(result.status);
}
});
Now I wonder how this further works.
You can make use of beforeSend event of ajax and use to start a progress bar and when it completes you can make progress bar width to 100%
$.ajax({
url: "/admin/test",
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
method: 'POST',
dataType: 'json',
data: {
id: whatever
},
beforeSend : {
// start progress bar
},
success: function(result)
{
console.log(result.status);
// complete progress bar
}
});
Additionally, you could use css to apply transition to give the feeling the of progress in progress bar.
Use the concept of javascript callback or promise. You can creatw a script where when the button is clicked , a onclick function will run and change the content inside of tge button and when changed do the ajax call and if success call the promise again

How to ensure ajax call is always made (not fetched from cache)

I have the following code. The function is called multiple times depending on the user checking or unchecking checkboxes.
This works in all browsers except IE10/11. In IE, the ajax call is only made once for a particular ID. Subsequent calls are not actually sent to the server, but appear to be fetched from the cache.
In F12 developer tools, the call appears to be being made to the server, but Fiddler shows that it is not actually happening.
F12 also shows a 304 response to the call.
How do I ensure that the call is always made to the server?
function updateReportTypes(event) {
var value = event.currentTarget.value;
if (event.currentTarget.checked) {
$.ajax({
url: "/PropertySearch/Order/AddReportType?id=" + value,
dataType: 'html',
success: function (data) {
$('#reportTypes').html(data);
hideProgress();
}
});
}
else {
$.ajax({
url: "/PropertySearch/Order/RemoveReportType?id=" + value,
dataType: 'html',
success: function (data) {
$('#reportTypes').html(data);
hideProgress();
}
});
}
}
Simple set the:
cache: false
argument to $.ajax(). When you do that, jQuery will automatically add a unique paramter onto the URL which prevents any caching of the request.
Using that option would look like this:
$.ajax({
url: "/PropertySearch/Order/AddReportType?id=" + value,
dataType: 'html',
cache: false,
success: function (data) {
$('#reportTypes').html(data);
hideProgress();
}
});
jQuery doc on this option: http://api.jquery.com/jquery.ajax/
I'm not familiar with this specific issue, but if all else fails, you should be able to add a dynamic, cache-busting value, such as a timestamp, to make your URL unique:
url: "/PropertySearch/Order/RemoveReportType?id=" + value + "&" + Date.now().toString()

JQuery POST aborted after page redirect

I have JQuery ajax POST operation which saves some data to a database. The operation takes about less than 20 milliseconds. This piece of javascript is embedded inside a .NET Web Forms application (out of my control). This .NET application triggers my POST inside a submit button and redirects to a another page. Now for the following browsers the POST is never executed:
FF on Windows
Safari on MAC
Chrome on MAC
IE works fine and even Chrome on Windows.
So I did some tests and tried to mimic the .NET Web Forms website which I luckily could reproduce by adding 'window.location = "go to another site"' directly after my save action. Here is my (stripped) code:
//BUTTON
$('#someSaveButton').click(function () {
GlobalObject.save();
});
// GLOBAL OBJECT CONTAINING ALL MY ACTIONS (delete, check, save, get)
var GlobalObject = (function () {
return {
save: function () {
...
someMode.save(); //NOTE: Depending on an url parameter different save methods are supported
window.location.href = "http://www.google.com"; //MIMIC-ING REQUEST ABORTING
}
};
})();
//EVENTUALLY THE SAVE:
function save() {
$.ajax({
type: "POST",
cache: false,
url: ...,
data: ...,
contentType: "application/json",
dataType: "json",
success: function (response) {
...
},
error: function (msg) {
...
}
});
}
This above reproduces the same POST-aborting behaviour. NOTE: the browser debugger reaches the $.ajax statement but never returns into 'success' or 'error'.
SOUTION I FINALLY FOUND:
I added 'async : false,' to the ajax call and everything seems to work fine!
Now I want to be sure if this is a correct solution because when I read on the JQuery site:
As of jQuery 1.8, the use of async: false with jqXHR ($.Deferred) is deprecated; you must use the success/error/complete callback options instead of the corresponding methods of the jqXHR object such as jqXHR.done() or the deprecated jqXHR.success().
I get a feeling the 'async: false' is maybe not a good solution. Is my Javascript construction OK? My background is C# and I am still learning/struggling on how to correctly embed/use functions inside javascript class definitions. So maybe my errors are related to a wrong construction of my functions (and the javascript garbage collector is cleaning things up or something).
alternatively, instead of settings async as false, you can do the redirect (window.location.href = "http://www.google.com";) within the success callback of the $.ajax call (and leave async: true):
//BUTTON
$('#someSaveButton').click(function () {
GlobalObject.save();
});
// GLOBAL OBJECT CONTAINING ALL MY ACTIONS (delete, check, save, get)
var GlobalObject = (function () {
return {
save: function () {
// ...
someMode.save(); //NOTE: Depending on an url parameter different save methods are supported
}
};
})();
//EVENTUALLY THE SAVE:
function save() {
$.ajax({
type: "POST",
cache: false,
url: ...,
data: ...,
contentType: "application/json",
dataType: "json",
success: function (response) {
// do stuff
// more stuff
// ... redirect when completed stuff
window.location.href = "http://www.google.com"; //MIMIC-ING REQUEST ABORTING
},
error: function (msg) {
// ...
}
});
}
hope that helps.
Your use of async: false is justified and correct in this instance.
The deprecation note refers to setting callback handlers on the jqXHR object, but you're already supplying them through the options object anyway.
Using async: false in this situation would not be incorrect, since the page is closing anyway and the user wouldn't expect it to be responsive, so the execution blocking goes mostly unnoticed (aside from the fact that 20 milliseconds are near inconceivable).
From the information provided, I don't see a cleaner solution than this.

Add cache to ajax json request

I have a basic ajax call to parse a json file. I need to make sure I am not hitting the feed every time someone visits the page. How would I go about adding some sort of cache so the feed only get's requested say every say 2 hours?
$(function () {
$.ajax({
type: "GET",
dataType: "json",
url: "my.json",
success: function (data) {
// do something with the data
}
});
May be you can use cookie store your time and check every time to know 2 hours time gap then you can call your function get the latest feed.
By default, is should get cached. You can set the option explicitly as shown below.
$(function () {
$.ajax({
type: "GET",
cache: true,
dataType: "json",
url: "my.json",
success: function (data) {
// do something with the data
}
});
You can also use the below statement for all ajax calls on the page.
$.ajaxSetup({cache: true});

Multiple AJAX requests in jQuery

I have a function that pulls data from two locations and places the returned content on a modal dialog that is displayed to the user.
Both requests are asynchronous because they're cross-domain. The problem lies in that I don't want to display the modal until both requests have finished loading. How can I check to make sure both requests have finished before loading the modal?
I have tried placing the openModal functions in the success handler of the second request and that works when the first requests finishes loading before the second request, but sometimes this isn't the case.
Here's a copy of my code:
function loadData(id) {
$.ajax({
type: 'GET',
url: 'https://someurl.com/v1.0/controller1/' + id,
dataType: 'jsonp',
success: function(data) {
// Do some stuff to the data
}
});
$.ajax({
type: 'GET',
url: 'https://someurl.com/v1.0/controller2/' + id,
dataType: 'jsonp',
success: function(data) {
// Do some stuff to the data
openModal();
}
});
}
function openModal() {
// Open the modal
}
Check out the new version of jQuery -- 1.5. It has support for exactly your problem, you can check out this blog post for the solution of your problem: http://www.erichynds.com/jquery/using-deferreds-in-jquery/
You could put the one of the ajax requests inside the success callback of the other request, but that wouldn't be as efficient as having them both request at the same time. Then you'd just have to put the openModal call inside the success callback of the inner ajax request. Not optimal, it would be a quick and easy fix if this solution would work for you until a better option is found.
I'm going to keep thinking on this one...
$.when(
$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?", {
tags: "moon",
tagmode: "any",
format: "json"
}),
$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?", {
tags: "bird",
tagmode: "any",
format: "json"
})).then(function (res1, res2) {
});

Categories

Resources