Refresh the page automatically upon submitting a form in WordPress using JavaScript

Is there a way to display data after submitting a form without refreshing the page in Wordpress? I have implemented a javascript function onSubmit that hides the form div and shows the result div, but the page reloads immediately after showing the result. How can I prevent this automatic refresh?

This is the code for the first form div:

<form  style="margin-top: 30px;" class="form-horizontal t-gray" id="ContactForm" method="post"  onsubmit="document.getElementById('first').style.display = 'none';document.getElementById('hidden_div').style.display = ''; return true;" action="">
<div id="first">

<div class="col-md-6">
<div class="form-group">
<label for="" class="col-sm-3 control-label">Select Journey Type:</label>
...

The second div displays the submitted data from the first form:

<div id="hidden_div" style="display:none" >
<?php
...

<div class="container booking-area">
...

Answer №1

One way to prevent the default behavior of an event is by using e.preventDefault() and passing e into your onsubmit function.

This simple method alters the default action of the event, such as stopping a form submission from refreshing the page in the browser. To learn more about event.preventDefault(), visit MDN.

Inline JavaScript function calls inside HTML elements are not recommended, especially when working with vanilla JS. It's better practice to use an HTML reference, like an id, in a separate JS file or a script tag.

To reference your form, you can do:

In ES6 (recommended)

const contactForm = document.getElementById('ContactForm');

In ES5

var contactForm = document.getElementById('ContactForm');

You can bind the submit event either through dot notation:

contactForm.onsubmit = function(e){
  e.preventDefault();
  // do other things
};

Or by adding an event listener:

contactForm.addEventListener('submit', function(e) {
  e.preventDefault();
  // continue doing stuff
}, false);

Many JS developers prefer using the addEventListener() method for better event handling control. However, it may be unnecessary in this case.

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

Detecting Specific Web Browsers on My Website: What's the Best Approach?

My website is experiencing compatibility issues with certain browsers, such as Firefox. I want to display a message when users visit the webpage using an unsupported browser, similar to how http://species-in-pieces.com shows a notification saying "Works ...

Can anyone suggest a simple method to decode this JavaScript?

While browsing a website's checkout page, I came across a suspicious Javascript snippet that seemed out of place. It raised concerns that it might be secretly stealing credit card numbers: var R = ['1jBCeMi', '81AdhODE', 'keyd ...

Creating a vendor bundle in create-react-appReady to optimize your create-react

When using the create-react-app tool, how can you specifically create a separate vendor bundle? While code splitting can be achieved easily with the react-code-splitting package, I have not been able to find clear instructions on generating vendor bundles ...

Securing user access in Angular: managing new tab or new browser window

When developing my AngularJS-based application, I initially utilized localStorage to save the JWT authentication token obtained from the backend. The app employed an interceptor to send this token along with every request made to the backend server. This p ...

The EJS template on the Express app is encountering an issue: it is unable to find the view "/id" within the views directory located at "/home/USER/Desktop/scholarship-app/views"

When attempting to render the request URL for an ID in my Express app, I encountered the following error: Error: Failed to find view "/id" in views directory "/home/USER/Desktop/scholarship-app/views" Here is a portion of my Express app code: app.get(&a ...

Encountering an issue while attempting to retrieve information from Vuex store

I recently encountered an issue while trying to store my water data in Vuex. I followed the implementation below, but when I attempted to access my data array, it did not show up as expected. const store = new Vuex.Store({ state: { categories: ...

Encountering an Error in Laravel 8: Form Submission Issue - Uncaught TypeError Preventing Property Read

<a href="{{ url('/home') }}">Home</a> <a href="{{ route('logout') }}" onclick="event.preventDefault();document.getElementById('logout-form').submit();">Logout</a> <form ...

Tips for updating the value of an Array of Objects using an array containing the desired string value

I have a scenario where I need to update the 'checked' key value to true for objects in an array based on another array's values. var daysActive = ['monday', 'tuesday', 'wednesday']; var weekDays = [{ "name": ...

What is the best approach to add additional functionality to an already existing object method?

Let's say we have an obj, var obj = { l:function(){ alert(1); } } In what way can additional functionality be incorporated into obj.l without directly modifying the object? ...

Analyzing the original data form versus the modified data

I'm dealing with a form in React that utilizes react-hook-form and the useFieldArray method for adding dynamic steps. The challenge I'm facing is how to compare the original data passed to the form with the edited data, in order to make correspon ...

Tips for reversing a sketch: Creating a timer where the text continuously refreshes causing it to intersect

Currently, I am working on developing a stopwatch that is functional. However, I am facing an issue where the text overlaps itself when it changes due to repetitive drawing. Removing the strokeText and fillText from the interval prevents it from changing a ...

Is there a way to exclude the element from being displayed when using ngIf in AngularJS?

Is there a way in Angular to conditionally add an element to the DOM without having it always added, even when its evaluation is false? I am looking for an alternative method to ngIf. ...

Break down React website into distinct modules and bundle them as npm dependencies within a single package

Currently, I am developing a React website that includes distinct sections such as contact management and message management. Each of these sections is quite extensive. To navigate to these sections, we use a single dashboard for control. Since separate ...

Checking for the existence of a row in Node.js using Sqlite3

Wondering if it's possible to verify the existence of a row using node.js and the sqlite module. I currently have this function in place, but it always returns false due to the asynchronous nature of the module. function checkIfRowExists(username, pa ...

Is it possible to utilize $.each() in combination with $.ajax() to query an API?

I am dealing with an array containing 2 values, and for each value, I need to make an AJAX query to an API to check the stock availability. If there is stock for both values, a certain message should be executed, otherwise, a different message. This check ...

Spotify preview URIs are not functioning properly on iOS Safari

I created a mini website that plays random songs using Spotify. Everything works perfectly fine on desktop browsers - the preview_urls play flawlessly! However, when I try to use my player on an iPhone (iOS), the preview_url doesn't respond and the so ...

Triggering OnClick() more than once may result in the function failing to execute as intended

My dilemma involves a table of cells where clicking a cell triggers an event. I need to dynamically add cells, so I plan to call OnClick again on all rows. But when I do so for the second time, cells that have already had OnClick called twice stop firing a ...

The Vue.js component was unable to retrieve the data

I am facing an issue with accessing data inside a simple component. Here is the code for my component: <template> <!-- success --> <div class="message-box message-box-success animated fadeIn" id="message-box-success"> <div cl ...

Tips for incorporating external libraries into a Grafana data source plugin

What's the best way to integrate an external library into a Grafana datasource plugin? My plugin is functioning properly, but I encounter an error when trying to use the "mqtt" library that I have installed and added to the package.json file: Plugin ...

Is there a way to extract and store the JavaScript Promise value in Selenium as a variable?

Using a JavaScript script, I make an xmlhttprequests call to retrieve a specific value. However, when trying to pass this value back to Selenium for further actions, my code consistently returns None. Even though I have assigned and returned the global var ...