Reputation: 397
What I want to do is return the echo value of "addTemplate.php" when I send it a form value via a http POST request. However, when I send the request, absolutely nothing happens.
What should I do?
Here's my JS
$(document).ready(function() {
$("#sendTemplate").on("submit", function(event) {
var template = $("#template").val();
event.preventDefault();
$.ajax({method: "POST", url: "addTemplate.php", data: template, success: function(result) {
alert(result);
});
});
});
Here's my html
<!DOCTYPE html>
<html>
<head>
<title>Admin</title>
<link type="text/css" rel="stylesheet" href="stylesheet.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="adminscript.js"></script>
</head>
<body>
<h1>Admin/Developer page</h1>
<form id="sendTemplate">
<p>Enter a new template for the server: (Enter #word to enter a placeholder for words)</p><input type="text" name="template" id="template">
<input type="submit" name="submit">
</form>
<div id='success'></div>
<br><br><br><br>
<form action="turing.html">
<button type="submit">Home</button>
</form>
</body>
</html>
And here is my php
$template = $_POST["template"];
if(strlen($template) <= 100 && strpos($template, "#word")) {
file_put_contents("templates.txt", "\r\n" . $template, FILE_APPEND);
header("Location: http://community.dur.ac.uk/h.j.g.baum/admin.html");
echo "True";
}
else {
echo "False";
}
What's wrong with my code (most likely in the JavaScript) and how can I improve it?
Thanks
Upvotes: 0
Views: 43
Reputation: 717
Just change your js to
$(document).ready(function() {
$("#sendTemplate").on("submit", function(event) {
var template = $("#sendTemplate").serialize();
$.ajax({method: "POST", url: "test.php", data: template, success: function(result) {
alert(result);
}});
event.preventDefault();
});
And
<form id="sendTemplate">
to
<form id="sendTemplate" method="POST">
This is the right way to get the form data and pass it to your php script
Upvotes: 0
Reputation: 16117
Replace ajax data:
data: template,
With:
data: "template="+template,
Issue:
You are using $_POST['template'] for getting values and didn't define in ajax data.
Upvotes: 1
Reputation: 12132
id do this:
$(document).ready(function () {
$("#sendTemplate").on("submit", function () {
$.ajax({
method: "POST",
url: "addTemplate.php",
data: $(this).serialize(),
success: function (result) {
alert(result);
});
return false;
});
});
Upvotes: 0
Reputation: 5109
I think you're missing a closing curly on the Ajax success function
$(document).ready(function() {
$("#sendTemplate").on("submit", function(event) {
var template = $("#template").val();
event.preventDefault();
$.ajax({method: "POST", url: "addTemplate.php", data: template, success: function(result) {
alert(result);
}});
});
});
Upvotes: 0