I’m new to Web Development. I’m learning JavaScript
now(JQuery
) and I chose Simple Chat as a project to get started.
Unfortunately, I can’t figure out how to prevent the page from refreshing after a message is sent.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<title>Chat</title>
</head>
<body>
<h1>Chat room</h1>
<div id="status"></div>
<form id="send" class="ajax" action="action.php" method="POST">
<label for="fname">Type your message</label>
<input type="text" id="fname" name="myMessage">
<input id="upload" type="submit" name="myButton"value="Submit" />
</form>
<div id="result"></div>
<script>
$(document).ready(function () {
$("form").submit(function (event) {
var formData = {
name: $("#fname").val(),
};
var posting = $.post(url, {
name: $('#fname').val(),
});
/* So far, just listing whether the Form has managed to prevent its classic sending */
posting.done(function(data) {
$('#result').text('success');
});
$.ajax({
type: "POST",
url: "process.php",
data: formData,
dataType: "json",
encode: true,
}).done(function (data) {
console.log(data);
});
event.preventDefault();
});
});
</script>
</body>
</html>
PHP:
<?php
$path = 'messages.txt';
if (isset($_POST['myButton']) ) {
$fh = fopen($path,"a");
$string = $_POST['myMessage' ];
fwrite($fh,$string . PHP_EOL);
fclose($fh);
}
?>
I have created a text file messages.txt
, where I want to save newly created messages using Ajax.
I would like the newly added message to be displayed on the page below the chat( in the div
with id #result
)
2
Answers
Thanks everybody for advices, this is how I have solved it
To save data to file in PHP with this jquery ajax code, try this: