Javascript POST not working: Sending Javascript Array to PHP
Despite numerous attempts, you've encountered a challenge in passing a JavaScript array to a PHP script via POST. Seeking assistance to resolve this issue, you present the following code:
JavaScript:
function sendToPHP() { $.post("index.php", { "variable": toSearchArray }); }
PHP:
<?php $myval = $_POST['variable']; print_r ($myval); ?>
Issue Resolution:
You may be facing an issue due to a misunderstanding of how AJAX (Asynchronous JavaScript and XML) operates. While jQuery simplifies AJAX usage, it requires a proper understanding of the process.
In your case, the sendToPHP() function triggers a POST request to the index.php page with the variable parameter set to the toSearchArray. However, it's crucial to define an AJAX success handler function to capture the server's response.
Example using index.php:
<html> <head> <title>Test</title> <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script> <script type="text/javascript"> $(document).ready(function(){ $('#btn').click(function(){ var txt=$('#txt').val(); if(txt == ''){ alert("Enter some text"); } else { $.post('catcher.php', {'text':txt}, function(data){ $('#response').text(data.message); }, 'json'); } }); }); </script> </head> <body> <input type="text" id="txt"> <input type="button" id="btn"> <pre id="response" style="overflow:auto;width:800px;height:600px;margin:0 auto;border:1px solid black;">