+ 1

Pass Js array to php?

hello i want to know how i can pass a js array and save it in a php array?

10th Jan 2019, 9:19 PM
jack
jack - avatar
7 odpowiedzi
+ 1
create a php file and put this code in it: <?php if($_SERVER["REQUEST_METHOD"] == "POST") { try { $stream = fopen("php://input", "rb"); if (!$stream) throw new Exception("cannot open input stream"); $data = stream_get_contents($stream); $ebc = json_decode($data, true); print_r($ebc); } catch(Exception $e) { } finally { fclose($stream); } } ?> <!DOCTYPE html> <html> <head> <title></title> </head> <body> <script type="text/javascript"> const array = ["one","two","three", 1230, 1458, ["five", "six"] , true, false] fetch("<?php echo htmlentities($_SERVER['PHP_SELF']); ?>", { method: "POST", headers: { "content-type": "application/json; charset=utf8", "x-requested-with": "xmlhttprequest" }, body: JSON.stringify( array ) }) </script> </body> </html> tip: don't try it here in sololearn playground it will not work
10th Jan 2019, 11:03 PM
MO ELomari
MO ELomari - avatar
+ 2
Thanks a lot, you know where i can learn more about the php stream. And can I use this aswell: $.ajax({ type: "POST", url: "tourFinderFunctions.php", data: { activitiesArray: activities }, success: function() { $("#lengthQuestion").fadeOut('slow'); } }); in php: <?php $myArray = $_REQUEST['activitiesArray']; ?>
10th Jan 2019, 11:25 PM
jack
jack - avatar
+ 2
thanks
10th Jan 2019, 11:30 PM
jack
jack - avatar
+ 2
great thanks a lot! cause this version is much shorter
10th Jan 2019, 11:53 PM
jack
jack - avatar
10th Jan 2019, 11:28 PM
MO ELomari
MO ELomari - avatar
+ 1
do you know an answer to my second question aswell?
10th Jan 2019, 11:33 PM
jack
jack - avatar
+ 1
you could use JSON.stringify(activities) to encode your activities array in javascript, and then use $myArray=json_decode($_REQUEST['activitiesArray']); in your PHP script to retrieve it: $.ajax({ type: "POST", url: "tourFinderFunctions.php", data: { activitiesArray: JSON.stringify(activities) }, success: function() { $("#lengthQuestion").fadeOut('slow'); } }); in php: <?php $myArray = json_decode($_REQUEST['activitiesArray'], true); ?>
10th Jan 2019, 11:35 PM
MO ELomari
MO ELomari - avatar