I have a simple Ajax script that works perfectly fine in Chrome, Internet Explorer 8, Firefox 3.5.5 but fails in Firefox 3.5.7. The code is as follows:
HTML Page:
<div>
<form>
<input id='button' type='button' value='click'>
</form>
</div>
<script>
$(document).ready(function(){
$("#button").click(function(){
$.ajax({
type: "POST",
url: HTTP_HOST+"/ajax/ajax.php",
data: 'source=test',
dataType: 'html',
success: function(data) {alert('success: '+data);},
error: function(XMLHttpRequest, textStatus, errorThrown){alert('fail:\n'+
textStatus+'\n'+
errorThrown+'\n'
);}
});
});
});
</script>
ajax.php page:
$sourcePage = $_POST['source'];
if($sourcePage == 'test'){
echo 'hello';
}
I get the expected response (an alert box saying ‘success: hello’) in the browsers I mentioned above. In Firefox 3.5.7, however, I get the alert box with ‘fail: error undefined’.
Using Firebug‘s Net panel I can see the Ajax calls and they get a response value of 200 OK although it can’t seem to distinguish the size of the response.
There are no other errors according to Firebug.
Based on the apparently successful Ajax call and the undefined size of response, I’m assuming Firefox is having trouble interpreting the response though I’m new to this and have no idea what to try.
How can I solve this problem?
I found what the problem was. Basically what was happening is my HTML page had an address of http://domain.com.au/testPage.php but my Ajax was calling http://www.domain.com.au/ajax.php. There must be some type of security setting that complains when you try to make an Ajax call to a different domain?
So if I access the page as http://www.domain.com.au/testPage.php then it works. Also, if I change the Ajax to call http://domain.com.au/ajax.php without the www, and make the call from http://domain.com.au/testPage.php that also works.
Basically make sure the sub-domain of your page is the same as the sub-domain of the page you’re requesting with Ajax.
This could potentially be a big problem for people who don’t realise this as a lot of hosting packages (like mine) will serve you the same page with or without the www sub-domain by default. As such it is possible for me to access all of my pages with or without the www and not notice a difference (except that Ajax won’t work).
It appears as though the other browsers have the same problem which means that it was a terrible fluke that every time I tested Firefox (on 5 different systems) I somehow ended up trying the URL without the www 🙁
I’ll have to look into finding a way of forcing everyone to use the www sub-domain. I believe http://www.thesitewizard.com/apache/redirect-domain-www-subdomain.shtml#domaintosub is what I’m looking for.