I have a piece of Javascript I want to run when a form loads. The form handles itself. When the form loads the Javascript works great, but when the form is submitted and the page handles itself the Javascript breaks it.
Is there a way to make the Javascript only run when the form is not being handled?
UPDATE:
I get this error when the form is handled (the Javascript is doing a AJAX request):
TypeError: 'undefined' is not an object XMLHttpRequest cannot load [ajax request url] Origin [original page] is not allowed by Access-Control-Allow-Origin
Here is the HTML:
<form method="#" action="post">
<!--form elements-->
</form>
Here is the Javascript:
ajax.onreadystatechange=function() {
if (ajax.readyState==4 && ajax.status==200) {
document.getElementById("invitestar-message").innerHTML=ajax.responseText;
var signup = document.getElementById("invitestar-content-container");
setTimeout(function(){
body.removeChild(document.getElementById('invitestar-verifying'));
signup.style.display = "block";
}, 500);
}
}
ajax.open("GET","http://nvrforget.com/invitestar/check-invite/?invite=kNdqyJTjcf",true);
ajax.send();
The domain that this javascript is run on is not http://nvrforget.com/
.
This error:
XMLHttpRequest cannot load [ajax request url] Origin [original page] is not allowed by Access-Control-Allow-Origin
is caused because you can't make ajax calls to a different domain than the web page is located on. See this description of the same-origin policy.
JSONP is a way to make cross-origin ajax calls. It requires a cooperating server (to implement the server side of the JSONP) and a method of adding the ajax request as a script tag. Libraries like jQuery or YUI support the client-side parts of JSONP or you can do it yourself (but you still need a cooperating server). Google JSONP if you want to know more about it.