0

我目前正在尝试在用户单击其他地方时更新文本区域。我不精通 AJAX 和 Jquery。但是,该脚本似乎没有更新数据库中的行。

Jquery/文本区域:

<textarea id="<?php echo $item_id; ?>_textarea"><?php echo $notes; ?></textarea>
    <script type="text/javascript">
    $('<?php echo $item_id; ?>_textarea').on('blur',function () {
var notesVal = $(this).val(), id = $(this).data('id');        
var itemVal = <?php echo $item_id; ?>;
$.ajax({
     type: "POST",
     url: "updateNotes.php",
     data: {notes:notesVal , id:id, itemId:itemVal},
     success: function(msg) {
         $('#'+id).html(msg);
     }
 })
});
</script>

updateNotes.php:

<?php

include('db_connect.php');
include('order_functions.php');



$email = $_SESSION['username'];

$cartId = getcartid($mysqli, $email);
$notes = $_POST['notes'];
$itemID = $_POST['itemId'];


$query = "UPDATE `rel` SET `notes` = '$notes' WHERE `cart_id` = '$cartId' && `id_item` = '$itemID'";
$result = $mysqli->query($query) or die($mysqli->error.__LINE__);

if(result) {
return "Notes Updated";

} ?>

4

1 回答 1

2

您忘记了 php 代码中最后一个 if 语句中的 $ 并且您应该使用“echo”(或类似的)而不是“return”,因为您不在函数中。

<?php

include('db_connect.php');
include('order_functions.php');

$email = $_SESSION['username'];

$cartId = getcartid($mysqli, $email);
$notes = $_POST['notes'];
$itemID = $_POST['itemId'];


$query = "UPDATE `rel` SET `notes` = '$notes' WHERE `cart_id` = '$cartId' && `id_item` = '$itemID'";
$result = $mysqli->query($query) or die($mysqli->error.__LINE__);

if($result) {
    echo "Notes Updated";
}
?>

您的 html/javascript-code 有点错误。这就是我猜你希望它工作的方式:

<div id="<?php echo $item_id; ?>_div">
    <textarea id="<?php echo $item_id; ?>_textarea" data-id="<?php echo $item_id; ?>"><?php echo htmlentities($notes); ?></textarea>
</div>

$('#<?php echo $item_id; ?>_textarea').on('blur', function () { // don't forget # to select by id

    var id = $(this).data('id'); // Get the id-data-attribute
    var val = $(this).val();
    $.ajax({
        type: "POST",
        url: "updateNotes.php",
        data: {
            notes: val, // value of the textarea we are hooking the blur-event to
            itemId: id // Id of the item stored on the data-id
        },
        success: function (msg) {
            $('#' + id + '_div').html(msg); //Changes the textarea to the text sent by the server
        }
    });
});

祝你好运

于 2013-02-03T23:37:08.590 回答