Вопрос

i'm trying to do a simple php chat application that receives data from the client via ajax and writes that data to a text file for storage. But i keep getting anundefined index error on the lines where i try to get the 'name' and the 'message' after parsing the json.

this is the chat.php file:

<?php
    if (isset($_POST['data']))
    {        
        $data = $_POST['data'];
        $chat = json_decode($data);
        $name = $chat->name;
        $msg = $chat->msg;

        $file = "chat.txt";
        $fh = fopen($file, 'w') or die("Sorry, could not open the file.");

        if (fwrite($fh, $name + ":" + $msg))
        {
            $response = json_encode(array('exists' => true));
        } else {
            $response = json_encode(array('exists' => false));
        }
        fclose($fh);
        echo "<script type='text/javascript'>alert ('" + $name + $msg + "')</script>"
    }
?>

this is the javascript:

<script type="text/javascript">
            $(document).ready(function() {
                $("#btnPost").click(function() {
                    var msg = $("#chat-input").val();
                    if (msg.length == 0)
                    {
                        alert ("Enter a message first!");
                        return;
                    }
                    var name = $("#name-input").val();
                    var chat = $(".chat-box").html();
                    $(".chat-box").html(chat + "<br /><div class='bubble'>" + msg + "</div>");

                    var data = {
                        Name : name,
                        Message : msg
                    };
                    $.ajax({
                        type: "POST",
                        url: "chat.php",
                        data: {
                            data: JSON.stringify(data)
                        },
                        dataType: "json",
                        success: function(response) {
                            // display chat data stored in text file 
                        }
                    });
                });
            });
        </script>
Это было полезно?

Решение

Probably your $chat variable

$chat = json_decode($data);

Does not contains these fields but Name and Message as you delcared here:

var data = {
  Name : name,
  Message : msg
}

name and msg are valuse and Field names are Name and Message.

Please try to print_r($chat) to see what it contains.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top