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

Issue with Vue JS function not providing the desired array output

I declared a property in my data model like this: someArray: [] A function returns an array: getMyArray: function (someId) { var result = [7, 8, 9, 10]; return result; } I'm assigning the result of the function to m ...

Send function arguments to populate dropdown menus with JSON data

Is there a way to pass the parameter into "foodName" from the function that sends the url and id, without explicitly mentioning it in the function? For example, could you create a more generic function like: call('/url/to/foodlist', "foodLis ...

PHP and AJAX concurrent session issue causing difficulties specifically in Chrome browser

TL;DR. I'm encountering an issue in Chrome where different requests are seeing the same value while incrementing a session counter, despite it working fine in Firefox and Internet Explorer. I am attempting to hit a web page multiple times until I rec ...

Error Message: Unexpected Type Error with axios in Vue 3

Trying to implement axios in my Vue3 project for fetching APIs. Here is the code snippet from my component: export default { name: "Step2", data() { return { loading: true; }; }, mounted() { this.loading = false; }, ...

I'm facing an issue with converting my object to an array as I keep getting the message: "ERROR TypeError: undefined

ERROR TypeError: undefined is not a function Why am I unable to convert my object to an array? This error keeps popping up as I attempt to map all the items that are currently objects but need to be converted into arrays for mapping. How can I accomplish ...

What is the reason behind the warning "Function components cannot be given refs" when using a custom input component?

When attempting to customize the input component using MUI's InputUnstyled component (or any other unstyled component like SwitchUnstyled, SelectUnstyled, etc.), a warning is triggered Warning: Function components cannot be given refs. Attempts to acc ...

Utilizing knockoutjs to send a MultipartFile along with additional data in an ajax request

Here is a sample form I am working with: <form id="form"> <ul> <li><label>Picture</label> <input id="upload" name="Picture" class="k-textbox" data-bind="value: picture" type="file"/> </li> < ...

apply a course to the designated element

Alright, I have this piece of code that deals with session and page requests. // Let's start our session session_start(); // Now let's check if there is a page request if (isset($_GET['page'])) { // If there is a requested page, we ...

Troubleshooting: How to resolve the issue of "Error [ERR_HTTP_HEADERS_SENT]: Unable to set headers after they have been sent to the client"

* **> const PORT=8000 const express = require('express') const {v4:uuidv4}=require('uuid') const bcrypt =require('bcrypt') const jwt =require('jsonwebtoken') const cors=require('cors') const {MongoClie ...

"Learn how to capture the complete URL and seamlessly transfer it to another JavaScript page using Node.js and Express.js

Is there a way to access the token variable in another page (api.js)? I need to use it in my index.js. var express = require('express'); var router = express.Router(); router.get('/', function(req, res ...

A comprehensive guide on associating a JavaScript function with an element attribute

I am looking for a way to assign a JavaScript function to an HTML attribute. For example: <li data-ng-repeat="job in jobList" class= dynamicClass(str) data-filter = "dynamicFilter(str)"> The reason I want to do this is because the class name and ...

Generate a unique sequence not functioning

I'm attempting to generate a unique string composed of random characters, similar to the example found at this source. $(document).ready(function(){ $('#randomize').click(function() { var str = ""; var possibleChars = "michaeljo ...

Loading Web Applications Screen

My web app contains multiple tree views. Upon loading the page, I first see the unordered lists before the styling of the trees is displayed in the DOM after a brief delay. Is there a method to mask the web app with a spinner placed in the center of the s ...

Why is my JSON object being mistakenly interpreted as a string literal during iteration?

I'm facing a seemingly simple question but I can't seem to figure it out. Below is the jQuery code I am working with: $(function() { $.get(urlGetContainerNumbers, function(data) { console.log(data); for (var idx = 0; idx &l ...

Discover the easy way to retrieve post values using the AJAX method .post

I am currently working with two files, filter.php and products.php, which are included in index.php. I am using a .post submit form without refreshing the page. The issue arises when I send data to products.php and return it back - my filter does not refre ...

Techniques for transferring PHP print_r arrays to Javascript

Array ( [0] => Array ( [sno] => 1 [name] => Sivamani [contact] => 750241378 [$city] => Madurai ) ) Array ( [1] => Array ( [sno] => 2 ...

What should be placed in the form action field if the router.post() method includes a parameter such as :id?

I'm struggling with how to properly submit data to my update form and what needs to be entered in the action field, especially considering the router.post includes an :id parameter. Below is the relevant code snippet: router.post('/gymupdate/:id& ...

Updating a document on Firestore based on a query is a straightforward process that involves first identifying

I'm currently working on a web form page that needs to update input fields into a specific firestore document based on certain conditions. Can anyone provide guidance on how this can be achieved? The initial part where I retrieve the query results se ...

Is there a way to integrate PHP functionality into JavaScript?

When it comes to using JavaScript and PHP together, a common challenge is retrieving information from a database and utilizing that data in a JavaScript function. In my case, I need this functionality for implementing password change functionality on a w ...

Managing "post" requests in a one-page web application using node.js

Although there may be similar answers to this question, I am in search of something different. On the client side, I have a signUp form that will make a post request to the server with the username and password. On the server side, I authenticate the req ...