I tried to pass value of name from .js file to PHP using POST method. But when I start the code, there isn´t any alert.
In console is only: Uncaught ReferenceError: $ is not defined
Do you know what could be improved?
<html>
<body>
<head>
<script type="text/javascript">
const name = "asdasd";
$.ajax({
url: "TargetFile.php",
method: "POST",
data: {
name
},
success: function (result) {
alert(result);
},
error: function (error) {
alert("Error " + error.status);
}
})
</script>
</head>
</body>
</html>
<?php
$name = $_POST['name'];
if (empty($name)) {
echo "Name is empty";
} else {
echo $name;
}
}
?>
2
Answers
You need to load the jQuery lib before using it. And also the head tag should be outside of the body tag.
As a simple, single page, test script that will send a POST request to the server which sends the response for the ajax callback. As others have stated – you should include the jQuery library but you need to change the payload to a valid object literal. The POST request expects
name=value
pairs as per below.Using 2 separate scripts, one that makes the request (index.html) and the other that processes the request and sends the response (targetfile.php)
index.html
targetfile.php
Both scripts in same directory, request is made OK and console message is displayed ( removed annoying
alert
)