Is it normal that the code below is returning "error" when the html-file is not uploaded to my server, and if so: why? It works perfectly once I upload it to my server, though...
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
function validate() {
$.ajax({
type:'POST',
url:'http://www.mywebsite.com/formvalidate.php',
data:{
},
dataType:'json',
success:function (data) {
alert('success');
},
error:function (XMLHttpRequest, textStatus, errorThrown) {
alert('error');
}
});
}
</script>
</head>
<body>
<input type=button onclick="validate();" value="Click me"/>
</body>
The reason is cross domain ajax is not allowed, when you were running this file from your browser or local host, it was hitting a different website url for ajax call, which is not allowed.
But when you uploaded it on the same server, then there were no cross domain issue, so success message
In order to allow the cross domain ajax call you should use JSONP
$.ajax({
url:"testserver.php",
dataType: 'jsonp', // Notice! JSONP <-- P (lowercase)
success:function(json){
// do stuff with json (in this case an array)
alert("Success");
},
error:function(){
alert("Error");
},
});
REFERENCES:- jQuery AJAX cross domain
Javascript isn't cross domnain lang', so you need to be in the same domain, or allow it in the loading page itself using JSONP.
It happens becouse "same site origin policy" you can avoid it if you use jsonp
type on jquery ajax call.
In your case you can, as your are authoring server and client sides.