Explain Codes LogoExplain Codes Logo

How to read the post request parameters using JavaScript

javascript
prompt-engineering
sessionstorage
post-request-parameters
Anton ShumikhinbyAnton Shumikhin·Feb 20, 2025
TLDR

If you want to capture POST data on the client-side when a form is submitted, take a look at this snippet:

document.querySelector('form').onsubmit = event => { event.preventDefault(); // No direct form submission here, thank you... let formData = new FormData(event.target); // Candid camera for form data formData.forEach((value, key) => console.log(`${key}: ${value}`)); // Log it all out };

On the other hand, when you're sending POST requests via fetch, here's how you can get back the response:

fetch('endpoint', { method: 'POST', // It's POST time! headers: { 'Content-Type': 'application/json' }, // Packaging info for our delivery body: JSON.stringify({key1: 'value1'}) // Packing our delivery }) .then(res => res.json()) // Unpacking the response .then(data => console.log(data)); // There's our post, all shiny and new!

FormData captures form data, while fetch makes the POST request and reads the response.

Server-side: The original poster

Bear in mind that even though the JavaScript code is operating on the client side, the actual POST request parameters are primarily handled on the server-side. Once the server receives the POST request, typically a server-side language, like PHP, is put to work to gobble up these values.

<?php $post_data = json_decode(file_get_contents('php://input'), true); // PHP: Not only good for elephants! ?>

A useful way to "bridge the gap" between server-side and client-side is to use PHP to echo out the post data into JavaScript variables within your HTML:

<script> var postData = <?php echo json_encode($post_data); ?>; // Mission impossible: PHP briefs JavaScript </script>

With that, you have postData as an object containing your POST parameters ready for JavaScript to juggle around.

Overcoming page reloads with sessionStorage

To make form data available for JavaScript even after page reloads, consider the sessionStorage object. It's like a reliable locker-keeper for form data that won't forget your belongings under the same origin:

sessionStorage.setItem('formData', JSON.stringify(formData)); // Trusty locker-keeper at your service

And to call it back this stored data on the client side with JavaScript:

let storedData = JSON.parse(sessionStorage.getItem('formData')); // Just like an old friend

Be sure to remember to sanitize and validate any data stored this way. It's like washing hands; hands of your data, keeps it clean in front of potential XSS attacks.

Understanding GET and POST with JavaScript

It's important to not get confused and remember that JavaScript's window.location.search is only for accessing GET parameters, not POST. Also, contrary to local storage, sessionStorage is restricted to the same session's tab or window (a bit like Game of Thrones: taboo for other houses).

And when it comes to cross-page access, storing serialized form data in local or session storage prior to form submission might help:

// Snap! Save the form data before submitting sessionStorage.setItem('formData', new URLSearchParams(formData).toString());

And then, pick it up on a different page:

// Fetch the saved data on another page let storedData = new URLSearchParams(sessionStorage.getItem('formData'));

Browser extensions as your minions

While client-side JavaScript alone cannot tap directly into the POST data, browser extensions or addons could, theoretically, intercept POST data in transit. However, these sort of stunts are pulled off mainly by developers and rarely ideal for general client-side code due to concerns for security and privacy.

Getting the data back to HTML

Another tactic involves extracting POST data on the server-side, and then passing it back to the HTML in the form of hidden inputs - a sort of a round trip:

<input type="hidden" id="postParam" value="<?php echo htmlentities($post_data['paramKey']); ?>"> // Secret messenger from server to client

JavaScript then just grabs the data:

let postParam = document.getElementById('postParam').value; // JS retrieves the secret message

Constant vigilance: The role of security

Remember, you need to have an eagle eye when it comes to sanitizing and validating inputs and data echoed back to the HTML to prevent injection attacks. Remember that values camouflaged in hidden fields can be tampered with by users - a word of advice, never fully trust client-side values for crucial validations or authorizations.