2015-07-02 07:29

使用Ajax / jQuery(内联文本编辑)在<div>标记内检索数据

  • php
  • ajax
  • jquery

I've been working on this problem for a few hours, but there is some mistake somewhere in the javascript file (I believe), but I can't figure it out.

Right now the alert(msg) gives me an Undefined index: headline/text in editPost.php.

The following PHP code is in a file profile.php. I want to retrieve the data within the <div>I want this data</div> tags (i.e. I want to retrieve the data in $row['headline'] and $row['text'].

while ($row = mysqli_fetch_array ($resultPost, MYSQLI_ASSOC)) {
    echo '<h1><div contenteditable="true" data-headline="headline" data-id=' . $row['id'] . '>' . $row['headline'] . '</div></h1>';
    echo '<p><div contenteditable="true" data-text="text" data-id=' . $row['id'] . '>' . $row['text'] . '</div></p>';

This is how I try to retrieve the data (seperate .js file):

$(document).ready(function() {
$('body').on('blur', "div[contenteditable=true]", function() {

    var headline = $("div[data-name='headline']:visible").text();
    var text = $("div[data-name='text']:visible").text();
        type: 'POST',
        url: 'editPost.php',
        data: {
            content: $.trim($(this).text()),
            id: $(this).data('id'),
            headline: $(this).data(headline),
            text: $(this).data(text),
        success: function(msg) {

The function above then posts the data to editPost.php, which submits the data to a database. Below is a snippet of how I do that:

$headline = $_POST['headline'];
$text = $_POST['text'];
$id = $_POST['id'];
$sql = "UPDATE blogpost SET headline = '$headline', text = '$text', edit_time = NOW(6) WHERE id = '$id'";

In the current state, when the data is sent to the database, it finds the correct table (using the id), and inserts "" in both the headline and text fields, but it updates the edit_time correctly.

Thank you!

  • 点赞
  • 回答
  • 收藏
  • 复制链接分享