Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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 ?

share|improve this question
1  
Why do you use stripslashes() here? –  SquareCat Dec 5 '13 at 22:07
1  
possible duplicate of Send array with Ajax to PHP script –  rlemon Dec 5 '13 at 22:09
    
No stripslashes required here, and you should maybe put quotes around your <?php echo $js_array; ?> line –  scrowler Dec 5 '13 at 22:09
    
I use json_decode($_POST['data']); It's not work. I dont't know. –  I'm a Newbie. Dec 5 '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 5 '13 at 22:18

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']); ?>
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.