article

Thursday, December 24, 2020

Insert Checkbox values in Database using Jquery Ajax and PHP Mysqli

Insert Checkbox values in Database using Jquery Ajax and PHP Mysqli

--
-- Table structure for table `checkbox`
--

CREATE TABLE `checkbox` (
  `id` int(11) NOT NULL,
  `name` varchar(155) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
<!doctype html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Insert Checkbox values in Database using Jquery Ajax and PHP Mysqli</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
</head>
<body>
    <h3>Insert Checkbox values in Database using Jquery Ajax and PHP Mysqli</h3>
    <input type="checkbox" class="get_value" value="Python">
    <label>Python</label>
    <br/>
    <input type="checkbox" class="get_value" value="JavaScript">
    <label>JavaScript</label>
    <br/>
    <input type="checkbox" class="get_value" value="Java">
    <label>Java</label>
    <br/>
    <input type="checkbox" class="get_value" value="PHP">
    <label>PHP</label>
    <br/>
    <input type="checkbox" class="get_value" value="C#">
    <label>C#</label>
    <br/>
    <br/>
    <button type="button" name="submit" id="submit">Save</button>
    <br/>
    <h4 id="result"></h4>
    <script>
        $(document).ready(function() {
            $('#submit').click(function() {
                var insert = [];
                $('.get_value').each(function() {
                    if ($(this).is(":checked")) {
                        insert.push($(this).val());
                    }
                });
                insert = insert.toString();
                $.ajax({
                    url: "insert.php",
                    method: "POST",
                    data: {
                        insert: insert
                    },
                    success: function(data) {
                        $('#result').html(data);
                    }
                });
            });
        });
    </script>
</body>
</html>
insert.php
//insert.php
<?php
if(isset($_POST["insert"]))
{
 $query = "INSERT INTO checkbox(name) VALUES ('".$_POST["insert"]."')";
 $result = mysqli_query($conn, $query);
 echo "Data Inserted Successfully!";
}
?>
//dbcon.php
<?php
$conn = new mysqli('localhost','root','','testingdb');
if ($conn->connect_error) {
    die('Error : ('. $conn->connect_errno .') '. $conn->connect_error);
}
?>

Related Post