"Object doesn't support..." IE8 stops at declaring ordinary variable - javascript

I'm trying to make a form send its data through AJAX and cancel the event sans jQuery, just for learning native JavaScript, which can never be bad, I figured. Anyway, this code is returning the error:
"Object doesn't support this property or method"
in IE8 at the line where I declare variables s and r in the send() function. I figured the problem must actually be elsewhere? Code works in both Firefox and Chrome, returning no errors. Ideas?
// Function to serialize form
function serialize() {
var a = document.getElementsByTagName('input'), b = '';
for (i = 0; i < a.length; i++) {
b += a[i].name + '=' + a[i].value + '&';
}
return b.substring(0, b.length - 1);
}
// Function to execute when user submits form
function send(evt) {
// Prevent the page from reloading
if (evt.preventDefault) {
evt.preventDefault();
} else {
evt.returnValue = false;
}
// Declare DOM variables for quick access
var s = document.getElementsByClassName('skicka')[0], r = document.getElementById('return');
// Hides the submit button and return text
s.style.visibility = 'hidden';
r.style.visibility = 'hidden';
// Initialize and send data and request to login.php
var xhr = new XMLHttpRequest();
xhr.open('POST', 'login.php', true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send(serialize());
// Check for return value from login.php
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if (xhr.responseText == true) {
// If response if true, reload page
window.location.reload(true);
} else {
// If response is false, reset form and show response
s.style.visibility = 'visible';
r.style.visibility = 'visible';
r.innerHTML = xhr.responseText;
}
}
};
return false;
}
// Declare event listeners
if (window.addEventListener) {
window.addEventListener('load', function() {
document.forms[0].addEventListener('submit', send, false);
}, false);
} else {
window.attachEvent('onload', function() {
document.forms[0].attachEvent('onsubmit', function() {
send(window.event);
});
});
}

IE8 does not support .getElementsByClassName(). See the Ultimate GetElementsByClassName for a pure JavaScript implementation that will work in IE.

Related

Object doesn't support property or method 'stop' IE

When i click on submit button. I got an error like "Object doesn't support property or method stop " in Internet Explorer but data is successfully added in database.
Here is my code.
function SaveComment(subCommentId, trShowresponseId, tdShowresponseId, startDate, endDate) {
// alert("");
debugger;
try {
var response = document.getElementById("TextBoxResponse~" + subCommentId).value;
if (response === "") {
alert("Please Enter Response.");
return false;
}
else {
// var isAdvanceComment = 1;
$("#showloading").show();
var commentType = 'A';
var returnReult = dashboards_DiscreteRating.SaveComment(response, subCommentId, commentType, startDate, endDate, 0).value;
if (returnReult.match("Error")) {
document.getElementById("spanErrorMessage").innerHTML = returnResponse;
}
else {
document.getElementById(tdShowresponseId).innerHTML = returnReult;
}
// document.getElementById(tdShowresponseId).innerHTML = dashboards_DiscreteRating.SaveComment(response, subCommentId, commentType, 0).value;
document.getElementById("trHiddenTextBox~" + subCommentId).className = "hide";
document.getElementById("trAddSpan~" + subCommentId).className = "show";
document.getElementById("TextBoxResponse~" + subCommentId).value = "";
document.getElementById(trShowresponseId).className = "show";
$("#showloading").hide();
window.stop();
}
}
catch (ex) {
alert(ex.description);
}}
Instead of using window.stop(), return false or call preventDefault on the event object in the form’s submit listener – likely wherever you call SaveComment. Something along the lines of:
commentForm.addEventListener('submit', function (e) {
// …
SaveComment(…);
e.preventDefault();
});
The alert here suggests you might already be passing the return value straight through:
alert("Please Enter Response.");
return false;
in which case you should be able to do it here too:
$("#showloading").hide();
return false;
See https://developer.mozilla.org/en-US/docs/Web/API/Window/stop
The stop() method is not supported by Internet Explorer.
Also: I don't know what you are trying to achieve by calling stop().
However: you call window.stop(); as the last line in your file. Since you don't rollback in your catch-block or anything, everything before that call (e.g. writing to database) gets executed and not rolled back
Finally i solved this error by using this .
function SaveComment(subCommentId, trShowresponseId, tdShowresponseId, startDate, endDate) {
// alert("");
debugger;
try {
var response = document.getElementById("TextBoxResponse~" + subCommentId).value;
if (response === "") {
alert("Please Enter Response.");
return false;
}
else {
// var isAdvanceComment = 1;
$("#showloading").show();
var commentType = 'A';
var returnReult = dashboards_DiscreteRating.SaveComment(response, subCommentId, commentType, startDate, endDate, 0).value;
if (returnReult.match("Error")) {
document.getElementById("spanErrorMessage").innerHTML = returnResponse;
}
else {
document.getElementById(tdShowresponseId).innerHTML = returnReult;
}
// document.getElementById(tdShowresponseId).innerHTML = dashboards_DiscreteRating.SaveComment(response, subCommentId, commentType, 0).value;
document.getElementById("trHiddenTextBox~" + subCommentId).className = "hide";
document.getElementById("trAddSpan~" + subCommentId).className = "show";
document.getElementById("TextBoxResponse~" + subCommentId).value = "";
document.getElementById(trShowresponseId).className = "show";
$("#showloading").hide();
if ($.browser.msie) { //************** Here is the answer ************
document.execCommand('Stop'); //************** Here is the answer ***********
}
else {
window.stop();
}
}
}
catch (ex) {
alert(ex.description);
}}
Internet Explorer does not support window.stop() so we can use document.execCommand("Stop") for IE.

