I have setup properties in my Ajax Request not to store cache. I have also added query string as a parameter in the URL to call new Ajax request. But whenever i refresh the page i see old content on the page. I always have to hard refresh a page to see the updated content.
The request headers are getting passed to the browser correctly which i have set in the properties of ajax. But why do i always have to hard refresh to get the updated content. How can i load the new content on just a page refresh. I have pasted my Ajax below
AJAX Methods to set the properties
$.ajaxPrefilter(function (options, originalOptions, jqXHR) {
if (options.type == 'POST') {
options.url += '?' + Date.now();
}
});
$.ajaxSetup({
cache: false,
headers: {
'Cache-Control':'max-age=0, public'
},
});
My JQuery
$.ajax({
url: "/Configuration/TestPlan/GetUserList",
type: 'POST',
cache: false,
dataType: 'json',
// async :false,
beforeSend: function () {
//call pageloader
showImageLoader();
},
data:jsonString,
contentType: "application/json; charset=utf-8",
success: function (data) {
From jquery - ajax - "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" -
So I don't think the cache option is doing what you think. Since it's a POST the only thing that will affect the cache-busting is that little snippet you have:
$.ajaxPrefilter(function (options, originalOptions, jqXHR) {
if (options.type == 'POST') {
options.url += '?' + Date.now();
}
});
Every time it makes a request - that page is actually being cached. It just does a new Date.now() - then that url is cahced until you do a new Date.now().
So when you comment it out - the last page/data called for is cached and now you've commented out the only thing updating the cachebuster.
Perhaps just apply the cache busting directly to the raw call:
$.ajax({
url: "/Configuration/TestPlan/GetUserList?" + Date.now(),
type: 'POST',
cache: false,
dataType: 'json',
// async :false,
beforeSend: function () {
//call pageloader
showImageLoader();
},
data:jsonString,
contentType: "application/json; charset=utf-8",
success: function (data) {
Related
As the title says, I wanna check if this ajax method has been submitted or not and show the result in a condition.
Here is the Ajax POST code;
$.ajax({
url: "addorderInfo.php", // Url to which the request is sent
type: "POST", // Type of request to be send, called as method
data: new FormData(this), // Data sent to server, a set of key/value pairs (i.e. form fields and values)
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData:false,
success: handleResult
});
And here is the condition I put but it is not working.
function handleResult(data){
if(data == 'error'){
window.location.href ='404.php';
}
else{
$( "#clearcart" ).click();
window.location.href = "ordercomplited.php";
}
}
try this
$.ajax({
url: "addorderInfo.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function (data) {
alert(data)
},
error: function (error) {
alert(error.responseText) // if your request doesn't work
}
});
There isn't sufficient code to know why is not working.
IMHO the ajax call is not handling the error. Try to edit your code as follow:
$.ajax({
url: "addorderInfo.php", // Url to which the request is sent
type: "POST", // Type of request to be send, called as method
data: new FormData(this), // Data sent to server, a set of key/value pairs (i.e. form fields and values)
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData:false,
success: function(data) {
handleResult(data);
}
error: function(data) {
handleError(data);
}
});
So I am dealing with this weird service when returns a html page as the ajax response which has a form and the form is triggered automatically by some scripts in the page (so when you render the page a post request will be sent to you). What I am trying to do is to load this page I am getting from the response.
Say this is my Ajax call:
var ajax_call_test = function() {
var formData = new FormData($('#documentForm')[0]);
console.log("doc form: " + formData);
$.ajaxSetup({
xhrFields: {
withCredentials: true
}
});
$.ajax("/documents/upload/", {
type: 'POST',
data: formData,
processData: false,
contentType: false,
cache: false,
async: false,
dataType: 'html',
success: function(html){
// ?
},
error: function(jqXHR, textStatus, errorThrown) {
console.log("failed: " + errorThrown);
}
});
}
So I tried to use .html to set the response to a hidden <div>. It sets the html but never triggers the form. I am guessing the javascript in that page is not loaded when I use .html.
I also cannot use jQuery.parseHTML() since the version of library I am using does not support that functionality. Any idea what should I do with response?
When ever you load new html into the DOM. The javascript does not know about it.
I have to re invoke my javascript to work with the new DOM.
Lets say I have some click events
$(function(){invokeClicks()}) // onload call
function invokeSomeAction(){
$("selector").off(); // disable previous events from old html
$("selector").on("event", function(){
// handle event
})
}
function invokeClicks(){
invokeSomeAction();
// ... etc
}
So when this JS loads, the invokeClicks() method gets called.
Now, if I replace the HTML through a $.ajax() call, all I have to do is call invokeClicks() again to clear the old events and now the new HTML will work with the javascript
$.ajax({
url: "somepath",
data: {id: 1},
method: "GET",
success: function(html){
$("container_selector").html(html);
invokeClicks(); // reinit
},
})
$.ajax({
type: "POST",
url: "http://localhost:8080/ChecktToken",
data: {"token": ($.cookie("uid")) },
contentType: "application/json; charset=utf-8",
dataType: "json",
cache: false,
success: function() {
},
error: function(data) {
location.href =('login.html')
},
});
The above Ajax call is used for redirecting the user to the login page if he is trying to access any other pages before actually logging into an application.
This works completely OK, but it takes about 2 seconds to redirect to the login page.
So for example if I try to access http://localhost:8080/index.html prior to logging in I will be able to see that page for 2 seconds before actually being redirected.
Is location.href =('login.html') the best method for redirection or is there something better I could do?
Looking for advices.
2 second delay in redirecting page is due to Ajax call waiting for response from server. These 2 seconds may increase if network of server slows down. To prevent page load you have hide page till you get the response or error. You can do that using beforeSend call back in ajax.
$.ajax({
type: "POST",
url: "http://localhost:8080/ChecktToken",
data: {"token": ($.cookie("uid")) },
contentType: "application/json; charset=utf-8",
dataType: "json",
cache: false,
beforeSend: function() {
//Hide page till you get the response. You can use element Id which holds entire body.
$(body).hide();
},
success: function() {
$(body).show();
},
error: function(data) {
location.href =('login.html')
},
});
I'm getting a unique nonce (i think a timestamp) appended to all and any of my js files every time I send a request to my rails web service:
I'm fairly sure the error has to do with the ajax call, because of jquery.ajax documentation which states cache:true in your ajax request will stop ajax from appending "_={timestamp}" to the get parameters.
I have set cache: true with no luck. How else can I stop these nonces from being applied?
ajax:
$.ajax({
beforeSend: function (xhr) {
xhr.setRequestHeader ('Authorization', api_key);
},
cache: true,
dataType: 'html',
type: 'GET',
url: url+'/gwsearch/ajax_search?d1='+d1_val+'&d2='+d2_val,
crossDomain: true,
success:function(result) {
$("#display").html(result);
},
error: function(result) {
$('#display').html('Unauthorized client.');
}
});
I solved this using an ajax prefilter:
$.ajaxPrefilter('script', function(options) {
options.cache = true;
});
I want to set a cookie value on an AJAX request but the code below doesn't work.
$.ajax({
type: "GET",
url: "http://example.com",
cache: false,
setCookies: "lkfh89asdhjahska7al446dfg5kgfbfgdhfdbfgcvbcbc dfskljvdfhpl",
crossDomain: true,
dataType: 'json',
success: function (data) {
alert(data);
});
How can I set cookies in the header?
Basically, ajax request as well as synchronous request sends your document cookies automatically. So, you need to set your cookie to document, not to request. However, your request is cross-domain, and things became more complicated. Basing on this answer, additionally to set document cookie, you should allow its sending to cross-domain environment:
type: "GET",
url: "http://example.com",
cache: false,
// NO setCookies option available, set cookie to document
//setCookies: "lkfh89asdhjahska7al446dfg5kgfbfgdhfdbfgcvbcbc dfskljvdfhpl",
crossDomain: true,
dataType: 'json',
xhrFields: {
withCredentials: true
},
success: function (data) {
alert(data);
});