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:
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 ""
}
?>
this is the 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 + "
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
}
});
});
});