簡體   English   中英

用戶輸入文本后,如何使用 AJAX 更新我的數據庫?

[英]How can I update my Database using AJAX after the user has entered text?

我創建了一個表,其中有一列用於注釋,注釋來自 MySQL 表並顯示。 當用戶單擊注釋時,它會轉換為輸入框並允許他們編輯文本。 然后我將如何使用輸入的新數據更新我的表格,因此當用戶單擊他們剛剛輸入文本的輸入框時,它將使用正確的行 ID 更新備注列

這是我目前的代碼......

Javascript

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-beta1/jquery.min.js"></script>
    <script>
    $( document ).ready(function() {
    $(function(){
      $("#loading").hide();
      //acknowledgement message
      var message_status = $("#status");
      $("td[contenteditable=true]").blur(function(){
          var field_id = $(this).attr("id") ;
          var value = $(this).text() ;
          $.post('scripts/update-jobdiary-notes.php' , field_id + "=" + value, function(data){ //change this to your liveupdatingpage.php
              if(data != '')
              {
                  message_status.show();
                  message_status.text(data);
                  //hide the message
                  setTimeout(function(){message_status.hide()},1000);
              }
          });
      });
    });
    });
    </script>

HTML

<td data-editable contenteditable="true" id="note_text_db_column:<?php $note['notes_id']; ?>"><?= $note['notes_text']; ?></td>

PHP

//DATABASE CONNECTION
if(!empty($_POST))
{
    //database settings

    foreach($_POST as $field_name => $val)
    {
        //clean post values
        $field_id = strip_tags(trim($field_name));

        //from the fieldname:user_id we need to get user_id
        $split_data = explode(':', $field_id);
        $data_id = $split_data[1];
        $field_name = $split_data[0];
        if(!empty($data_id) && !empty($field_name) && !empty($val))
        {
            $stmt = $pdo->prepare("UPDATE ser_diarynotes SET notes_text = ? WHERE notes_id = ?"); //here just change name of your table and name of your unique_column
            $stmt->bind_param("si", $val, $data_id);
            $stmt->execute();
            $stmt->close();

            echo "Updated";
        } else {
            echo "Invalid Requests";
        }
    }
} 
?>

讓我使用替代 js 和更新的 html 進一步修改您的代碼以捕獲:

  1. 您的內容的唯一 ID 假設每條記錄都必須有一個唯一的 id 列以便於更新
  2. 正在編輯的內容

這是一個示例 HTML

<style>
#status { padding:10px; position:fixed; top:10px; border-radius:5px; z-index:10000000; background:#88C4FF; color:#000; font-weight:bold; font-size:12px; margin-bottom:10px; display:none; width:100%; }
#loading { padding:10px; position:absolute; top:10px; border-radius:5px; z-index:10000000; background:#F99; color:#000; font-weight:bold; font-size:12px; margin-bottom:10px; display:none; width:100%; }
</style>

 <div id="status"> </div>
 <div id="loading"></div>

<table id="tableID">
<tbody>
  <tr>
    <!--Edit below by specifying notes_text column and notes_unique_id-->
    <td data-editable contenteditable="true" id="note_text_db_column:<?php echo $note['notes_unique_id']; ?>"><?php echo $note['notes_text']; ?></td>
    </tr>
 </tbody>
</table> 

這是將兩個變量傳遞給您的 PHP 頁面以在 db 上更新的 JavaScript

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-beta1/jquery.min.js"></script>
 <script>
$( document ).ready(function() {
$(function(){
    $("#loading").hide();
    //acknowledgement message
    var message_status = $("#status");
    $("td[contenteditable=true]").blur(function(){
        var field_id = $(this).attr("id") ;
        var value = $(this).text() ;
        $.post('liveupdatingpage.php' , field_id + "=" + value, function(data){ //change this to your liveupdatingpage.php
            if(data != '')
            {
                message_status.show();
                message_status.text(data);
                //hide the message
                setTimeout(function(){message_status.hide()},1000);
            }
        });
    });
});
});
</script>

現在你的PHP示例頁面來更新你的數據

<?php  
//Your connection
$conn = new mysqli( 'localhost', 'db_user', 'user_password', 'your_db'); 

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $con->connect_error);
}

if(!empty($_POST))
{
    //database settings

    foreach($_POST as $field_name => $val)
    {
        //clean post values
        $field_id = strip_tags(trim($field_name));

        //from the fieldname:user_id we need to get user_id
        $split_data = explode(':', $field_id);
        $data_id = $split_data[1];
        $field_name = $split_data[0];
        if(!empty($data_id) && !empty($field_name) && !empty($val))
        {
            $stmt = $conn->prepare("UPDATE your_table SET $field_name = ? WHERE column_id = ?"); //here just change name of your table and name of your unique_column
            $stmt->bind_param("si", $val, $data_id);
            $stmt->execute();
            $stmt->close();

            echo "Updated";
        } else {
            echo "Invalid Requests";
        }
    }
} 

else {
    echo "Invalid Requests";
}
?>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM