0

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,469
  • 6
  • 38
  • 48
  • 1
    Why do you use `stripslashes()` here? – SquareCat Dec 05 '13 at 22:07
  • 1
    possible duplicate of [Send array with Ajax to PHP script](http://stackoverflow.com/questions/9001526/send-array-with-ajax-to-php-script) – rlemon Dec 05 '13 at 22:09
  • No `stripslashes` required here, and you should maybe put quotes around your `` line – scrowler Dec 05 '13 at 22:09
  • I use json_decode($_POST['data']); It's not work. I dont't know. – I'm a Newbie. Dec 05 '13 at 22:10
  • What's the value of `$_POST['data']`? Do you get an `alert('success!');` when you run this? Are there any errors in the console? – MattDiamant Dec 05 '13 at 22:18
  • The dataType attribute for jQuery specifies how to handle the responding data, not the sending data. The sent data is always converted into a URL encoded string. If you don't use JSON.stringify() you can use $_POST['data'] directly. Then json_encode on the PHP side. – Camron Dec 05 '13 at 22:30

1 Answers1

3

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']); ?>
krosullivan
  • 172
  • 2
  • 12