Javascript 404 check on anchor tag click

I need to implement javascript only solution that would override default a href behavior, check if href location exist and then redirect to it or to 404.html. So far I come up with this:
function UrlExists(url)
{
var http = new XMLHttpRequest();
http.open('HEAD', url, false);
http.send();
return http.status!=404;
}
document.onreadystatechange = function()
{
var anchorElements = document.getElementsByTagName('a');
for (var i in anchorElements)
anchorElements[i].onclick = function()
{
if (UrlExists(this.href)) {window.location=this.href; }
else {window.location='404.html'=;}
return false;
}
}
However, if UrlExists() gets called, default behavior is not overridden. Any ideas?
EDIT: 404 check works, and all links are on same domain
Also non jQuery solution is preferred.
//UrlExists function was copied from Trip and jAndy
Thanks to RobM. and Script47 for pointing out that preventDefault is native function:
function UrlExists(url)
{
var http = new XMLHttpRequest();
http.open('HEAD', url, false);
http.send();
return http.status!=404;
}
document.onreadystatechange = function()
{
var anchorElements = document.getElementsByTagName('a');
for (var i in anchorElements)
anchorElements[i].onclick = function(th)
{
th.preventDefault();
if (UrlExists(this.href)) { window.location=this.href; }
else {window.location='404.html';}
return false;
}
}

Adding a second submit handler

I am trying to modify an existing web page which looks like this
<script type="text/javascript" src="s1.js"></script>
s1.js has something like this
window.onDomReady = DomReady;
function DomReady(fn)
{
if(document.addEventListener)
{
document.addEventListener("DOMContentLoaded", fn, false);
}
else
{
document.onreadystatechange = function(){chState(fn);};
}
}
function chState(fn)
{
if(document.readyState == "interactive" || document.readyState == "complete")
fn();
}
window.onDomReady(addHndlrs);
function addHndlrs()
{
var forms = document.getElementsByTagName("form");
for(var i = 0; i < forms.length; i++)
{
var form = forms[i];
if(form.addEventListener)
{
form.addEventListener("submit", DoValidate, false);
}
else if (form.attachEvent)
{
form.attachEvent("onsubmit", DoValidate);
}
Other stuff.
}
When I click Submit on the form, DoValidate does called.
I am trying to modify this page to add another submit handler which is called after the first one.
I copied the above code, changed function names & put into s2.js.
window.onDomReady = DReady;
function DReady(fn)
{
if(document.addEventListener)
{
document.addEventListener("DOMContentLoaded", fn, false);
}
else
{
document.onreadystatechange = function(){Chk1State(fn);};
}
}
function Chk1State(fn)
{
if(document.readyState == "interactive" || document.readyState == "complete")
fn();
}
window.onDomReady(myready);
function myready()
{
var forms = document.getElementsByTagName("form");
for(var i = 0; i < forms.length; i++)
{
var form = forms[i];
if(form.addEventListener)
{
form.addEventListener("submit", mynewhandler, false);
}
else if (form.attachEvent)
{
form.attachEvent("onsubmit", mynewhandler);
}
}
}
In the form html, I added a reference to it
<script type="text/javascript" src="s1.js"></script>
<script type="text/javascript" src="s2.js"></script>
My new submit handler never gets called. I debugged it through firebug - I see DReady being called and my DOM Ready handler being registered. However myready never gets called, so my submit handler never gets registered.
What am I missing here? I tried changing order of inclusion of s1.js and s2.js but that doesn't seem to help. I want to do this without modifying s1.js
The code you provided seems to be fine! Have checked in Chrome 25, FireFox 19 and IE 10!
Normally I find it easier to just modify the code at runtime (not the source file), thanks to JavaScript being dynamic typed, you could overwrite the DoValidate function with your own, passing it the original DoValidate through closure in the s2.js:
var originalValidate = DoValidate;
DoValidate = function () {
originalValidate();
alert("my handler");
};

Sending an, intercepted and modified, submit re-loads the (wrong) page

I use a Greasemonkey script in Firefox to intercept a submit process in order to modify a certain post variable. I save the old submit routine to call it later and overwrite HTMLFormElement.prototype.submit with my interception (modification) function.
The problem I am currently facing is that something drops the post variable post=Submit and calling the (old) submit function after the modification takes me back to the current page.
var intercept_complete = false;
window.addEventListener('submit', function (e) {
e.stopPropagation();
e.preventDefault();
interceptor(e);
}, true);
function interceptor_setup() {
HTMLFormElement.prototype.real_submit = HTMLFormElement.prototype.submit;
HTMLFormElement.prototype.submit = interceptor;
}
function interceptor(e) {
var frm = e ? e.target : this;
if (!interceptor_onsubmit(frm)) {
return false;
}
if (!intercept_complete) {
ModifyAndPost(frm);
return false;
} else {
HTMLFormElement.prototype.real_submit.apply(frm);
return true;
}
}
function interceptor_onsubmit(f) {
return !f.onsubmit || f.onsubmit();
}
function ModifyAndPost(f) {
var attrs = new Array('name', 'type', 'value');
for (var i = 0; i < f.elements.length; i++) {
for (var a = 0; a < attrs.length; a++) {
if (attrs[a] == 'name') {
if (f.elements[i][attrs[a]] == "message") {
var current_message = f.elements[i][attrs[a + 2]];
if (current_message.indexOf("hello") != -1) {
var do_replace = confirm("Detected hello, would you like to replace that with bye?");
if (do_replace) {
f.elements[i][attrs[a + 2]] = current_message.replace("hello", "bye");
}
}
}
}
}
}
PerformSubmit(f);
}
function PerformSubmit(f) {
HTMLFormElement.prototype.real_submit.apply(f);
}
interceptor_setup();
Basically the script works and modifies the post variables successfully but when calling HTMLFormElement.prototype.real_submit.apply(f); to submit the modified form the request is missing the Post=Submit variable and the submit fails.
I tried removing e.stopPropagation() and e.preventDefault() and then it worked sometimes, but still dropped that post variable once in a while.
Would be great if anyone could point me in the right direction on this one. ;)

Stop html submit button in js ajax function

I want to stop the submit button in the js function checkUni()
Usually in js you can just return false, but that it not gonna work in my case because its an asynchronous (ajax)function, so the outer function will return before the inner function is able to determine wether to return false or true.
Here is the js function:
function checkUni() {
var URL = "http://localhost:8080/GradSchoolApp/test.jsp";
var container = document.getElementById("container_ID"); //destination of returned data
var request = false;
if (window.XMLHttpRequest) {
request = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
try {
request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
}
}
}
request.open("GET", URL, true);
request.onreadystatechange = function() {
if (request.readyState == 4) {
//SOME CODE
//IF <something> then STOP SUBMIT BUTTON
container.innerHTML = request.responseText;
}
}
request.send(null);
}
Simply return false in the onclick listener.
<input type="submit" onclick="checkUni(); return false;"/>
You can set the action of the form element to "#" which will have the same effect.

Categories