RamiD has asked for the wisdom of the Perl Monks concerning the following question:

hi , tried to send a array of json files from javascript to perl dancer route , but in perl I did not manage to print every array cell here is the code javascript code

<script> var test=[]; test[0]={'one':'oneValue','two':'twoValue'}; test[1]={'one':'oneValue1','two':'twoValue1'}; test[2]={'one':'oneValue2','two':'twoValue2'}; var xhttp = new XMLHttpRequest(); xhttp.open("POST", "url", "true"); xhttp.send(JSON.stringify(test)); </script>

perl route code

set serializer => 'JSON'; my @items = request->body; debug $items[0]; debug $items[1]; debug $items[2];

the output was $items[0]; {"one":"oneValue","two":"twoValue"},{"one":"oneValue1","two":"twoValue1"},{"one":"oneValue2","two":"twoValue2"} in /home/ramid/scriptMask/scriptMask/lib/scriptMask.pm l. 300

$items1; undef

$items2; undef

Replies are listed 'Best First'.
Re: perl dancer route recive array of json via xmlhttp request
by Corion (Patriarch) on Oct 03, 2016 at 14:10 UTC

    I don't use the serializers closely, but maybe your Javascript didn't send the correct MIME Content-Type headers so Dancer did not autodecode the content?

    Personally, I would do the decoding and validating directly in Perl instead of hoping for the (runtime) setting of serializer being the correct one. Note that there is no distinction between input and output serialization, so if you switch the serializer to CGI (or whatever the "other" setting is) anywhere else in your program, it might be in the wrong state when you receive that input.

      do you have any clue what Content-Type I should add !!

        Maybe the standard content type for JSON? application/json I guess.

Re: perl dancer route recive array of json via xmlhttp request
by stevieb (Canon) on Oct 03, 2016 at 14:25 UTC

    Another thing to check is this line:

    xhttp.send(JSON.stringify(test));

    I've never used it, but I suspect that when you call stringify(), you're compiling the entire array back into a single string, which is perhaps why it's only showing up in $items[0], leaving the other two elements empty.

Re: perl dancer route recive array of json via xmlhttp request
by jellisii2 (Hermit) on Oct 03, 2016 at 16:54 UTC
    Since arrays are objects in Javascript, wouldn't this get stringed to what you're indicating? You're not POSTing an array of HTML inputs to get parsed by the script, you're POSTing a single javascript object.
Re: perl dancer route recive array of json via xmlhttp request
by Anonymous Monk on Oct 03, 2016 at 19:40 UTC