phpjqueryajax

GET request using jquery AJAX to a php backend - returns entire page of php code


I'm learning the basics of PHP and am trying to create the most basic PHP backend possible, with a JS/jQuery frontend. My current problem is that a GET request does not execute the .php file, like I was expecting, but instead returns a whole page.

I've tried many jQuery and PHP scripts based on tutorials and stack overflow posts, and the current configuration is based on this post here.

I have read some other StackOverflow posts about this issue here, here, and here but couldn't get those solutions to work, or didn't understand the answer.

Here's my setup: I have an index.html page that will render the results of my jQuery AJAX request & a data.json.php page, where I would like a basic response to be sent from. These files are in the same directory.

--- jquery.js ---

$(function () {

    $.ajax({
        url: "data.json.php",
        success: function(result){
           alert(result);
        }
     });
});

---data.json.php---

<?php
  header('Content-Type: application/json');
  $output = "hello"
  echo json_encode($output); 
?>

I am using the live server addon to render the html and I have started the php server through the command php -S localhost:4000.

I do get an alert, but it's returning the contents of the .php file rather than executing it. I think that I may be misunderstanding how to start the PHP server correctly, the proper way of running a PHP script, or how the flow of information goes.

Any help, tips, or resources would be greatly appreciated. Thanks!


Solution

    1. ./test
    2. ./test/test.php
    3. ./test/test.html
    4. #cd test
    5. #php -S localhost:4000

    test.php content:

    <?php
      header('Content-Type: application/json');
      $output = "hello";
      echo json_encode($output); 
    

    test.html content:

    <html>
        <head>
        <script src="https://code.jquery.com/jquery-3.6.2.min.js"></script>
        </head>
        <body>
    
        <script>
    $(function () {
    
        $.ajax({
            url: "http://localhost:4000/test.php",
            success: function(result){
               alert(result);
            }
         });
    });
        </script>
        </body>
    </html>
    

    how to and test video