0

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!

Alex G.
  • 3
  • 2
  • If you use apache, you need the php apache module. If you use nginx, you need fpm. – svgta Dec 20 '22 at 17:42
  • It works for me. Your problem may be from somewhere else. – Atena Dadkhah Dec 20 '22 at 17:57
  • Thanks for the heads up svgta - your comment took me down a long rabbit hole about php_mod and I learned a bunch! Eventually I got it to work - the error lay in my url - it needs to be an absolute path starting with 'localhost:400xxxx' apparently. Thanks again for the input though! – Alex G. Dec 21 '22 at 02:38

1 Answers1

0
  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

  • This worked! I appreciate the detailed layout and the test video! I wish I had enough reputation to upvote this. It looks like the relative path I used is incorrect, and the one using 'localhost:4000:xxxx' must be used. Cheers! – Alex G. Dec 21 '22 at 02:37