Home » Php » php – How to insert data to a table using a jquery

php – How to insert data to a table using a jquery

Posted by: admin February 25, 2020 Leave a comment

Questions:

I need to insert data to a table, using a jquery function. I need to put the sql query within a function call buttonClick() and then need to call that function once the Save button clicks.

As I am new to this I have already tried an example as follows and it works. Table name is user

======index.php===========

// Starting session
session_start();

// Storing session data
$_SESSION["firstname"] = "Peter";
 ?>

<!DOCTYPE html>
<html>
<head>
    <title>POST JQUERY</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
    <form>
        <label>Name</label>
        <input type="text" name="uname" id="name">
        <label>City</label>
        <input type="text" name="city" id="city">
        <button type="button" name="btn" id="submit">Save</button>
    </form>


<p id="out">----</p>

    <script>
        $(document).ready(function(){
            $("#submit").on('click', function(){
                // alert($_SESSION["firstname"]);
                var na = $("#name").val();
                var ci = $("#city").val();
                $.post("save.php", {
                    name: na,
                    city: ci

                },function(data){
                        // $("#out").html(data);
                });
            });
        });

    </script>  
</body>
</html>

========save.php========

<?php 
            $con = new mysqli("localhost", "root", "", "testphp");

            $sql = "INSERT INTO user (name, city) values ('{$_POST["name"]}' , '{$_POST["city"]}')";
        if ($con->query($sql)) {
            echo "Data Saved";
        }else{
            echo "Error";
        }

  ?>

But what I actually want is, I have a Table.model php file which contains few different functions to insert data to various tables. There I want to make a function call buttonClick(). Within this function I need to put this sql query which is in save.php and I want to call this buttonClick() function once user clicks on Save button.
Therefore my buttonClick() need to be looked something like this in Table.model file.

function buttonClick(){
            // $con = new mysqli("localhost", "root", "", "testphp");
         // $sql = "INSERT INTO user (name, city) values ('{$_POST["name"]}' , '{$_POST["city"]}')";
            $sql = "INSERT INTO user (name, city) values ('{$_POST["name"]}' , '{$_POST["city"]}')";
        if ($con->query($sql)) {
            echo "Data Saved";
        }else{
            echo "Error";
        }
        }

Can you please tell me how can I call this buttonClick function , instead of save.php to insert data to table ? or is there another way to this (I code php mvc).
Thank you

How to&Answers: