Issue:
I have a Mootools Request object which sends a GET request to a PHP script. The script returns an array of IDs. In every browser except IE each time a new instantiation of the Request object is made it hits the PHP backend script - no problem. BUT with IE it only every hits the PHP script once per browser session. If I clear the cache it flows through to the backend again OK, but after a browser restart or cache refresh.
Question:
Is IE blocking my requests with caching somehow?
If so I there something I can change to prevent IE from blocking the Requests?
Note:
The issue is present on IE9 and on
IE9 in compatibility mode. I have not
tested on older IE versions.
Using
page-wide no-cache is not an option.
I used a error_log() statement in my script to check whether is was getting reached or not.
Here's my code:
requestIDs : function() {
new Request({
url : "/identity/idGenerator.php?generate_ids",
method : "get",
onSuccess : function(response) {
this.container.set('html', '');
var idList = response.split(",");
console.log(idList.join(","));
}.bind(this)
}).send();
}
});
You need to prevent IE from caching the request, here is one solution.
And the right solution which is built in mootools is initializing the Request with the config param noCache:true
var myRequest = new Request({...
...
noCache:true,
...
...);
Use method: 'post' to prevent IE from caching.
Related
I have a problem with fetching JSON data from server in Internet explorer. I am using standard jquery ajax call to the server to retrieve binary data representing file, which is then opened in FlowPaper's PDF viewer. Everything is OK for files of sizes up to 20MB. When I try to get data for files with size 30MB and up, the call comes back as successfull, but data sent to success callback is undefined. This behavior happens in Internet explorer only, but in Chrome or Opera everything works for all file sizes.
JS code is straightforward and simple
var id = "documentID";
var url = 'API/GetDocumentURL';
var data = JSON.stringify({
"DocumentID": id
});
var type = 'POST';
var async = true;
var success = function (data) {
debugger; // in IE data is undefined, other browsers have results stored in this variable
};
$.ajax({
url: url,
type: type,
async: async,
data: data,
success: success
});
Jquery version is 1-8-2, but I have a feeling that this is more a problem of Internet explorer, and not Jquery. Internet explorer version is 11.
Does anyone have any idea why Internet explorer is firing success callback, but not passing in the data retrieved with AJAX call?
Returning the MIMEType of application/json; charset=utf8 caused this same behavior for me in IE8. Changing it to application/json; made IE8 magically start functioning. Check what your server is returning for a MIMEType and see if fiddling with that is causing an issue.
Edit: Actually what was causing the real problem is that it should be charset=utf-8 and not as shown above without the hyphen.
For more infor jquery Ajax response "undefined" with Internet Explorer
I use AngularJS to get data from server. It work well in chrome and firefox if data in server changed. But in IE, It does not show the newest data. I think because IE save data in cache so I send request to server to get new data but IE still shows old data.
How to fix this bug.
Try to use this: https://github.com/saintmac/angular-cache-buster
It adds a query string to the requests like ?timestamp=123456789 to disallow IE to cache it.
Basically if you don't want to use that, you have just to add a different query string to the url requested each time. This prevents IE from caching the request.
IE caches the call, and if you are going to send the same call, then IE will return the cached data.
If you are using $http for your calls, then you can simply add the following code in config function
$httpProvider.defaults.headers.common['Cache-Control'] = 'no-cache, no-store, must-revalidate';
$httpProvider.defaults.headers.common['Pragma'] = 'no-cache';
$httpProvider.defaults.headers.common["If-Modified-Since"] = "0";
However, if you are using jQuery or even $http (another solution), add timestamp in the call along with existing parameters.
jQuery.ajax({
url: "your_url",
data: {
param1 : value1 ,
timestamp : new Date().getTime()
},
success: successCallbackFn
});
I have a problem with an AJAX call in JQuery. It works on Chrome, FF, and Safari, but not IE. In fact in IE nothing happens at all, no errors, no data loaded.
Here is the code:
$(document).ready(function() {
$.ajaxSetup({ cache: false });
$.get("ShoppingCart2.aspx", { }, function(data) {
//query the jq object for the values
alert(data);
alert($(data).find('#Items').text());
var intI = parseInt(($(data).find('#Items').html()));
With the alert data I find all the data from the page I am making a call from, but unfortunately my data.find methods pull up null for IE. I'm not sure if it's the code or the browser, but I am really stuck. Thank you for the help.
Edit: I did add in the cache: false command, but still I have no luck. I really cannot understand why this won't work in IE.
Try this (once in your page/external js, before your AJAX calls):
$.ajaxSetup({ cache: false });
IE likes to cache the hell out of things, and if you were testing and had no content there at one point, chances are IE is holding onto it. Using $.ajaxSetup() and and telling it by default to not cache AJAX results should resolve this. If you're curious, it's sticking a timestamp on the URL as a cache breaker under the covers, use fiddler to see this happening.
Is it perhaps caching the AJAX? What happens if you put this before your code:
$.ajaxSetup({ cache:false });
A quick solution without coding it could be to press CTR+F5 to clear the cache upon refresh.
Well I was unable to make the .find part of the .get work in internet explorer, but I did find a way to get the ajax information I needed:
var information = $.ajax({ type: "GET", dataType: "html", url: "ShoppingCart2.aspx", data: querystring, async: false }).responseText + " ";
This passes a query string to the website then gets information from the website back into one big string. I then
manipulated that string to get what I needed. Unfortunately it is a lot slower than the .get command, but it is a fix.
Thanks for the help everyone!
I'm working on a firefox extension and have been developing it in Firefox 3, I went to test it on Firefox 2 and for some reason, none of my HTTP requests is firing. The format of the requests are below (using prototype):
theResponse = function(response){
//some code
}
new Ajax.Request(url,{
method:'get',
parameters : {url: currentURL},
onSuccess: theResponse,
onFailure: function(){ alert('Something went wrong...') }
});
I have been trying to find a solution but the closest thing I've found is something to do with cross-site HTTPrequests, anyone has any ideas?
Figured out the problem was to do with the way prototype performs HTTPrequests, switched to using jquery and no further problems ... well with HTTPrequests anyway.
I prefer to use jQuery with my ASP.NET MVC apps than the Microsoft Ajax library. I have been adding a parameter called "mode" to my actions, which I set in my ajax calls. If it is provided, I return a JsonViewResult. If it isn't supplied, I assume it was a standard Http post and I return a ViewResult.
I'd like to be able to use something similar to the IsMvcAjaxRequest in my controllers when using jQuery so I could eliminate the extra parameter in my Actions.
Is there anything out there that would provide this capability within my controllers or some simple way to accomplish it? I don't want to go crazy writing code since adding a single parameter works, it just isn't ideal.
Here's an except from MVC RC1 release notes - Jan 2009
IsMvcAjaxRequest Renamed to IsAjaxRequest
The IsMvcAjaxRequest method been
renamed to IsAjaxRequest. As part of
this change, the IsAjaxRequest method
was updated to recognize the
X-Requested-With HTTP header. This is
a well known header sent by the major
JavaScript libraries such as
Prototype.js, jQuery, and Dojo.
The ASP.NET AJAX helpers were updated to send this header in
requests. However, they continue to
also send it in the body of the form
post in order to work around the issue
of firewalls that strip unknown
headers.
In other words - it was specifically renamed to be more 'compatible' with other libraries.
In addition, for anyone who hasnt read the full release notes but has been using previous versions - even as recent as the beta - I STRONGLY recommend you read them in full. It will save you time in future and most likely excite you with some of the new features. Its quite surprising how much new stuff is in there.
Important note: You will need to make sure you upgrade the .js file for MicrosoftAjax.MVC (not the exact name) if upgrading to RC1 from the Beta - otherwise this method won't work. It isn't listed in the release notes as a required task for upgrading so don't forget to.
See Simons answer below. The method I describe here is no longer needed in the latest version of ASP.NET MVC.
The way the IsMvcAjaxRequest extension method currently works is that it checks Request["__MVCASYNCPOST"] == "true", and it only works when the method is a HTTP POST request.
If you are making HTTP POST requests throug jQuery you could dynamically insert the __MVCASYNCPOST value into your request and then you could take advantage of the IsMvcAjaxRequest extension method.
Here is a link to the source of the IsMvcAjaxRequest extension method for your convenience.
Alternatively, you could create a clone of the IsMvcAjaxRequest extension method called
IsjQueryAjaxRequest that checks Request["__JQUERYASYNCPOST"] == "true" and you could dynamically insert that value into the HTTP POST.
Update
I decided to go ahead and give this a shot here is what I came up with.
Extension Method
public static class HttpRequestBaseExtensions
{
public static bool IsjQueryAjaxRequest(this HttpRequestBase request)
{
if (request == null)
throw new ArgumentNullException("request");
return request["__JQUERYASYNCPOST"] == "true";
}
}
Checking from an action if a method is a jQuery $.ajax() request:
if (Request.IsjQueryAjaxRequest())
//some code here
JavaScript
$('form input[type=submit]').click(function(evt) {
//intercept submit button and use AJAX instead
evt.preventDefault();
$.ajax(
{
type: "POST",
url: "<%= Url.Action("Create") %>",
dataType: "json",
data: { "__JQUERYASYNCPOST": "true" },
success: function(data) {alert(':)');},
error: function(res, textStatus, errorThrown) {alert(':(');}
}
);
});
Why don't you simply check the "X-Requested-With" HTTP header sent automatically by most Javascript libraries (like jQuery) ?
It has the value 'XMLHttpRequest' when a GET or POST request is sent.
In order to test it you should just need to check the "Request.Headers" NameValueCollection in your action, that is :
if (Request.Headers["X-Requested-With"] == "XMLHttpRequest")
return Json(...);
else
return View();
This way, you can simply differentiate regular browser requests from Ajax requests.
Ok, I have taken this one step farther and modified my jQuery file to load the additional parameter into the post data, so I don't have to repeat the "__JQUERYASYNCPOST: true" for every call to post. For anybody that's interested, here's what my new definition for $.post looks like:
post: function(url, data, callback, type) {
var postIdentifier = {};
if (jQuery.isFunction(data)) {
callback = data;
data = {};
}
else {
postIdentifier = { __JQUERYASYNCPOST: true };
jQuery.extend(data, postIdentifier);
}
return jQuery.ajax({
type: "POST",
url: url,
data: data,
success: callback,
dataType: type
});
}
I added the "postIdentifier" variable as well as the call to jQuery.extend. Now the Helper explained in spoon16's response works without having to add any thing special to my page-level jQuery code.