I want to send a JavaScript array to the server when a user clicks on a button.
My current code is as follows, but it does not work, could someone help me with this?
HTML
<?
$arrs = {include for database}
$js_array = json_encode($arrs);
?>
<script>
var dataArray = <?php echo $js_array; ?>;
var jsData = JSON.stringify(dataArray);
$.ajax({
type: "POST",
url: "savepos.php",
datatype: "JSON",
data: {data : jsData},
success: function() {
alert('success!');
}
});
</script>
savepos.php
$data_array = json_decode(stripslashes($_POST['data']));
However, I get $data_array as null ?
Pranav 웃
8,4676 gold badges41 silver badges48 bronze badges
1 Answer 1
You can just send the array without using JSON.stringify(). There is no need for it, as you set the datatype. Check out this fiddle
Open up chromes network tools before you hit run to see the form data being sent. Then you can use
<?php json_decode($_POST['data']); ?>
answered Dec 5, 2013 at 22:18
krosullivan
1722 silver badges12 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
default
stripslashes()here?stripslashesrequired here, and you should maybe put quotes around your<?php echo $js_array; ?>line$_POST['data']? Do you get analert('success!');when you run this? Are there any errors in the console?