Maintain checkbox state through page reloads using ajax

Currently, I am troubleshooting a script that is intended to keep checkbox values checked even after the page is reloaded or refreshed. The code snippet below was implemented for this purpose, but unfortunately, it doesn't seem to be functioning correctly. Any assistance in resolving this issue would be highly appreciated.

<script>
            function onClickBox() {
                let checked=$("#check").is(":checked");
                localStorage.setItem("checked", checked);

            }
            function onReady() {

                let checked="true"==localStorage.getItem("checked");
                $("#check").prop('checked', checked);
                $("#check").click(onClickBox);
            }
            $(document).ready(onReady);

</script>

The following line of code

return '<input type="checkbox" id="check" href="#"' + 'order_id="' + data + '">Yes</>';
allows an admin user to select a checkbox. Subsequently, the code captures the ID and triggers the execution of check_payment.php where a query inserts "yes" into the specified ID row.

 aoColumnDefs: [
           {
                aTargets: [6],
                mData: "userId",
                mRender: function (data, type, full) {
                     return '<input type="checkbox" id="check" href="#"' + 'order_id="' + data + '">Yes</>';
                    //return '<button href="#"' + 'order_id="'+ data + '">Yes</button>';
                }

            }
         ],
         language: {
            url: 'https://cdn.datatables.net/plug-ins/9dcbecd42ad/i18n/English.json'
            }
});
$('#example').on( 'click', 'input:checkbox', function () {
            var data = table.row( $(this).parents('tr') ).data();
            var order_id = data['order_id'];
            console.log(order_id);
            $.ajax({
                type: "POST",
                url: 'check_payment.php',
                data: "order_id=" + order_id,   
            });
        } );

Answer №1

Presented here is a VanillaJS solution. With the availability of document.querySelector, it seems that jQuery has become outdated in my opinion. Your logic appears to be sound, so I can only assume that one of your jQuery calls is causing issues, although I am unsure which one.

// find element with id #check
var checkbox = window.check;

// check and set value
isChecked = () => localStorage.getItem("checked") == "true";
setCheck = (v) => checkbox.checked = v;

// event handlers
onClickBox = () => localStorage.setItem("checked", checkbox.checked);
onReady = () => setCheck(isChecked());

// bindings
checkbox.addEventListener("click", onClickBox);
document.addEventListener("load", onReady);

Edit: It is possible that the onLoad handler (or onReady, with jQuery) is not firing because the code is embedded in the body. If the script is in the head, utilize the eventHandler; if the script is in the body, simply call onReady() after setting the click handler for the checkbox.

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

Showing the image as a backdrop while scrolling through text

How can I create an effect that continuously displays the image while scrolling text in Internet Explorer without using position: sticky or position: fixed? var sticky = document.querySelector('.sticky-container'); var img = document.querySele ...

The server's response is unpredictable, causing Json.Parse to fail intermittently

I have encountered a strange issue that is really frustrating. It all started when I noticed that my Json.Parse function failed intermittently. Here is the code snippet in question: const Info = JSON.parse(response); this.onInfoUpdate(Info.InfoConfig[0]); ...

When attempting to utilize nsIPrefBranch in a Firefox extension to save data, an unexpected error of NS_ERROR_UNEXPECTED occurs

I am facing a challenge with saving persistent data in a Firefox extension. Currently, I am attempting to utilize nsIPrefBranch in the following manner: var db = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.ns ...

Exploring Fetch API with Promise.all

I have successfully implemented a functionality that fetches data from two URLs and performs an action only when both requests are successful. However, I am curious if there is a more efficient and succinct way to achieve the same result. Helper functions ...

Why are the radio buttons not aligned with the text in the center?

Currently, I am in the process of building a form that includes radio buttons. However, I've encountered an issue where the text next to the radio buttons appears on a different level than the buttons themselves. How can I go about fixing this partic ...

Supply context to node package

