Home >Backend Development >PHP Tutorial >How can I properly receive and process a JavaScript array sent via POST to a PHP script?
Sending Javascript Array to PHP
When attempting to send an array from JavaScript to PHP using POST, it's essential to understand how asynchronous JavaScript and XML (AJAX) operates.
To POST an array, you can use the following JavaScript code:
<code class="javascript">function sendToPHP() { $.post("index.php", { "variable": toSearchArray }); }</code>
However, on the PHP side, you should avoid using $_POST['variable'] directly to access the array. Instead, create a custom PHP function to receive and process the array:
<code class="php"><?php function receiveArray() { if (!empty($_POST['variable'])) { $myval = json_decode($_POST['variable'], true); print_r($myval); } } ?></code>
This function will decode the JSON-encoded array and make it accessible in the $myval variable.
Handling POST in PHP
It's important to create a function in PHP to handle the POST request. This ensures that the PHP code is executed only when necessary.
<code class="php"><?php if (!empty($_POST)) { receiveArray(); } ?></code>
The receiveArray() function will now handle the POST request and echo the array.
Using Separate PHP and HTML Files
For clarity and maintenance, it's recommended to separate the PHP and HTML code into different files.
PHP File:
<code class="php"><?php function receiveArray() { // Handle the POST request and echo the array } ?></code>
HTML File:
<code class="html"><html> <head> <script src="jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function() { $('#btn').click(function() { $.post('phpfile.php', { "variable": toSearchArray }); }); }); </script> </head> <body> <input type="text" id="txt"> <input type="button" id="btn"> <pre id="response">