What is the best way to refresh a page during an ajax call while also resetting all form fields?

Each time an ajax request is made, the page should refresh without clearing all form fields upon loading

Custom Form

<form method='post'>
 <input type='text' placeholder='product'/>
 <input type='number' placeholder='cost'/>
 <input type='number' placeholder='tax'/>
 <button type='button' id="cust_tax"  data-toggle="collapse" data-target="#cust_tax">Custom tax</button>
<input type='number' placeholder='new tax' id="cust_tax" class="collapse"/>
<input type='button' class='apply_tax'>New tax add</button>
<input type='submit'/>
</form>

When a user clicks on custom tax, an ajax call is triggered which saves the new_tax in the database and adds it to the list automatically.

AJAX Function

$(".tax_apply").click(function() {
 var tax_name = document.getElementById("tax_name").value;
 var tax_value = document.getElementById("tax_value").value;
 ajaxPost('/myurl',{'user':user,'tax_name':tax_name,'tax_value':tax_value},function(result){
                    alert('new tax added');
                //reload page
                    });
});

Now, each time an ajax request is made and a user adds a new tax, the page should reload without clearing the form fields that have been entered.

Answer №1

If you want to save the content typed into form fields and retrieve it on page load, one way is to attach an event listener that stores the data in localStorage. Here's a sample implementation:

$(myCollectionOfFields).keyup(function(){
    $(myFormFields).each(function(){    
        var id = $(this).attr('id');
        var value = $(this).val();
       localStorage.setItem(id, value);

    });   
});

$( document ).ready(function() {
    $(myFormFields).each(function(){    
        var id = $(this).attr('id');
        var value = localStorage.getItem(id);

        $(this).val(value);

    }); 
});

Note that this method may not work for all users if they don't allow local storage. It's also worth considering addressing the backend issue instead of relying solely on this approach.

Nevertheless, this solution could potentially serve its purpose.

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

How to smoothly glide to the bottom of a chat box by scrolling synchronously

I am currently in the process of developing a chat application. Each time a user sends a new message, it is added to a list of messages displayed in an unordered list (ul). I have successfully made the ul scrollable, but unfortunately, when a new message i ...

The .val() and focus() methods are not functioning correctly

I am having an issue with a simple script: when I input a link to an image in the form's INPUT field, it should automatically display a preview of the image: https://example.com/image.jpg However, when I input the same link not by using ctrl+C/ctr ...

Retrieve the contents of the browser's DOM from within an Android operating system runtime

Imagine a typical login page similar to the one depicted below: https://i.stack.imgur.com/SF1Bd.jpg To interact with the HTML elements within the DOM, we can utilize either jQuery or conventional JavaScript like so: https://i.stack.imgur.com/e5aQZ.png ...

Ways to attribute a numeric worth to a choice in a JavaScript form

I am in the process of creating a form that allows users to customize and order pizza while showing them the invoice as they make their selections. Currently, I have successfully implemented the display of user-selected options, but I am struggling with a ...

Magical Stylist - Eradicate Indicators while Preserving Labeling

Recently, I've been experimenting with the Google styling wizard in an effort to remove markers while retaining labels for businesses. My objective is to eliminate the marker icons but still display the text labels such as "Jimmy Johns," "Boone Saloon ...

What is the best way to include multiple action creators in a single listenerMiddleware in Redux Toolkit?

I am looking to store the current state in my database every time there is a change in any of its properties. I have implemented two middlewares to handle this task, each responsible for dispatching the saveTrip function. Although both middlewares are ide ...

Unable to execute the Unisubs (amara) repository on GitHub

Within the repository at https://github.com/pculture/unisubs, I attempted to follow the "Quick start" guide, but encountered an error at step 3: "... Get:13 trusty/universe amd64 Packages [7589 kB] Fetched 20.8 MB in 53s (391 kB/s) W: Failed to fetch Ha ...

``There seems to be an issue with the Express app when trying to access it

I have set up an express app that I want other devices on the same WIFI network to access without requiring internet connectivity. The main computer hosting the app is assigned with a fixed IP address: 192.168.1.60 In my server.js file, I have included t ...

Sending JSON data stored in a JavaScript variable through a jQuery POST request

I am currently attempting to retrieve data from a remote location using a JQuery post method. It works perfectly fine when I directly input the data to be posted, but for some reason, it fails when I store the JSON in a JavaScript variable and pass it in. ...

Transform this JavaScript into Vue 3 code

Hey there! I'm currently working on implementing dark mode into my project by following a tutorial. However, the tutorial is based on JavaScript and not Vue, so I'm having some trouble converting this particular section of code to work with Vue 3 ...

Utilize AJAX to verify the content of a PHP variable within a Wordpress environment

After attempting multiple approaches without success, I am seeking advice from anyone who has experience with this particular issue. I have developed a custom post type that generates Public pages. However, I require certain information to only be accessi ...

Is there a way to link the datepicker of one calendar to automatically sync with another under specific circumstances?

I have implemented two datepicker fields on a single page: Start Date and End Date. $("#orders-start-date").datepicker({ dateFormat: "yy-mm-dd", maxDate: new Date(), onSelect: function(date, el) { $this.trigger("orders:filter", date, $ ...

Converting image bytes to base64 in React Native: A step-by-step guide

When requesting the product image from the backend, I want to show it to the user. The issue is: the API response contains a PNG image if the product has an image, but returns a (204 NO Content) if the product does not have an image. So, I need to display ...

Establishing numerous websocket connections within a singular application

I am looking to conduct load testing on our websocket service. Is there a method to establish multiple websocket connections from one workstation? My attempt with npm ws and websocket modules in conjunction with NodeJS was successful for a single connecti ...

Is there a way to use jQuery to determine if the selectAll checkbox is selected after manually selecting all checkboxes?

How can I accomplish this task? I believe I am capable of doing it. <input type='checkbox' id='selectAll'/> <input type='checkbox' id='select1' class='select'/> <input type='checkbox&apo ...

How can I remove a dynamically added <tr> element using jQuery?

I insert the <tr> into the <tbody> for (var i = 0 ;i < 12 ;i++){ $(`<tr><td>test</td></tr>`).appendTo('#songsTbody'); } within this HTML structure. <tbody id="songsTbody"> </tbody> ...

The idleTimer plugin appears to be malfunctioning

I have been working on implementing an automatic logout feature for users who remain idle for a specific amount of time on a particular page. My approach involves using jade files to structure the layout of my html pages. I attempted to integrate the idleT ...

Retrieve data from a text file using ajax and then return the string to an HTML document

Just starting out with ajax, I have a text file containing number values For example, in ids.txt, 12345 maps to 54321 12345,54321 23456,65432 34567,76543 45678,87654 56789,98765 Here is the Html code snippet I am using <html><body> < ...

"The Material UI date picker is encountering an issue with the error prop, which is being evaluated

I have developed a date picker that utilizes the Jalali calendar. While attempting to pass error checking using the error prop in the following code: <LocalizationProvider dateAdapter={AdapterJalali}> <MobileDatePicker label={lab ...

Unusual actions observed with that particular button

Currently, I am working on creating a pomodoro clock using Codepen. While I acknowledge that my code isn't flawless yet, I have encountered a peculiar behavior with the Start button. When I click on it once, the timer starts as expected. However, if I ...