Jquery ajax() call fails in IE8 - javascript

I have the following code for submitting data using ajax from forms of class ajax. this works perfectly in Firefox, Safari and Chrome but fails in IE.
ajax: function() {
$('form.ajax').live('submit', function() {
var form_ajax = $(this);
$.ajax({
url: form_ajax.attr('action'),
data: form_ajax.serialize(),
type: form_ajax.attr('method'),
dataType: 'script',
beforeSend: function(xhr) {
$('#ajax-bid-new .ajax-form-error, #ajax-bid-new .ajax-form-success').remove();
form_ajax.slideUp();
}
});
return false;
});
Please help - I am stuck here for past 2 days. I am returning a Javascript file from server to be evaluated inside browser. This works as expected in Firefox, Chrome and Safari, but IE receives it as a file and opens up the file download dialog.
What can I do in IE to make this work? I tried by dropping the following code in my application.js file (I'm doing a rails project btw)
// public/javascripts/application.js
jQuery.ajaxSetup({
'beforeSend': function(xhr) {xhr.setRequestHeader("Accept", "text/javascript")}
})
I get the same behavior from IE even after writing the ajaxSetup block like above.

Looks like live doesn't work with submit in IE. Have you tried using a normal submit instead:
$('form.ajax').submit(function() {

To catch live form submit events in IE, instead of:
$("form").live("submit", function() { ... });
to
var submitHandler = function() { ... };
$("body").children().each(function() {
$("form", this).live("submit", submitHandler);
})
Point to be noted
IE caches AJAX requests really aggressively (more so than Firefox, anyway). You need to set the Cache-Control headers in the response appropriately if this is not right for your site.
change your content type, last time i fixed similar problem by changing content-type from application/json; charset=utf8 to just plain application/json
jQueries' bind and live behaviours along with the liveQuery plugin

LiveQuery plugin solved the problem http://github.com/brandonaaron/livequery

Related

Jquery Ajax Request return forbidden (403) in cakePHP project

EDIT 2
I still need help, as the error still isn't fixed.
Below I have added a link to a screenshot of what .ajaxError() does throw:
http://i.imgur.com/RkcgNtG.jpg
Another thought was the server setting. Is there any chance that suphp or the mpm_itk module are the cause for this bug?
EDIT
I have figured out something. My Ajax-Call should update some data from an input and a textarea. I tested some more and saw that the 403 only occurs when the value of my textarea or the value of my input has more than one whitespace ... So 'that-is-a-test' and 'thatisatest' work fine, but 'that is a text' returns a 403.
I also want to add that the Ajax-Call is done with a get-method.
Original
I've got a problem working on my cakePHP project.
First of all I have to say that I am new to cakePHP and that I work on a project that was not developed by me initially.
I have set up this project on my localhost (Windows 8 with xampp) and everything works fine.
In a next step I edited the Bootstrap-Configuration file, corrected the database information and uploaded all files to my server.
Now everything still works, except for the jQuery AjaxCalls. Tracing the root of this error I saw that the server returns an 403 Status Code.
Now I searched for possible reasons. First aspect I found was to set the security-level from high to medium. But as my 2.x project does not have this setting anymore, I need another solution.
Next step was to check the server settings. But the phpinfo of both, my local version and the server where the error takes place, seem to be nearly the same.
Only the PHP version of 5.3 on the server and the use of FastCGi are different.
But as cakePHP do not need more than 5.2 that cannot be the reason.
So now I have no idea what to search for. I think it has to be one setting because it works fine on my localhost, worked fine on another server but fails on the new server.
Any ideas I could check? As I am not an expert of server technologies it would be great if you answer as detailed as possible.
thanks and greets
I have now changed my jQuery Ajax-Call that looks like following
$.ajax({
url: '/metas/saveMetas',
data: {
"model": model,
"f_key": f_key,
"pagetitle": pagetitle,
"keywords": keywords,
"description": description,
"niceurl": niceurl
},
dataType: 'json',
complete: function(){
return false;
},
success: function(result) {
if(typeof result =='object') {
$('#modal-spinner-seo-update').hide('slow');
jQuery.each(result, function(field, message) {
$('#seo-'+field).next('div.error-message').html(message).fadeIn('fast');
});
} else {
$('#modal-spinner-seo-update').hide('slow', function() {
$("#seo-widget-message-success").fadeIn('slow').delay(2000).fadeOut('slow');
});
}
return false;
}
});
into a simple JavaScript xmlHttpRequest as following
xhr = new XMLHttpRequest();
xhr.onreadystatechange=function()
{
if (xhr.readyState==4 && xhr.status==200)
{
console.log(xhr.responseText);
if(typeof xhr.responseText =='object') {
$('#modal-spinner-seo-update').hide('slow');
jQuery.each(result, function(field, message) {
$('#seo-'+field).next('div.error-message').html(message).fadeIn('fast');
});
} else {
$('#modal-spinner-seo-update').hide('slow', function() {
$("#seo-widget-message-success").fadeIn('slow').delay(2000).fadeOut('slow');
});
}
return false;
}
};
xhr.open('GET','/metas/saveMetas?model='+model+'&f_key='+f_key+'&pagetitle='+pagetitle+'&keywords='+keywords+'&description='+description+'&niceurl='+niceurl, true );
xhr.send();
and now everything seems to work fine. But I still do not understand why. Can anyone explain what I did wrong?

$.ajax async:false doesn't work in IE and Firefox, works in Chrome/Safari

I am trying to measure download speed with ajax call.
Here is the my code
var start = new Date();
$.ajax ({
url: 'https://www.example.com/perftest/dummyFile1024',
cache: false,
success : function() {
var total = (new Date() - start)
alert(total)
},
error : function(jqxhr, status, ex) {}
})
It doesn't wait until whole file loaded. When I add async: false, it waits for loading whole file and I am able to measure bandwidth at chrome and safari however internet explorer and firefox still works the same as async: true, they don't wait until whole file loaded. Do you have any idea how I can manage it works for I.E. and firefox as well? Thanks.
IE 8/9 cross domain requests require jQuery to use a different transport method which uses a XDomainRequest instead of the default XmlHttpRequest.
I believe the question has been answered already here: [question]: CORS with jQuery and XDomainRequest in IE8/9
For FireFox try setting the "dataType" of the content returned by the $.ajax request.

JSON - Not working in Internet Explorer 8

I tried few thing to fix, Nothing helped.
in server side script,
$array['content'] = "test";
echo json_encode($array);
This is working in javascript. But
$array['content'] = "<p>test</p>";
echo json_encode($array);
Not working. If i add any html tag, it is not working.
But they all are working in firefox and chrome.
This is the js handling the return value.
function showResponse(responseText) {
$('.form_result').html(responseText.formData);
alert(responseText.formData);
}
function submitButton1() {
var options = {
beforeSubmit: showRequest, // pre-submit callback
success: showResponse, // post-submit callback
dataType: 'json',
cache: false
};
// bind form using 'ajaxForm'
$('#form').ajaxSubmit(options);
}
header("Cache-Control: no-cache, must-revalidate");
header("Expires: 0");
Added the above two lines in php file.
<meta http-equiv="X-UA-Compatible" content="IE=8" />
Added the above in html file which handling the js. Still no use.
What could be the problem?
additionally, i dont see any error or warning in IE.
Internet Explorer 8 doesn't support CORS in the XMLHttpRequest object which jQuery is using
ie8 uses XDomainRequest object
jQuery doesn't support XDomainRequest by default.
check this An update is available for the native JSON feature in Internet Explorer 8
i don't know what's the problem, but if disable enctype="multipart/form-data" all works fine.
I guess it's ajax form plugin problem.
I haven't tried this, but if you search for XMLHttpRequest object existing, and it doesn't, then implement your own ajax call.
Also check if JSON exists, and if doesn't then include json.js from just download it from the github and dynamically add it.

Access denied to jQuery script on IE

I have an iframe using the jQuery 1.4.2 script. The same iframe is injected into both http and https sites. The jQuery script is included in the main HTML file as a relative path (e.g., /scripts/jquery-1.4.2.min.js).
When an AJAX call is made, Internet Explorer denies access. The AJAX is calling on another subdomain, but it's using the right protocol. All other browsers work but Internet Explorer gives the following error:
SCRIPT5: Access is denied.
jquery-1.4.2.min.js, line 127 character 344
I heard this error is from cross-domain AJAX calls. But why is IE the only one giving me crap? Is there an IE solution?
Also, this is my AJAX:
$.ajax({
url: thisURL,
dataType: "json",
data: {cmd : 'getMessage', uurl: urlVar, t: Math.random()},
success: function(ret){
callback(ret)
}
});
IE requires you to use XDomainRequest instead of XHR for cross site, you can try something like...
if ($.browser.msie && window.XDomainRequest) {
// Use Microsoft XDR
var xdr = new XDomainRequest();
xdr.open("get", url);
xdr.onload = function() {
// XDomainRequest doesn't provide responseXml, so if you need it:
var dom = new ActiveXObject("Microsoft.XMLDOM");
dom.async = false;
dom.loadXML(xdr.responseText);
};
xdr.send();
} else {
// your ajax request here
$$.ajax({
url: thisURL,
dataType: "json",
data: {cmd : 'getMessage', uurl: urlVar, t: Math.random()},
success: function(ret){
callback(ret)
}
});
}
Reference
http://forum.jquery.com/topic/cross-domain-ajax-and-ie
not sure whether it fits your scenario
xdr = new XDomainRequest();
xdr.onload=function()
{
alert(xdr.responseText);
}
xdr.open("GET", thisUrl); //thisURl ->your cross domain request URL
//pass your data here
xdr.send([data]);
you can find some more guidance here
This solved the issue gracefully for me:
https://github.com/MoonScript/jQuery-ajaxTransport-XDomainRequest
Just install/compile after jQuery and before your script and use the $.ajax method as you normally would, the rest is handled behind the automatically.
Have you try to use the lastest of JQuery(> jquery-1.8.0)? Since the version 1.8.0, they solved some IE9's bugs. Perhaps this one too.
http://blog.jquery.com/2012/08/30/jquery-1-8-1-released/
I had a similar problem and the solution for me was to use jsonp instead of json. That way I didn't have to break out a customer version for IE.
You can only do this if the json server host supports the callback request variable or you have access to the server and can add support. Here is a page that helped me understand the process. Its .net mvc focused, but it gives a good over view of the diffrence between json and jsonp.
http://blogorama.nerdworks.in/entry-EnablingJSONPcallsonASPNETMVC.aspx
Check the domain you are accessing, following response headers should be there
"Access-Control-Allow-Methods" : "POST, GET, OPTIONS"
"Access-Control-Allow-Origin" : "http://www.mydomain.com" or "*"
the other domain should allow your script request. One more header to be added to your response is P3P header.
"p3p" : "CP=IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT"
it should help you out.
I was facing similar issue.
I was using file upload control but it was hidden and I had another element trying to control the file upload and events to upload file in ajax way
try using the file upload control directly. this solved issue in my application.
I get this bug (and thus google here) but the reason was very different. So if you don't have cross site and still get this access denied error: double check the value sent
let's say that you affect one of you variable with the bad following expression:
urlVar = $("theID").val // without () this was the error!
[...]ajax call:
data: {cmd : 'getMessage', uurl: urlVar, t: Math.random()},
Google/FF have no problem with this (check what is receive server side...) BUT IE refuse to send this!
I changed my JQuery from version 1.10.1 to 1.10.2 and it seems to have solved this problem for me.
It seems that MS is finding its own way of doing things, rather than adopting industry recommendations. I found the solution here:
https://github.com/MoonScript/jQuery-ajaxTransport-XDomainRequest/blob/master/jQuery.XDomainRequest.js
Simply add 'callback=?' on your ajax URL request like here:
http://wsvdmeer.blogspot.com.es/2012/08/bugfix-getjson-not-working-in-ie.html

Load Recaptcha script with Prototype

I need to load the Recaptcha library on demand, with javascript (using Prototype):
var captcha = new Element('script', { type: 'text/javascript', src: 'http://api.recaptcha.net/js/recaptcha_ajax.js' });
$$('head')[0].appendChild(captcha);
captcha.onload = function()
{
Recaptcha.create("dsfahsldkjfhlasdjfc","recaptcha_image", {theme: "custom"});
};
The problem here is with IE, of course. It seems that the captcha.onload wont work in IE. As usual, it works on other browsers.
So, how can I check that the script is loaded on IE, and call Recaptcha.create afterwards?
Is there an easier and cross-browser way of loading and evaluating external scripts with Prototype?
Thanks.
Looks like IE doesn't support onload, but DOES support onreadystatechange:
Sample code for onreadystatechange:
http://gist.github.com/461797
Post with some info, source of above link:
http://blog.andrewcantino.com/post/211671748/replacement-for-script-onload-in-ie

Categories

Resources