Reputation: 70
Im looking to fix following AJAX POST method:
index.php:
<!DOCTYPE html>
<html>
<head>
<title>Document</title>
<script src="jquery.min.js"></script>
<script src="main.js"></script>
</head>
<body>
<?php echo($_POST['send']);?>
</body>
</html>
main.js
$.ajax({
type: 'POST',
url: 'index.php', // both files are in root level
data: {send: "string"}
});
In dev tool's network tab every request seems to be in right order and the response shows "string" is included in the body. The question is: Why I'm getting: "Undefined index: send"??
I'm using Apache/2.4.37 (x64) OpenSSL/1.1.1 PHP/7.2.12, jQuery/3.3.1 (just in case there has been some syntax updates, which I'm not aware of).
Upvotes: 0
Views: 72
Reputation: 347
This is also the page which you loaded in the GET requests visible in developer tools ? You are loading it as a GET with no POST parameters - thats why it is undefined, but when you send correct POST request it echoes correct data. If u just want to fix this error, in other word display $_POST['send'] only on POST request do:
<!DOCTYPE html>
<html>
<head>
<title>Document</title>
<script src="jquery.min.js"></script>
<script src="main.js"></script>
</head>
<body>
<?php if(!empty($_POST)) echo($_POST['send']);?>
</body>
</html>
Edit: this will only check if its $_POST request, not necesarily if 'send' is set. For that use
if(!empty($_POST['send']))
Upvotes: 0
Reputation: 944172
This is the order of events:
index.php
$_POST['send']
is not setdone()
handler.You should rewrite your code so you have two different URLs.
You could also use one URL and an if/else
based on if the request is POST or GET, but that wouldn't be RESTful or a sensible seperation of concerns.
Note that your code is vulnerable to XSS. User input needs escaping before being inserted into an HTML document!.
Upvotes: 2