Jump to content

How to get a checkbox to update a database onclick without a submit button?


Richie1209
 Share

Recommended Posts

Javascript runs on the client, PHP on the server, so you can't incorporate PHP code inside JS.

What you can do is submit an AJAX request from JS to the server, process it with PHP and send back the results as a response.

In JQuery, look at

  • $.ajax()
  • $.get()
  • $.post()

Here's a very basic example

<?php
if (isset($_GET['ajax']))  {                     // I like to tell my script it's reciving AJAX
    $x = $_GET['x'] ?? 0;
    exit("$x squared is " . ($x**2));            // when process an AJAX request, anything that would normally be sent to the screen 
}                                                // is sent back in a response message

// rest of php code here
?>
<html>
<head>
<title>Example</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js"></script>
<script type='text/javascript'>
   $().ready( function() {
       $("#btnSub").click( function() {
           $.get (
                "",                                         //  target script is "self"
                {"ajax":1, "x":$("#x").val() },             // data to send
                function(resp) {                            // process response
                    $("#result").html(resp);
                },
                "TEXT"                                      // response type
           )
       })
   })
</script>
</head>
<body>
Input a number <input type='text' id='x' value='0'>
<br>
<button id='btnSub'>Get Square</button>
<hr>
<div id='result'></div>
</body>
</html>

 

Edited by Barand
  • Great Answer 1
Link to comment
Share on other sites

This thread is more than a year old.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

 Share

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.