簡體   English   中英

Ajax調用php,獲取mysql數據作為數組並在JS函數中使用

[英]Ajax call to php, get mysql data as array and use in JS function

我希望對 PHP 腳本進行 ajax 調用以從 MySQL 獲取數據,創建一個 json 數組並將其傳遞回 ajax 調用的成功函數,然后我將在其中將其用作 JavaScript 函數的參數。

這是我的ajax調用,

    $('button[name="message"]').click(function() {
    var $row = $(this).closest("tr");    // Find the row
    var $tenant_id = $row.find(".col-md-1 id").text(); // Find the tenants ID
    var $landlord_id = "<?php echo $id; ?>"
    $.ajax({
        url : "./message.php",
        type : "POST",
        async : false,
        data: {
        landlord_id: $landlord_id,
        tenant_id : $tenant_id
        },
        success: function(data){
            console.log(data);
            var messages = data;
            insertChat(messages.sender_id, messages.body, messages.timestamp);
        }
        })
});

這是我的 PHP 文件,

    <?php
    session_start();
    require_once('../dbconnect.php');
    // update tenants table to show deposit returned
    if(isset($_POST['tenant_id'])){
    $tenant_id = $_POST['tenant_id'];
    $landlord_id = $_POST['landlord_id'];

    $sql = "SELECT * from messages  WHERE messages.sender_id OR messages.receiver_id = '$tenant_id' AND messages.sender_id OR messages.receiver_id = '$landlord_id'";
    $result = mysqli_query($conn, $sql) or die("Error in Selecting " . mysqli_error($conn));

    //create an array
    $messages = array();
    while($row =mysqli_fetch_assoc($result))
    {
        $messages[] = $row;
    }
    echo json_encode($messages);

}
    ?>

如果有人有教程或各個部分的鏈接,那就太棒了。 我什至不知道我上面概述的過程是否正確。 如果有人能告訴我解決此問題的正確方法,那將有很大幫助!

謝謝

只需調整您的 javascript 方面的幾件事(我不會解釋您遇到的 php sql 注入問題...但請研究preparebind_paramexecute ):

  1. 由於您正在從 php (json_encoded) 返回$messages的數組,因此您需要在success處理程序中循環這些信息。

  2. dataType: 'JSON'添加到您的選項中,因此它明確期望從 php 返回 json。

  3. 你少了幾個分號;)

添加到您的代碼的調整:

$('button[name="message"]').click(function() {
    var $row        = $(this).closest("tr");
    var tenant_id   = $row.find(".col-md-1 id").text();
    var landlord_id = "<?php echo $id; ?>";
    $.ajax({
        url : "./message.php",
        type : "POST",
        data: {
            landlord_id: landlord_id,
            tenant_id : tenant_id
        },
        dataType: 'JSON',
        success: function(data){
            console.log(data);
            if (typeof data !== undefined) {
                for(var i = 0; i < data.length; i++) {
                    insertChat(data[i].sender_id, data[i].body, data[i].timestamp);
                }
            }
        }
    });
});

暫無
暫無

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

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