Passing a js array to PHP

Why can't I access my array through $_POST in PHP? I'm trying to use the jQuery $.post method. Here is the corrected code with your suggestions:

My javascript:

<script type="text/javascript">
var selectedValues;
var serializedValues;
$("td").click(function() {
$(this).toggleClass('selectedBox');

// map text of tds to selectedValues
selectedValues = $.map($("td.selectedBox"), function(obj) {
        return $(obj).text();

});

serializedValues = JSON.stringify(selectedValues);

// $.post('/url/to/page', {'someKeyName': variableName}); //exemple
$.post('handler.php', 
      {'serializedValues' : serializedValues}, 
      function(data) {
        //debug 
     }
);

});

</script>

My php:

<?php
if(isset($_POST['serializedValues'])) {

            var_dump($_POST['serializedValues']);
            $originalValues = json_decode($_POST['serializedValues'], 1);
            print_r($originalValues);

        }


?>

Answers:

Answer

You should serialize your array into json string:

serializedValues = JSON.stringify(selectedValues)

And pass it to php. And then decode with json_decode:

$originalValues = json_decode($_POST['serializedValues'], 1);

http://php.net/manual/ru/function.json-decode.php

Answer

On a side note; your javascript could be refactored into something a bit more simple

$("td").click(function() {
    $(this).toggleClass('selectedBox');

    // map text of tds to selectedValues
    var selectedValues = $.map($("td.selectedBox"), function(obj) {
            return $(obj).text();
    });

    // $.post('/url/to/page', {'someKeyName': variableName}); //exemple
    $.post('handler.php', 
          {'serializedValues' : JSON.stringify(serializedValues)}, 
          function(data) {
            //debug 
         }
    );
});

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.