IE11 JQuery ajax caching even with cache:false - javascript

I've tried everything I know and everything I've found to prevent IE (Edge!) from caching:
cache:false within the ajax params
add (manually) a timestamp in the call
set ajaxSetup
change request method from GET to POST
return a header inside the AJAX page that was called
I'm not using C# in order to use the param mentioned in some posts (I'm using coldfusion). Does someone know another method in order to fix that IE "feature"?
Here's the AJAX code in case you don't trust in me (like Dr. House says: everybody lies) or I'm skipping something:
$('a#showLista').click(function(event){
event.preventDefault();
$.ajax({
url: 'cfc/carrito.cfc?' + (new Date()).getTime() + '&method=preciosListaFav',
cache: false,
countentType: "application/json; charset=utf-8",
dataType: "json",
type: 'POST',
data: {
DataSource: DataSource,
IDCliente: clienteID,
IDUsuario: IDUsuario,
Sesion: Sesion
},
success: function(datos) {
i = datos.DATA.length;
if (i > 0) {
// Insert data into table
} else
// Alert empty list
}
});
});

Related

In Ajax response my if condition is not working

Check the jquery code bellow. Here after process post request the response returning no_file_found but if condition not meeting and not hitting alert(). Whats wrong i am doing here?
$("#btnFoo").on("click", function () {
var file_data = $('#formUploadImg').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
form_data.append('ProId', $(this).attr("img-upload-product-id"));
$.ajax({
url: '/mycontroller/upload',
dataType: 'text',
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function (response) {
console.log(typeof response);//it returns string
if (response == "no_file_found") {
alert("this not hits");//this alert not hits
}
},
error: function (response) {
alert("Error");
}
});
});
Please note i am using c# mvc5 and the response is comming from mvc5 controller. Mvc5 example bellow:
[HttpPost]
public JsonResult upload()
{
return Json("no_file_found");
}
You need to use .trim() function to make sure all unseen spaces are removed from the response to be able to match the exact comparison== of no_file_found.
Edit: The reason it is not working is because you are returning "no_file_found" with double quotes "" added. But on the front end you are checking simply no_file_found - You need to use replace function to make sure all the double quotes are deleted from the response.
var response = '"no_file_found"';
if (response.replace(/["']/g, "").trim() == "no_file_found") {
alert("this hits"); //this alert hits
}
The problem here is that you are returning a Json value - but your ajax is set to have a dataType: 'text'.
If you change dataType: 'json' all works as expeceted.

Lock state multiple ajax calls

I have multiple rich text editors on single page.
There is autosaving of both done by ajax calls that are separate.
Each text editor is saved on focus lost or when focus is inside of editor every 20 seconds.
When editor is not saved and user navigates away I am showing "navigate away warning".
Now I need to manage warning that when one editor is in the middle of saving and the other one finishes earlier warning will not be removed.
What I have now:
editorOneIsSaving=true;
SetNavigateAwayNotification();
$.ajax({ type: "POST", contentType: "application/json",
dataType: 'json', url: "/SaveEditorOne",
data: mypostdata1,
success: function (msg) {
editorOneIsSaving = false;
if (!editorTwoIsSaving) {
RemoveNavigatingAwayNotification();
}
updateSavedInfo();
},
});
For second editor:
editroTwoIsSaving=true;
SetNavigateAwayNotification();
$.ajax({ type: "POST", contentType: "application/json",
dataType: 'json', url: "/SaveEditorTwo",
data: mypostdata2,
success: function (msg) {
editorTwoIsSaving = false;
if (!editorOneIsSaving) {
RemoveNavigatingAwayNotification();
}
updateSavedInfo();
}
});
I was looking into adding object to array or list but it is not really nice in javascript. This way I would know who is the owner of lock or if there would be more editors I could make sure that same editor is not taking lock multiple times.
Maybe I am just overthinking and I should go with simply counter which if is 0 then remove navigate away.
One way to do this would be to add a counter to each ajax call to save.
You increment the counter before sending the data to the server and decrement it in the promise.
something like the following
function showSavingMessage(){
//code to show message
}
function removeSavingMessage(){
// code to remove message
}
var ctr = 0;
function saveData(){
showSavingMessage();
ctr++;
$.ajax({ type: "POST", contentType: "application/json",
dataType: 'json', url: "/SaveEditorXXX",
data: mypostdata2,
success: function (msg) {
if (ctr > 0){
ctr--;
} else {
removeSavingMessage();
}
}
});
}
You can handle errors any way you like. may be change the "saving" message to error message.
You can also pass the url and the data to the saveData function to make it reusable, so you have a single function with the Ajax code.

Ajax jquery making web api call

I made an api in java , which allows the user to get data.
there is an call : ..../api/users where i give a list back of all users avalible.
Now i got a site with a search user button, wen you press that button i want to make a call to /api/users with the help of Ajax.
i got the part that you can click on the search button, but i don't understand how to make that call with ajax
This is my code:
$.ajax({
url: ”api / resource / users ",
dataType: "json”,
}
).fail(
funcNon(jqXHR, textStatus) {
alert("APIRequestfailed: " + textStatus);
}
).done(
funcNon(data) {
alert("succes!")
}
);
Is this the way of making a good call with ajax ?
or do i have to use :
http://localhost/projectUser/api/resource/users ?
Assuming you are using JQuery to make the Ajax call then this sample code should be helpful to you. What it does is;
On search button was clicked
Do AJAX call to fetch stuff from your Java REST API
When the expected JSON object was returned, parse it and do something
O
$(document).ready(function() {
$('#demoSearchBtn').click(function () {
// Search button was clicked!
$.ajax({
type: "GET",
url: "http://localhost/projectUser/api/resource/users", // edit this URL to point into the URL of your API
contentType: 'application/json; charset=utf-8',
dataType: "json",
success: function (data) {
var jsonObj = $.parseJSON(data);
// Do something with your JSON return object
},
error: function (xhr) {
alert('oops something went wrong! Error:' + JSON.stringify(xhr));
}
});
});
}
if this http://localhost/projectUser/api/resource/users is the url, it's either
$.ajax({
url: ”api/resource/users", ...
or
$.ajax({
url: ”http://localhost/projectUser/api/resource/users", ...
depending on what the browsers current URL is (relative or absoute depends on context of the browser).
but it is never ever ”api / resource / users " with spaces between words and slashes.

Remove short delay or lag upon clicking button

Is there a way to remove the short delay or lag when i click the button? It seems like nothing is happening then after some seconds only when it loads. This is my code:
$('#save-btn').bind('click',function(){
$.ajax({
cache: false,
url: url,
type: 'POST',
async: false,
data : {data:models},
success: function(result){
window.location = url2;
}
});
});
Thanks.
You are waiting until the ajax call returns to redirect to the new url, so those seconds are the response time of your server. If it's taking too long to response, it could be that you are returning too much data (ie a full page instead of a json response for example), or you're doing a very complex operation. Odds are it's just the server being slow.
If save-btn is an <input type="submit"> button, use the following code to change its val() .
$('#save-btn').bind('click',function(){
$(this).val('loading...');
$.ajax({
cache: false,
url: url,
type: 'POST',
async: false,
data : {data:models},
success: function(result){
window.location = url2;
}
});
});

AJAX jQuery Freezing IE/Safari

At my wits end here.
Im running this script
<script type="text/javascript" charset="utf-8">
jQuery(window).ready(function(){
//alert('running');
var sold = false;
var leads = [
["one", 120],
["two", 0]
];
jQuery.each(leads, function(index, value) {
var _data = "";
jQuery.ajax({
url: "/wp-content/plugins/cUrl/submit_lead.php?lead=" + value[0],
dataType: "json",
//contentType: "application/json; charset=utf-8",
timeout: value[1] * 1000, //Yes i need to wait 120 seconds for "one"
async: false,
cache: false
}).success(function(data) {
_data = data;
console.log(data.status + " Lead: "+ value[0]);
if (data.status == "sold") {
sold = true;
jQuery.ajax({
url: "/wp-content/plugins/cUrl/submit_lead.php?resetSession",
dataType: "json",
//contentType: "application/json; charset=utf-8",
async: false,
cache: false
}).success(function() {
//Silence is golden.
});
window.location.href = data.link;
}
}).error(function(jqXHR, textStatus){
console.log("ERROR: " + textStatus + " Lead: " + value[0]);
});
if (_data.status == "sold") {
return false;
}
});
if (!sold) {
//If we get here, None of the leads were sold.
jQuery.ajax({
url: "/wp-content/plugins/cUrl/submit_lead.php?resetSession",
//contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
cache: false
}).success(function(data) {
//Silence is golden.
});
window.location.href = '/thank-you.php';
}
});
</script>
The script takes some info submits it to submit_lead.php which will return a json response with a status, a message and a link. Once it has this link it needs to call the same script with ?resetSession and the redirect the user to the link received.
I have a sync turned off because I need to wait until I get a response from "one" before trying "two", because if I receive a link there's no point trying the next one.
When the script runs on FF or Chrome, it runs fine. There is a little animation that plays while the requests are going through and once a link is returned it redirects accordingly.
When the script runs in <= IE8 or Safari, the page sorta loads half then waits (The animation loads but does not animate.). Once the ajax response has returned the page suddenly springs to life and then you get redirected.
I have tried window ready and document ready and nothing seems to work.
Any suggestions would be appreciated.
Thanks for reading.
Like i said in the comments, turn async back on.
Add your redirect or whatever operations you want to perform in the callback from the ajax function. Thats most likely the reason you are getting locking.

Categories

Resources