Two languages, several environments
PHP commonly runs on a server before the response reaches a visitor. Browser JavaScript runs after the browser loads a page and can react to clicks, change the Document Object Model (DOM) and request new data. JavaScript can also run outside a browser through Node.js and other server runtimes. “PHP is backend, JavaScript is frontend” describes a common arrangement, not a rule about where JavaScript can run.
Both languages can create HTTP responses in a suitable server environment. PHP can return HTML, JSON or other data. Browser JavaScript can update the visible page, but it cannot safely hold server secrets or connect directly to a private database with privileged credentials.
What each part commonly does
Think about the environment and the job, not just the language name. A form can submit to a PHP endpoint for validation and storage; browser JavaScript can also validate the interface and send the form using fetch. Server-side validation still matters because a client can bypass browser checks.
| Task | PHP on a server | Browser JavaScript | JavaScript with Node.js |
|---|---|---|---|
| Generate HTML | Can build an HTML response before it is sent. | Can create or change DOM elements after the page loads. | Can generate HTML in a server application. |
| Handle a form | Reads submitted request data and validates it on the server. | Can read fields, show feedback and submit without a full reload. | Can handle and validate a submitted request on a server. |
| Call an API | Can make a server-to-server request or return an API response. | Can call an allowed API using fetch, subject to browser security rules. | Can call or provide APIs on a server. |
| Use a private database | Can connect using server-held credentials and an appropriate extension. | Must normally call a server API; credentials must not be shipped to the browser. | Can connect using server-held credentials and appropriate libraries. |
| Code sent to visitor | PHP source normally stays on a properly configured server; output is sent. | Scripts downloaded by the browser are visible to the visitor. | Server-side source normally stays on the server; output is sent. |
A practical page that uses both
Save the example below as index.php and serve its folder with a PHP-capable local server. On the first request, PHP outputs the HTML page. When the visitor clicks the button, browser JavaScript calls the same URL with ?format=json. PHP detects that query value and returns JSON instead of HTML. JavaScript reads the response and changes the text on screen.
The early JSON branch calls exit, so the HTML below it is not accidentally appended to the JSON response. The code uses textContent, so response text is inserted as text rather than interpreted as HTML. In a real application, the data could come from a database after server-side validation. A failed request is caught and shown as a friendly message.
Local development, from the example folder
php -S 127.0.0.1:8000When would you use each?
Use server code when it needs protected credentials, trusted validation, database access or an initial response. Use browser JavaScript for interactions such as updating a result after a click. Node.js is an alternative server runtime when a team chooses JavaScript for that role. Many products use PHP and browser JavaScript together; they solve different parts of the same request.
Neither language guarantees secure code. Validate on the server, avoid exposing secrets to the browser, and check that API endpoints send the intended status and content type.
Syntax
<?php echo "Hello from PHP"; ?>
<script>console.log("Hello from JavaScript");</script>Examples
PHP serves the page; browser JavaScript requests fresh data
One index.php file demonstrates an HTML response and a JSON response from the same endpoint.
<?php
if (($_GET['format'] ?? '') === 'json') {
header('Content-Type: application/json; charset=utf-8');
echo json_encode(['message' => 'Your next lesson is PHP requests.'], JSON_THROW_ON_ERROR);
exit;
}
?>
<!doctype html>
<html lang="en">
<head><meta charset="UTF-8"><title>Next lesson</title></head>
<body>
<button id="load" type="button">Show next lesson</button>
<p id="result" aria-live="polite">Choose the button to load a lesson.</p>
<script>
document.querySelector('#load').addEventListener('click', async () => {
const result = document.querySelector('#result');
try {
const response = await fetch('?format=json');
if (!response.ok) throw new Error('Request failed');
const data = await response.json();
result.textContent = data.message;
} catch (error) {
result.textContent = 'Could not load the lesson. Please try again.';
}
});
</script>
</body>
</html>- The PHP condition detects format=json and sends a JSON response with the correct Content-Type. exit stops execution before the HTML template begins.
- Without that query value, PHP returns HTML. The browser renders the button and then executes the script in the page.
- When clicked, fetch makes another HTTP request. The script checks its status, parses JSON and assigns the message through textContent. catch handles network, HTTP and parsing failures without an unhandled rejection.
- This is the same PHP endpoint serving two different representations. In a real service, protect and validate any data that a visitor can submit.
Best practices
- Keep database credentials and other secrets in server-side code and configuration.
- Validate form and API inputs on the server even when the browser also checks them.
- Check HTTP status and handle rejected browser requests before updating the interface.
Runtime & versions
PHP runtime on a server or CLI. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
PHP Manual