Avoid page refreshes when sending form data without using jQuery

As I work on improving my JavaScript skills, I've been experimenting with submitting a form using AJAX without jQuery. However, I've encountered an issue where I can't seem to prevent form submission using addEventListener(); in JavaScript.

window.addEventListener('load', function(){
    document.forms[0].addEventListener('submit', function(){
        send();
        return false;
    }, false);
}, false);

No matter how I rearrange the code or try different methods like return send(); or returnValue=false;, the form still submits and the page reloads. I can only prevent this by using return false; within an inline event listener, but is that the best approach?

Any suggestions or thoughts on why addEventListener(); doesn't stop form submission as expected?

Answer №1

Which web browser are you currently utilizing? Please note that addEventListener is not compatible with versions of Internet Explorer prior to IE 9.

In addition, be sure to execute .preventDefault() and .stopPropagation().

Furthermore, keep in mind that the load event will not trigger until all page content, including images, has fully loaded. This means your handler may not be registered in time when submitting a form.

On a related note, if using jQuery, the following code snippet can help:

$(function(){
  $('form').submit(function(){
    send();
    return false;
  });
});

This method ensures the handler is registered once the DOM is ready and will function correctly in Internet Explorer.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing the JQuery Error Event for displaying a backup image in case of loading error

While studying event handling in jQuery, I came across the jQuery events documentation. I encountered an issue when trying to replicate the jQuery error event on my webpage. Here is a snippet of the HTML code: <!DOCTYPE html> <html> <head ...

Material UI allows for the creation of numbered lists with ease. This

<List> {instructionList.map((el) => ( <ListItem divider key={el.id}> {el.type === 'number' ? <React.Fragmen ...

Utilize a Java application to log in to a website automatically without the need to click on

Opening two websites in my application is a requirement. Both of these websites have login forms with the action set to POST method. My goal is to automatically redirect to the next page after logging into these websites when I access them through my proj ...

Angular 5 combined with the dynamic capabilities of Popper.JS

Launching a training project that requires Popper.Js in its features has been quite challenging. Despite following Bootstrap's documentation on how to implement Popper.Js, I have encountered difficulties. As per Bootstrap's docs, I tried initiat ...

Tips for relying on an extensive Database in NodeJS NPM

Dealing with large files in NPM can be tricky. For example, my NPM package includes an 800MB SQLite database. I initially wanted to avoid including it in the package tarball and instead add it as a URL dependency. Unfortunately, using this approach would ...

Utilize a checkbox located within a table to obtain or delete the ID with the help of

Greetings everyone, I am currently working on creating a table with checkboxes. The goal is to add the ID to an array of objects when the checkbox is clicked and remove it when unchecked. Here is a snippet of my code: HTML Table ... <td><input ...

Slowly reveal a portion of the picture

I have created a slider that changes pictures when the next button is clicked. Everything works perfectly on localhost, but on the server, some images fade in halfway instead of fully displaying. There are 39 pictures in total for the slider, each with a s ...

What is the process for importing npm scoped packages with @ symbol in Deno?

Having some trouble with importing @whiskeysockets/baileys in Deno. Here's the code snippet I'm using: import * as a from "npm:@whiskeysockets/baileys"; console.log(a); When I try to run deno run main.ts, it throws the following error: ...

Accomplishing Nested Element Retrieval in Javascript

While this question may have been asked previously, it hasn't been tackled quite like this before... I have the following block of HTML code. <table class="fr ralign cartSummaryTable"> <tr> <td width="320px"> <div cl ...

Setting the date in a datetimepicker using the model

I've encountered an issue while trying to utilize the angular date time picker. It seems that when I load data from the model, the picker does not bind the value correctly. If I manually set the value to a date, it works fine. However, when the data ...

Importing modules dynamically in NodeJS enhances flexibility in loading and utilizing

How can I dynamically import modules in JavaScript? Let's say this is my project structure : | - index.js | - modules | - SomeModule | - router.js | - controller.js | - SomeOtherModule | - SubModule ...

Submit button does not capture Angular ng-model values

Here's a situation with two input fields in a form that I need help with: <form name="modifyApp" class="form-signin" ng-submit="modify(val)"> <input type="text" class="form-control" ng-model="val.name" id="appName"> <input type=" ...

Dynamic navigation menu with Bootstrap's responsive multi-level design

I recently developed a multi-level navigation menu using Bootstrap. Everything seems to be working smoothly when the screen size is 1200px or above. However, I encountered an issue with the second level dropdown menu not opening upon clicking on screens sm ...

Use javascript to implement lazy-loading for images

Looking to enhance website performance by lazy loading images. Plan is to initially display a set number of images and then load the rest lazily. Here's what I have currently: Check out the code here <div> <img src="http://i.imgur.com/CmU ...

Refreshing the webpage with new data using jQuery after an AJAX request is

I'm experiencing a problem where the DOM is not updating until after the completion of the $.each loop. On my website, I have several div elements that are supposed to turn orange as they are being looped over. However, once the data is sent to the s ...

What is the process for validating the CSS background-image URL using Javascript?

The concept here is to verify the URL of the CSS element's id (.boot). If the URL matches, which it does, then it should display "hello world." However, despite everything seeming correct, the expected behavior is not occurring, and the reason behind ...

The button is not displaying

When trying to click on the "Open device Access" button within the accordion, it does not appear. It seems like there may be an issue with the JavaScript as the transition from "display none" to "display block" is not functioning properly. The "Open device ...

Identifying the presence of a period within a string

Forgive me for what may seem like a foolish inquiry, but I am unsure of how to search a string to determine if it includes a period. Here's what I have attempted: var text = "This is an example without a period. What next?" alert(text.search(".")); ...

Consolidating various analogous operations into a single function

After scouring through StackOverflow in search of a solution to what I perceive as a simple issue, I have come up empty-handed. It seems like I may be using the wrong keywords in my search. I am interested in finding out how to condense the following code ...

There seems to be an issue as the function reporter.beforeLaunch cannot be identified and

I am currently attempting to incorporate the protractor screenshot reporter for jasmine 2. However, I encountered the following error in the terminal: /usr/local/bin/node lib/cli.js example/conf.js /Users/sadiq/node_modules/protractor/node_modules/q/q.j ...