Is there a way to submit a form by simply checking a checkbox without causing the page to reload?

I'm in the process of setting up a home automation system using a Raspberry Pi running Raspbian. I plan on creating a web page that will feature checkboxes to control lights through relays. I need help with implementing a checkbox functionality that, when checked, triggers PHP to execute a Python code file for relay control. I've heard that Ajax and JavaScript can be used to post forms without the need to refresh the entire page, but I am not well-versed in these languages. Can someone demonstrate a simple example of a checkbox where checking it runs one PHP exec() command and unchecking it runs another?

Here is an example:

<!DOCTYPE html>
<html>
    <head>
        <script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
        <title>Raspberry Pi</title>
    </head>
    <body>
        <input type="checkbox" class="iclass" />
        <script>
    $("input.iclass").click(function (e) {
    e.preventDefault();
    $.post("post.php", {param1: value, param2: value});
});
        </script>
    </body>
</html>

The post.php currently only displays alert('Succesful!');, but there seems to be an issue with its functioning.

Answer №1

Ensure to incorporate the jQuery library. Here is an example of how you can do it:

$("input.checkbox-class").click(function (e) {
    e.preventDefault();
    $.post("/path/to/php/script.php", {param1: value, param2: value});
});

The content of /path/to/php/script.php will contain:

<?php
    exec("system");
?>

An illustration with the complete HTML would be:

<!DOCTYPE html>
<html>
    <head>
        <script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
        <title>Raspberry Pi</title>
    </head>
    <body>
        <input type="checkbox" />
        <script>
            $(document).ready(function (e) {
                e.preventDefault();
                $.post("/path/to/php/script.php", {param1: value, param2: value});
            });
        </script>
    </body>
</html>

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

Trigger a function when the browser automatically populates an input field

I am attempting to trigger a function that can detect if the browser has autofilled a field and then add a specific class to it. After finding a thread with a solution that mostly works, mentioned here: Here is how I implemented it: $.fn.allchange = fun ...

"Exploring the Possibilities of Cross-Domain Requests in Internet

Just wanted to express my gratitude to everyone who offered assistance in the comments. After exploring various websites in IE11 and observing their ajax requests, it appears that many requests are being blocked from CORS, leading most code to fallback to ...

What is the best way to personalize the Window.Confirm() dialog in JavaScript?

var val= confirm("Are you sure to cancel?"); The code snippet above will display a popup with two choices - Ok and Cancel, with Ok being the default choice. Is there a way to make Cancel the default choice instead and switch the positions of the ...

Utilizing Grunt to streamline a personalized project

I have set up Grunt as my "JS Task Runner". Node.js is installed in the directory "C:/Program Files". NPM has been installed in C:/users/Peterson/appdata/roaming/npm. Inside the npm folder, I have Grunt, Bower, and Grunt-cli. I am working on a pro ...

(Node.js Fundamentals) Is there a specific reason for placing a period in front of the pathname following the parsing of a

As a beginner in Node.js, I decided to follow a tutorial on w3school to deepen my understanding of this platform. var http = require('http'); var url = require('url'); var fs = require('fs'); http.createServer(function (req ...

Steps for iterating through array objects within a function

I am encountering an issue with vs.selectedTags array, which consists of 3 objects. Within a for loop that iterates 3 times, I need to make 3 API calls to retrieve ticker data for each object, a task I have successfully accomplished. The problem arises w ...

Showcasing information retrieved from MongoLab on my site

I am struggling to find a straightforward method to retrieve data from MongoLab and present it using HTML, JavaScript, or JQuery. Despite reviewing their REST API extensively, I still can't grasp how it functions. Can someone offer assistance? This in ...

Javascript encountering compatibility issues with certain versions of Internet Explorer; employing browser detection workaround

Unfortunately, Internet Explorer is causing issues when trying to execute this script (specifically the 'else' part). Despite numerous attempts, I have been unable to resolve it. $(document).ready(function(){ if (navigator.appName != "Micros ...

Tips for avoiding the 'ResizeObserver loop finished with unhandled notifications.' error when using React with mui/material/Table

This is our current code snippet: import Table from '@mui/material/Table'; import TableBody from '@mui/material/TableBody'; import TableCell from '@mui/material/TableCell'; import TableContainer from '@mui/material/TableC ...

Aggregating multiple parameters in a D3 Treemap visualization

I have come across an interesting challenge while working on a project involving a zoomable treemap. I am currently exploring how to pass and aggregate multiple parameters within the treemap, similar to what is typically done in a zoomable treemap visualiz ...

The compilation of the module has encountered an error with the PostCSS loader. There is a SyntaxError at line 2, character 14 indicating an unknown

I am developing an Angular 8 application. Currently, I am incorporating AlertifyJs into my project. In the styles.css file of Angular, I have imported these libraries: @import '../node_modules/alertifyjs/build/alertify.min.js'; @import '. ...

What is the process for advancing an object in Three.js?

Does anyone know how to advance the position of an object in Three.js? I've been thinking about converting rotation.x, y, z into a vector and manipulating it that way. However, as a beginner, I'm unsure of how to proceed. Any guidance would be g ...

Error encountered with Firebase Modular SDK V9.0.0+: Issue with undefined firebase property 'apps' causing TypeError

Encountered an error while attempting to run my next.js app. Despite trying various methods, I have been unable to resolve it. The version of Firebase I am using is 9.0.1 Server Error TypeError: Cannot read property 'apps' of undefined The error ...

Implementing Laravel pagination to retrieve data through ajax calls

I am currently working on setting up a pagination feature using Laravel. When it comes to the backend, I have set up my JSON response in the following way: if(isset($request->myDate)) { $request->validate([ ' ...

Unexpected symbol in JSON parsing with JavaScript

let information; $.ajax({ url: link, type: 'POST', dataType: "json", success: function (data, textStatus) { information = data; alert(data.name); } }); I am attempting to retrieve JSON-encoded data from a spe ...

Exploring the integration of Formik with Material-UI's select field - A step-by

Trying to implement Formik with Material-UI's Textfield component using the select attribute. Every time I change the option, it shows this warning: Material-UI: You have provided an out-of-range value null for the select (name="subIndicatorId& ...

Attaching a modal to an entity

I am currently working on binding a Knockout (KO) viewmodel to a Bootstrap modal, but it seems like I am overlooking a step to direct KO to fill in the input fields. Below is the current setup: The template for the modal: <script type="text/html" id= ...

What is the method for extracting element.style.marginTop in digits exclusively?

Consider an HTML element with the property margin-top: 30px. function extractValue(margin) { /* to do */ } var element = document.getElementById("element"); alert(extractValue(element.style.marginTop)); #element { margin-top: 30px; } <div id=" ...

.class selector malfunctioning

I'm currently developing a card game system where players can select a card by clicking on it and then choose where to place it. However, I've encountered an issue where nothing happens when the player clicks on the target place. Here is the li ...

Unable to retrieve response token from form in a Next.js/React application utilizing Cloudflare Turnstile

As a beginner in Next.js/React, I'm currently working on creating a basic contact form with Cloudflare Turnstile integration. Prior to implementing Turnstile, the form functioned perfectly, submitting data to the API and sending emails without any iss ...