911madza
911madza

Reputation: 70

AJAX POST ---> Unidetified index?

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"??

Screenshot of dev console

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

Answers (2)

matri70boss
matri70boss

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

Quentin
Quentin

Reputation: 944172

This is the order of events:

  1. You type the URL into the address bar which causes the browser to make a GET request to index.php
  2. This runs the PHP which gives the browser an instruction to load two scripts, and an error message because it was a GET request so $_POST['send'] is not set
  3. The JavaScript causes the browser to make a second request to the same URL, this time it is a POST request.
  4. The PHP runs again and gives different output (the script elements and the echoed input).
  5. The browser makes the second response available to your JavaScript. jQuery processes it, but then it falls out of scope and is discarded because you have no done() handler.

You should rewrite your code so you have two different URLs.

  • One URL should be for the HTML document
  • One URL should be for the web service which you access with JavaScript

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

Related Questions