jQuery AJAX call to PHP script returns raw PHP source code instead of executing

I’m working on a simple web application that utilizes JavaScript for the frontend and PHP for the backend. Unfortunately, whenever I attempt to make an AJAX request to my PHP file, it ends up returning the raw source code of the PHP file itself instead of executing it and sending me the expected output.

Here’s the JavaScript code I have:

$(document).ready(function() {
    $.get({
        url: "api.php",
        dataType: "json",
        success: function(response) {
            console.log(response);
        },
        error: function() {
            console.log("Request failed");
        }
    });
});

And here is my PHP file (api.php):

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

I’m currently running a local PHP server with the command php -S localhost:8000 and I’m using the Live Server extension for the HTML file. Both of these files are located in the same directory. Instead of receiving “Hello World” as JSON, the AJAX request is returning the complete PHP code as plain text. Could you please help me figure out what might be wrong with either my server configuration or the structure of my code?

You’ve got conflicting server environments. Live Server is serving your HTML file from one port while your PHP server runs on localhost:8000. When your AJAX request tries to fetch api.php, it’s grabbing the file through Live Server’s static serving instead of the PHP interpreter. Your PHP server at localhost:8000 can’t handle the request because your HTML comes from a different domain or port. Fix this by putting your HTML file in the same directory as your PHP files and accessing everything through localhost:8000 only. That way all requests go through the PHP server and your scripts will execute properly to generate JSON responses.

Interesting issue! Are you opening your HTML file through Live Server extension or localhost:8000? If you’re using Live Server, that’s probably causing a cross-origin problem. What happens when you open everything through the PHP server instead?

your setup’s mixed up. the html file needs to run on localhost:8000 where yr php server is running, not on live server. open the html file from the php server and that’ll fix it.