Reputation: 49
I'm new to web development, especially PHP, jQuery, AJAX...
I'm trying to make the user enter a name, then the index.html sends it to a php file, the php file saves it to a file of names and changes a div element with the id of status on the website. I can't figure out the problem, the div element's inner HTML stays "processing..."
index.html
<html>
<head>
<script>
function ajax_post(){
document.getElementById("status").innerHTML = "processing...";
$.post("server.php", { username: $("#userName").val() }, function(data) {
$("#status").html(data);
})
}
</script>
</head>
<body>
<h2>Ajax Post to PHP and Get Return Data</h2>
Username: <input id="userName" name="userName" type="text"> <br><br>
<input name="myBtn" type="submit" value="Check" onclick="ajax_post();"> <br><br>
<div id="status"></div>
</body>
</html>
server.php
<?php
if(!empty($_POST['username'])){
$data = $_POST['username'];
echo 'You are now registered,' . $data;
$fname = "save.text";
$file = fopen($fname, 'a');
fwrite($file, $data . "\n");
fclose($file);
}
?>
I'm assuming my $.post syntax is wrong, but I don't really understand it.
Upvotes: 0
Views: 4489
Reputation: 11808
Try this I have executed this code and it worked for me.
Index.html
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript">
function ajax_post(){
document.getElementById("status").innerHTML = "processing...";
console.log($("#userName").val());
$.post("server.php", { username: $("#userName").val() }, function(data) {
$("#status").html(data);
})
}
</script>
</head>
<body>
<h2>Ajax Post to PHP and Get Return Data</h2>
Username: <input id="userName" name="userName" type="text"> <br><br>
<input name="myBtn" type="submit" value="Check" onclick="ajax_post()"> <br><br>
<div id="status"></div>
</body>
</html>
Server.php
<?php
if(!empty($_POST['username'])){
$data = $_POST['username'];
echo 'You are now registered,' . $data;
$fname = "save.text";
$file = fopen($fname, 'a');
fwrite($file, $data . "\n");
fclose($file);
}
?>
Upvotes: 3