Onsubmit form is completely ignored

I am trying to create a dynamic comment insertion system using AJAX, but I have a problem with the form: it will not even try to execute the javascript function. Instead, it just performs a GET operation and redirects me to ?user=&reply=&submit=Submitand does nothing. Here is my form code:

<form id="cmtsubmit" onsubmit="return submitComment(this);">
    <input type="text" name="user" id="user" />
    <textarea name="reply" id="reply"></textarea> 
    <input type="submit" name="submit" value="Submit" />
</form>

and here is my javascript code:

function submitComment(form) {
    if (window.XMLhttpRequest) {
        httpRequest = new XMLhttpRequest();
    } else if (window.ActiveXObject) {
        httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
    }

    httpRequest.onreadystatechange = function() {
            if(httpRequest.readyState === 4 && httpRequest.status === 200) {
                document.getElementById('container').innerHTML += '<div style="border: 1px solid; padding: 15px;">' + httpRequest.responseText + '</div>';
                return false;
            } else {

            }
    }

        httpRequest.open('GET', 'index.php?p=cmtinsrt&user=' + form.user.value + '&cmt=' + form.reply.value, true);
        httpRequest.send(null);

}

Where am I going wrong?

EDIT: I added "return false" to the code, and now it works in IE10, but not in Firefox or Chrome. I have not tested other browsers yet, but it is clear that if this does not work in these two, this is not the right solution.

+4
source share
1 answer

javascript false, . , :

<a onclick="somefunction();" href="http://www.google.com">Go</a>

someFunction , Google. , , :

<form onsubmit="return someFunction(this);">

... someFunction - . true, . false, .

var someFunction =function (formElement) {
    // .. code
    return false; // prevents the form submit
}

javascript:

var ele = document.getElementById('myElement');
ele.addEventListener('click', someFunction);

... preventDefault , :

var someFunction =function (e) {
    e.preventDefault();
    // .. code
    return false; // redundant if you preventDefault
}

, . , . , , return false , , .

Documentation

+2

Source: https://habr.com/ru/post/1547281/


All Articles