AJAX calls fail in Opera and IE8 - javascript

For some reason, AJAX requests seem to be failing in both Opera 11.51 and IE8 but work in Firefox and Chrome. I am not doing anything fancy other than the standard post request call:
$.post('/dashboard/valid_email/', { email:email }, function(data) {
I've added an alert before and after the AJAX call and I only get one alert which means the callback function isn't called.
I am using jquery.1.6.2 hosted on Google.
Any ideas?

Add an error handler to see what error is being thrown. If you are returning something other than text/html, you need to set the dataType parameter to the proper dataType.
Parse error means that there is something wrong with the data you are returning; if you are returning html, then the html is not valid, and if you are returning json, the json is not well-formed.
$.post(url,data,callback,datatype).fail(function(x,y,z){
alert(x + "\n" + y + "\n" + z);
})

I finally found out what the problem was. I was making use of mouseflow and it was causing problems for some reason on those two browsers! I just removed it and won't be using mouseflow again. I've let the developers know - maybe they can apply a fix.

One error I see: You need to change email to 'email':
$.post('/dashboard/valid_email/', { 'email' : email }, function(data) {
It's not likely your whole problem, but it needs correction.

Related

jQuery ajax request to Flickr sporadically fails

Occasionally, an ajax request to Flickr's api will fail. I'm not sure if I'm doing something wrong here - or if I'm just not handling things correctly - but the code works over 90% of the time. When it doesn't work, I get the following error message from Firefox's console:
TypeError: jQuery19109306644694293944_1362865216185 is not a function
(I am letting jquery generate the callback, which is why the callback is named like that.)
This is the code that sometimes fails:
function getAppropriateSize(photo){
console.log("In getAppropriateSize");
/** stuff. query is defined here **/
$.ajax({
url: 'http://api.flickr.com/services/rest/?method=flickr.photos.getSizes&format=json&api_key='+flickrKey+'&photo_id='+query.id,
dataType:'jsonp',
jsonp:'jsoncallback',
timeout:3000,
success: function(sizes){
console.log("In success - getAppropriateSize");
/**determine the correct size**/
flickrURL = sizes.sizes.size[currVal].source;
},
error: function(xmlhttprequest,textstatus,msg){
console.log("In error - getAppropriateSize");
/* handle error*/
}
});
}
I've checked what's returned when this happens and JSLint says it's valid javascript. flickrURL also gets set to a valid URL. I'm pretty mystified about what's causing this error - any help would be appreciated.
Edit: I was messing around and this time getAppropriateSize just received two separate messages from flickr for one call. The first one was
({stat:"fail", code:1, message:"Photo not found"})
The second one was the a full response from the server that also produced the TypeError mentioned above. However, the second response found the photo and gave me the sizes.

JQuery external Ajax call not working in IE

I have an ajax script that sends some data to an external URL. The external URL is hosted on the same server, however the domain is different than the source of the ajax call.
This is working perfectly in Firefox and Chrome. However in IE The ajax call does not go through, and the Return False function does not either work (once the ajax call fails).
Below is my code:
$.get('http://myexternaldomian.com/feedback/save.php', {
answer: $('#answer').val(),
page_url: pathname
});
// Keeps the user on the page
return false;
When I try removing the http:// from the ajax url, the return false does work.
Any help on this would be greatly appreciated. Thank You
From jQuery documentation
Due to browser security restrictions,
most "Ajax" requests are subject to
the same origin policy; the request
can not successfully retrieve data
from a different domain, subdomain, or
protocol.
and Same Origin Policy on Wiki
I'm surprised any of them are working. Browsers generally don't allow ajax calls to a domain other than the one the current page came from.
The main exception to this rule is if you make an ajax call using jsonp (json with padding). You can do this with jQuery, here's how. Look under the dataType option.
(this is copypaste from my another similar answer). You could try enabling "jQuery.support.cors=true" flag and see how it goes. I use jQuery v1.7.2.
I had to load webpage from local disk "file:///C:/test/htmlpage.html", call "http://localhost/getxml.php" url, and do this in IE8+ and Firefox12+ browsers, use jQuery v1.7.2 lib to minimize boilerplate code. After reading dozens of articles finally figured it out. Here is my summary.
server script (.php, .jsp, ...) must return http response header Access-Control-Allow-Origin: *
before using jQuery ajax set this flag in javascript: jQuery.support.cors = true;
you may set flag once or everytime before using jQuery ajax function
now I can read .xml document in IE and Firefox. Other browsers I did not test.
response document can be plain/text, xml, json or anything else
Here is an example jQuery ajax call with some debug sysouts.
jQuery.support.cors = true;
$.ajax({
url: "http://localhost/getxml.php",
data: { "id":"doc1", "rows":"100" },
type: "GET",
timeout: 30000,
dataType: "text", // "xml", "json"
success: function(data) {
// show text reply as-is (debug)
alert(data);
// show xml field values (debug)
//alert( $(data).find("title").text() );
// loop JSON array (debug)
//var str="";
//$.each(data.items, function(i,item) {
// str += item.title + "\n";
//});
//alert(str);
},
error: function(jqXHR, textStatus, ex) {
alert(textStatus + "," + ex + "," + jqXHR.responseText);
}
});
http://en.wikipedia.org/wiki/Same_origin_policy
I dont think it should work on Chrome or Firefox, unless you testing on localhost or something like that, this would be against the crossdomain policy.
What you need is to proxy it inside the same domain, use php to connect to the destination you need and call the url from the same domain.
save_cross_domain.php -> connect through server to the desired url
then ajax calls save_cross_domain.php
you should add a
callback=?
to your url and handle this on the server side.
I did this once for a java servlet, and when the callback param was included I added an extra pair of parenteses around the json response..
hope it helps!
A couple of things:
The answers/conversation for this question has gone a bit out of context. Actually from the question it was more implied how to make ajax calls in IE. [Atleast modify the question title, else the question is very localized]
A couple of solutions to this cross-domain issue:
CORS[compatible after IE7]
JSONP [ here actually the browser takes in the input thinking it is a script]
server side encoding

Jquery post > success not trigger

I had a problem with jquery's post api.
$(".MGdi").click(function () {
id=$(this).attr("rel")
$.post( 'Mdeger.asp?cmd=MG', { id: id, drm: $(this).html()} ,
function( data ) {
var $response=$(data);
var snc = $response.find('#snc').html();
alert(snc);
},"application/x-www-form-urlencoded");
});
Another way is:
$(".Pasif").click(function () {
id=$(this).attr("rel")
$.post( 'Mdeger.asp?cmd=Pasif', { id: id, drm: $(this).html()} ,
function( data ) {
$(this).html(data);
alert(data)
},"application/x-www-form-urlencoded");
});
Everything is OK on serverside but clientside's success function does nothing.
Even basic codes like alert("hoho"); success not triggering.
this usually happens when respond couldn't be parsed. you should check the respond using firebug or similar debugging tool.
especially the methods that expects json data, strictly validates the respond and if there is anything invalid it just does nothing, no-error, no-warning, no-exception.
when your callback function doesn't run, you should suspect that your respond isn't correct.
// Türkçe özet
uzun lafın kısası dönüş değerinde bir terslik varsa dönüş fonksiyonu çalışmayacaktır. sunucudan gelen değerleri iyice kontrol etmekte fayda var. jquery dönüş değerinde veya dönüş fonksiyonunda bir hata olursa seni uyarmadan işi sonlandırıyor.
I had this problem as well. It turns out I was making an AJAX call to the same domain, but on a different port, which is not allowed (for security reasons) in Javascript.
See this relevant question for more info:
How do I send an AJAX request on a different port with jQuery?
I was very surprised that the AJAX call would POST/GET to the server, (which I was able to verify by looking at the server log) but that the response was never read. I would have thought that both sending and receiving would be disallowed.
I had this error too, and that was a stupid problem : I set dataType to "json" in my JS, but the page called was returning plain HTML. And this cause to not fire the success function at all.

Issue with jQuery $.get in IE

I have a login form which appears at the top of all of my pages when the user is logged out. My current jQuery/javascript code works in Firefox 3 but not IE 7. The code queries a page which simply returns the string "true" or "false" depending on whether the login was successful or not. Inside my $.ready() function call I have the following...
$('#login_form').submit(function() {
var email = $('input#login_email').val();
var pw = $('input#login_password').val()
$.get('/user/login.php', { login_email: email, login_password: pw }, function(data) {
alert('get succeeded');
if(data == 'true') {
$('#login_error').hide();
window.location = '/user/home.php';
alert('true');
}
else {
$('#login_error').show();
alert('false');
}
});
alert('called');
return false;
});
In FF, I am successfully transferred to the intended page. In IE, however, the below alerts "called" and nothing else. When I refresh the page, I can see that I am logged in so the $.get call is clearly going through, but the callback function doesn't seem like its being called (ie. "get succeeded" is not popping up). I also don't appear to be getting any javascript error messages either.
Why isn't this working in IE?
Thanks
EDIT: Since a couple people asked, whenever I enter a correct email/password or an incorrect one, nothing in the callback function happens. If I manually refresh the page after entering a correct one, I am logged in. Otherwise, I am not.
EDIT 2: If I alert out data in the callback function nothing happens in IE (I do not get an alert popup). In FF, it alerts true for valid email/pw combos and false for invalid ones. I am using jQuery 1.3.2.
EDIT 3: Ok, guys, I tried R. Bemrose's thing down there and I'm getting a "parseerror" on the returned data. I'm simply echoing 'true' or 'false' from the other PHP script. I also tried 'yes' and 'no', but that still gave me a parse error. Also, this works in Chrome in addition to FF.
In your response type use:
header("content-type:application/xml;charset=utf-8");
As stupid as this sounds... perhaps IE7 is being anal retentive about the missing semicolon on the var pw line?
Probably not, but the only way I can think of getting more information is to convert it to an $.ajax call in order to add an error hook and see which error type it think is happening. Oh, and to check out the exception object.
$.ajax({
type: 'GET',
url: '/user/login.php',
data: { login_email: email, login_password: pw },
success: function(data) {
alert('get succeeded');
if(data == 'true') {
$('#login_error').hide();
window.location = '/user/home.php';
alert('true');
}
else {
$('#login_error').show();
alert('false');
}
},
error: function(xhr, type, exception) {
alert("Error: " + type);
}
});
If the error type is parse, IE may be complaining because the data coming back has extra commas at the end of comma separated arrays/lists.
IE uses cached data for get requests. Maybe that's your problem? What happens if you try different user id, password?
In any case, isn't it a better idea to send password in POST? :)
I'm am having a similar problem with the following code:
var listOrder = $(this).sortable('toArray').toString();
var otherVariable = whatever
$.get('process_todo.cfm?method=sortToDos', {listOrder:listOrder,otherVariable :otherVariable });
The variable displays through an alert as 'test_123,test_456'. I can hard code the same values and it does not fail. It must have something to do with the 'toArray'? I have been trying to debug this one thing for hours. Works perfectly in Firefox, Safari and Chrome... of course!
Instead of:
if(data == 'true')
try:
if(data)
then in your server just return either a 1 (or true) and a empty value.
What you've posted (at least after Edit 2) looks good. I think the problem is in what you haven't posted.
First, have you checked your server logs to ensure that it's sending back what you presume?
If so, I'd recommend dropping the submit mechanism and using a 'button' type with an 'onclick' handler, and not 'submit' button w/a 'onsubmit' handler...
<input type="button" id="login_submit" value="Login" />
Then switch the submit handler:
$('#login_form').submit(function() { ... });
from the form to the button with:
$('#login_button').click(function() { ... });
If that doesn't help, can you post the HTML for the form, too?
[Edit 3] - try adding the 4th 'type' parameter of "text" to the $.post() call.
Have you used Fiddler to have a good look at what's actually being transferred? (http://www.fiddler2.com)
if you are testing/checking your script in local machine then you will not see any thing in any version of internet explorer because IE on localmachine send datatype as text and not xml and in your case again its matter of datatype not compatible with your document datatype so it worth checking if your datatypes are matching
as far as xml goes solution is here
http://docs.jquery.com/Specifying_the_Data_Type_for_AJAX_Requests
you may check this and find some inspiration :)
salman

Wtf IE7 - AJAX calls using setTimeout

I have tested this on Firefox, Opera and Seamonkey. It works fine. When it comes to Internet Explorer 7. It works but upto a certain point. I am making an AJAX call to a PHP script every few seconds. In IE7 it makes the first AJAX call and it retrieves the data but it doesn't do it again ever. Even though i have a setTimeout function in the else block. WHY? :(
startTime = setTimeout('getStatus()', 5000);
}//function convertNow
function getStatus()
{
$.ajax({
type: "GET",
url: "fileReader.php",
data: 'textFile=' + fileNameTxt,
success: function(respomse){
textFileResponse = respomse.split(" ");
$("#done").html("Downloading & Converting Video...<b style='font-size:17px;color:green;'>" + textFileResponse[0] + "</b><br /><b>" + properFileName + '</b>');
}
});//ajax
if(textFileResponse[0]=='100.0%'){
}
else{
continueTime = setTimeout('getStatus();', 3000);
alert('call end');
}
}
Apologies if any frustration comes through this question. I've been running around like a headless chicken for the past 3 hours.
Thank you for any help.
EDIT 2
I have added the full function. The setTimeout seems to be working correctly. It must be the AJAX call, am just checking what is being returned. Even stranger! It keeps returning the same value from the AJAX request and its not getting any newer values!! I think Answer 2 might have something.It may be due with cache but how do you over come that?
Are you requesting the ajax call via HTTP GET as opposed to HTTP POST? IE tends to use cached results of ajax calls unless you use POST instead of GET.
EDIT: Since you've updated your question, I can see that you are indeed using the GET verb. Change it to POST and I bet your issue will be resolved.
You could still use the GET request and simply add
cache: false
to the $.ajax request.
Not at all sure on this but are you missing the ;?
from:
setTimeout('getStatus()', 3000);
to:
setTimeout('getStatus();', 3000);
I noticed that textFileResponse is set in the function declaration of the success handler for the AJAX call yet referenced as an array immediately after making the AJAX call. Perhaps in IE 7 the success handler hasn't completed before the array reference which would throw a java script error, thus the setTimeout would never run.

Categories

Resources