Despite the long hours of googling, Ajax does not connect to any. I simplified the code to the maximum.

This is the main index.php file. Jquery, as you can see, connected:

 <!DOCTYPE html> <html> <head> ... <!--js--> <script src="js/jquery-3.0.0.min.js"></script> <script src="js/CreateLayout.js" type="text/javascript"></script> </head> <body> <?php echo 'TestResult '. $_POST['testData']; ?> </body> 

The Ajax request itself is in an external file ( js/ directory):

 $.ajax({ type: 'POST', url: 'index.php', data: 'testData=test' }); 

I use NetBeans in conjunction with OpenServer, landing page address; displayed in the browser - http://testproject/index.php . I admit that it may be wrong to write the address in the request; I tried both http://testproject/index.php , and testproject/index.php , but nothing changes.

What else is worth trying?

  • Lakremon's answer is not correct. Why did you mark it as a solution? - RostD
  • I myself was mistaken in accepting the answer for the correct one; I beg your pardon. (a consequence of 9 hours of work, half of which is the search for an answer to this question). - Bokov Gleb

2 answers 2

At the time when the file is being rendered index.php POST data does not exist. In your case, they appear only after the html response has been generated, transferred to the client (in the browser), and only then the POST data has been sent.

Naturally, it is too late to display them. Do not forget that JavaScript is executed on the client side, in contrast to PHP.

Please try to understand and test the following code:

index.php file

 <?php // Проверяем, есть ли POST данные "testData" if(isset($_POST['testData'])){ echo "Ура, данные 'testData' пришли: ".$_POST['testData'].""; exit(); } ?> <html> <head></head> <body> <p id='postData'>POST данных не обнаружено</p> <input type="submit" id="submit" value ="Отправить testData"> </body> <script src="js/jquery-3.0.0.min.js"></script> <script src="js/CreateLayout.js" type="text/javascript"></script> </html> 

file CreateLayout.js

 // При клике отправляем post данные $("#submit").click(function(){ $.ajax({ type: 'POST', url: 'index.php', data: 'testData=test', success: function(data){ // В случае успешного ответа сервера вставляем ответ сервера в тег <p> $("#postData").text(data); } }); }); 
  • 2
    Ok, everything works. Thank you very much for the constructive answer with an explanation, and once again I apologize for the mistake in choosing the winner. - Bokov Gleb
  • Always happy to help. Thank you too. - RostD

So try:

 $.ajax({ method: 'POST', url: '/index.php', data: { testData:"test" } }); 
  • Ah, no, unfortunately I was wrong. Your solution doesn't work either. - Bokov Gleb