简体   繁体   English

用户输入文本后,如何使用 AJAX 更新我的数据库?

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

I have created a table which has a column for notes, the notes are from a MySQL table and displayed.我创建了一个表,其中有一列用于注释,注释来自 MySQL 表并显示。 When the user clicks on the notes it'll convert to an input box and allow them to edit the text.当用户单击注释时,它会转换为输入框并允许他们编辑文本。 How would I then update my table with the new data that's been entered, so when the user clicks off of the input box they've just entered text in, it'll update the notes column using the correct row ID然后我将如何使用输入的新数据更新我的表格,因此当用户单击他们刚刚输入文本的输入框时,它将使用正确的行 ID 更新备注列

Here is my code at the moment...这是我目前的代码......

Javascript 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 HTML

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

PHP 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";
        }
    }
} 
?>

Lets me modify your code further with an alternative js and updated html in order to capture:让我使用替代 js 和更新的 html 进一步修改您的代码以捕获:

  1. unique ID of your content.您的内容的唯一 ID assuming each record has to have a unique id column for easy update假设每条记录都必须有一个唯一的 id 列以便于更新
  2. the content being edited正在编辑的内容

Here is a sample HTML这是一个示例 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> 

Here is the JavaScript that will pass the two variables to your PHP page to update on db这是将两个变量传递给您的 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>

and now Your PHP sample page to update your data现在你的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.

相关问题 如何使用ajax POST方法将日历值更新到数据库? - How can I make my calendar value update to my database with my ajax POST method ? 如何使用javascript通过AJAX调用访问数据库? - How can I hit my database with an AJAX call using javascript? 使用$ .ajax发布用户输入的文本,如何在data属性中传递文本内容? - Posting user entered text using $.ajax, how to pass text content in the data property? AngularJS + Bootstrap-验证文本框-仅在用户输入一些数据后如何显示验证反馈? - AngularJS + Bootstrap - Validating Text Box - how to show validation feedback only after the user has entered some data? 更新通知数后,此框将有额外的空间。 我该如何删除? - after i update my notification count, the box has an extra space. how can i remove this? 如何计算用户在文本表单中输入的特定符号的数量 - How to count the amount of specifc symbols that a user has entered in a text form 如何根据用户输入的内容动态添加更多文本字段? - How can I dynamically add more textfields according to what the user has entered? 如何使用ajax更新表? - How can I update a table using ajax? 创建地图框地图后,如何更新GeoJSON? - How can I update GeoJSON on my mapbox map after it has been created? 拖放后如何使用javascript / ajax更新数据库? - How to update database after drag and drop using javascript/ajax?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM