Intercepting Form Submission Before It Reaches PHP
In your current implementation, you have set up a standard HTML form that waits for a user to click the submit button. When that happens, the browser naturally dispatches an HTTP POST request containing the form fields (name, email, pass) to profile.php. However, your JavaScript logic attempts to intercept this event inside the onclick handler using myFunction().
The problem lies in how you are trying to communicate between the client-side script and the server. The function myFunction() successfully extracts the values from the DOM, but it stops right there. It does not initiate any network request. Consequently, when the browser finishes executing that JavaScript block, it proceeds with its default behavior: sending the POST request based on the form's action attribute (which defaults to the same file if not specified) or following a redirect if you were to use window.location.
To send data to a different PHP file (profile.php) directly from JavaScript without relying on the standard form submission cycle, you must explicitly create an AJAX request. This allows you to detach the data transmission from the visual page reload process.
Using Fetch for Modern Browsers
The most robust way to handle this today is using the fetch API. It provides a promise-based interface that is cleaner than older methods like XMLHttpRequest.
First, update your JavaScript function to construct the payload and send it to the target endpoint:
function myFunction() {
var name = document.getElementById("name").value;
var email = document.getElementById("email").value;
// Note: The source code referenced 'password' in the ID but 'pass' in the input type.
// Ensure the ID matches the element you are selecting to avoid undefined values.
var password = document.getElementById("pass").value;
fetch('profile.php', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
name: name,
email: email,
pass: password
})
})
.then(response => response.json())
.then(data => console.log('Success:', data))
.catch(error => console.error('Error:', error));
// Optional: Prevent the default form submission if you want to handle the UI state manually
event.preventDefault();
}
Understanding the Trade-offs
By sending a JSON payload via fetch, you are changing the contract between your frontend and backend. Your original profile.php attempts to access data using $_POST['name']. In standard HTML forms, inputs are serialized as URL-encoded strings (e.g., name=John&email=john@example.com), which PHP reads into $_POST automatically.
When you send JSON, the body of the request contains a raw string like {"name":"John"}. Standard PHP does not parse this automatically into an associative array. If you submit a JSON request to your current profile.php, the variable $_POST['name'] will likely be empty or undefined because PHP is looking for form-encoded data, not a raw JSON blob.
To receive the data sent via fetch, you must modify profile.php to decode the incoming JSON string:
<?php
// Check if the request body contains JSON
if (json_decode(file_get_contents('php://input'))) {
$data = json_decode(file_get_contents('php://input'), true); // Decode as associative array
if (isset($data['name'])) {
$name = $data['name'];
// Process $name here
}
} else {
// Fallback for traditional form submission or error handling
$name = $_POST['name'] ?? null;
}
?>
Security and Validation Considerations
Sending passwords via client-side JavaScript, even with fetch, exposes the data to potential interception if the connection is not secure. Ensure your server is served over HTTPS. Additionally, never rely solely on frontend validation (like the required attribute in HTML or checks inside your JS) for security. The backend must always validate and sanitize inputs before processing them.
Another critical detail is Content Security Policy (CSP). If your application has strict CSP headers configured to prevent cross-site scripting (XSS), sending a request to a different origin or using specific methods might be blocked unless the policy explicitly allows it. Since you are calling profile.php from index.php, they must reside on the same domain and protocol.
Finally, consider the lifecycle of the data. If you use fetch without handling the response explicitly (as shown in the simplified example above), the user will see no feedback. You should implement a loading state on your submit button or provide error messages based on the response.ok status code to improve the user experience.
If you are moving toward a framework-based architecture later, tools like Laravel can simplify this routing and request handling significantly. For more details on building robust APIs with these frameworks, check out resources from LaravelCompany.