I've encountered an issue with the code below, where sometimes the content is not passed correctly: var app = require('buildersApps'); app.addContent({ folderPath: __dirname + '/content/' }); app.start(); To address thi ...

Displaying an image with a JavaScript variable is a common task in web

I have a Javascript code snippet below where the image name "samson decosta" is stored in a MySQL database. I am retrieving this image and trying to display it as a background_image in a div. document.getElementById("image_chk").style.backgroundImage="url ...

What is the best way to ensure the submenu is visible on every menu when the cursor hovers over it

I am currently working on implementing a drop-down menu using react.js. I have been following a tutorial but encountered an issue when trying to add a submenu to the menu items. Instead of the submenu appearing only for the specific menu item hovered over, ...

Discord.js counter feature

Recently, I attempted to create my own counting system for my server inspired by bots like countr. Here is the code snippet I came up with: if (message.channel.id === "794733520458612736") { const numdb = db.get("numdb"); if (me ...

Ways to change the visibility of a view depending on a state in vuex?

If I have a button <Button> Log me in! </Button>, and I want to dynamically change its style based on the state of my Vuex app (state.user is not null). How should I properly implement this functionality? I'm considering creating a field ...

What is the method for implementing conditions within a button element in Vue.js 2?

Here is an example of my component code: ... <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> ... <script> import { mapGetters } from 'vuex' export default{ ...

Bootstrap Thumbnail Grid - dynamic loading with ajax

Situation: I am facing a challenge where I have a view displaying countries in a twitter bootstrap thumbnail grid. Upon clicking an image, the intention is to dynamically show cities related to that particular country within the same grid on the screen. T ...

Tips for transferring data to the next page with JavaScript AJAX

I am working on a webpage that includes an html select element <pre> $query = mysql_query("select * from results"); echo "<select id='date' onchange='showdata()' class='form-control'>"; while ($arr = mysql_fetch_a ...

Troubleshooting Issue with jQuery onclick Function not Transmitting Data

Why is this error occurring: Uncaught TypeError: Object [object global] has no method 'data' HTML: $attributes = array('class' => 'main post', 'onsubmit' => 'validateModules(event)', 'dataid& ...

Retrieve a DOCX file via AJAX response

I am encountering an issue with a Django function that returns a file: ... return FileResponse(open('demo.docx', 'rb')) I am using ajax to fetch it on the client side. Now, I need to download it on the client side. This is the code I a ...

Despite setting the csrfmiddlewaretoken and csrftoken cookie for an Ajax POST request, Django still returns a 403 Forbidden error

Despite ensuring that both the csrfmiddlewaretoken and the csrftoken cookie are correct for a django POST request to be successful, I am still receiving a 403 error: When checking the chrome console: document.cookie The output shows "csrftoken=Wt9eeJ ...

How can I handle pings in Discord using discord.js?

I've been working on a feature in my discord.js bot that responds to pings, but I'm running into issues. Even after trying <@BOTID> and @BOT#0000, the functionality is not behaving as expected. Here's the snippet of code I'm using ...

Leveraging the power of AJAX with either jquery or plain javascript to parse nested JSON data and display the

Similar Question: jquery reading nested json I am seeking a reliable method to iterate through multiple sets of data stored in JSON, some of which may have deep levels of nesting. My goal is to display this data in a table format. I am uncertain abou ...

Lambda script for Amazon Alexa Skill is not functioning as expected

I am currently developing a Lambda function for an Amazon Alexa skill using NodeJS. For those unfamiliar, Alexa is a cylindrical speaker that responds to voice commands, and a "skill" is essentially a voice-operated app for the device. This particular func ...

Setting up RTL (Right to Left) functionality in Material UI version 5 - A Step-by-Step Guide

After updating my app to version 5 of Material-UI from version 4, I noticed that the RTL support is no longer functioning. I carefully followed the instructions in the documentation: https://mui.com/guides/right-to-left/ The current outcome is that the ...