+ 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?
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
+ 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']; ?>
+ 2
thanks
+ 2
great thanks a lot!
cause this version is much shorter
+ 1
check this:
http://php.net/manual/fr/book.stream.php
+ 1
do you know an answer to my second question aswell?
+ 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); ?>