Home > Back-end >  How to send the value from the form to the database via ajax and return it to the page?
How to send the value from the form to the database via ajax and return it to the page?

Time:03-06

I welcome everyone, please tell me how I can send a new description from the Ajax form to the database? And bring it back to display on the page?

When you click on the "submit" button, an ajax request is sent to the send_description function. In this function, as I understand it, you need to write the input value to the database and return it back to the page

screenshot from the pagee

<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport"
        content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Ajax</title>
  <script src="https://code.jquery.com/jquery-3.6.0.js" integrity="sha256-H K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" crossorigin="anonymous"></script>
</head>
<body>

    <div  style="width: 400px; border: 1px solid red; padding: 20px; margin-bottom: 50px;">

        <form method="post" id="form">
            <span>Current description: <textarea name="new_description"></textarea></span>
            <button type="submit">Save</button>
        </form>

    </div>

   <div  style="width: 400px; border: 1px solid green; padding: 20px;">
        <span>Description: <b>Lorem Ipsum is simply dummy text of the printing and typesetting industry. </b></span>
   </div>


   <script>
    $(function(){
        $('form').on('submit', function(e){
            e.preventDefault();
            var formData = new FormData(document.getElementById("form"));
            $.ajax({
                url: 'index/get_description',
                data: formData,
                method: 'POST',
                dataType: 'json',
                processData: false,
                contentType: false,
                success: function(data){
                    console.log(data);
                }
            });
            return false;
        });
    });
   </script>

</body>
</html>

<?php
// connect mysql
$db = new mysqli('localhost', 'root', '', 'test_ajax');

if ($db -> connect_errno) {
    echo 'missing database connection!';
} else {
    echo 'successfully connected to the database';
}

// function
function send_description() {
    $sql = 'SELECT * FROM store';
    // 1) Записать новое описание в таблицу
    // 1) Write a new description to the table

    // 2) Вернуть наше новое описание чтобы отобразить на странице
    // 2) Return our new description to display on the page
}
?>

In the database, the "store" table, the "description" column screenshot from the database

CodePudding user response:

It can be done like this:

You form

<form method="post" id="form">
   <span>Current description:
     <textarea name="description"></textarea>
   </span> 
  <button type="submit">Save</button>
</form>

You js script

 <script>
    $(function(){
        $('#form').on('submit', function(e){
            e.preventDefault();
            
            $.ajax({
                url: 'index/get_description', // you url php script
                data: $(this).serialize(),
                method: 'POST',
                dataType: 'json',
                success: function(data){
                    console.log(data);
                }
            });
            return false;
        });
    });
   </script>

You php code

<?php
$db = new mysqli('localhost', 'root', '', 'test_ajax');

if (!$db->connect_errno) {
    echo 'error connected to the database';
    die();
}  

if ($_SERVER['REQUEST_METHOD'] == 'POST'){
   $db->query("INSERT INTO store SET description = '{$_POST['description']}'");  // insert in table 
   $result = $db->query("SELECT * FROM store");  // get from  table
   $result = $result->fetch_row(); // get array from result
   echo json_encoder($result);  // retun data for ajax
   die();
}
  • Related