2

How can I create a Perl array from a JavaScript array that is passed via AJAX?

Perl Access:

@searchType = $cgi->param('searchType');
print @searchType[0];

Output:

employee,admin,users,accounts

It seems that the Perl array sets the first value (@searchType[0]) as a string of all the passed JavaScript array objects.

2
  • Use JSON to serialize your data. Commented Feb 14, 2014 at 22:15
  • @JamesHickman: As ThisSuitIsBlackNot suggested, one way to this, is to use JSON. I added a working example below which does what you want, I think. Please let me know whether that works for you or whether it needs to be adapted to your needs. Commented Aug 5, 2015 at 17:09

2 Answers 2

3

It is an old question, so I am not sure whether that is still interesting for you but maybe someone else is interested in this question, too.

As already suggested in the comments above, one way to pass a javascript array to Perl via ajax is to convert this array first to an JSON object - using "JSON.stringify(jsArray);" - which is then decoded in the Perl script. I added a very simple example below where the first item of your array is returned through an alert.

index.html:

<!DOCTYPE html>
<html>
    <head>
        <title>Testing ajax</title> 
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
        <script>

            $(document).ready(function() {

                $("#test").click(function(){
                    var jsArray = ["employee", "admin", "users", "accounts"];
                    var jsArrayJson = JSON.stringify(jsArray);
                    $.ajax({
                            type: 'POST',
                            url: '/cgi-bin/ajax/stackCGI/processJsArray.pl', //change the path
                            data: { 'searchType': jsArrayJson},
                            success: function(res) {alert(res);},
                            error: function() {alert("did not work");}
                    });
                })

            })

        </script>
    </head>
    <body>
       <button id="test" >Push</button>

    </body>
</html>

processJsArray.pl

#!/usr/bin/perl

use strict;
use warnings;

use CGI;
use JSON;

my $q = CGI->new;

my @myJsArray = @{decode_json($q->param('searchType'))}; #read the json object in as an array

print $q->header('text/plain;charset=UTF-8'); 
print "first item:"."\n";
print $myJsArray[0]."\n";
Sign up to request clarification or add additional context in comments.

2 Comments

You're sending JSON embedded in application/x-www-form-urlencoded. That's unnecessarily complex. Pick one or the other. I'd go with form data as its easier to build progressively.
@Quentin: Sure, there might be more efficient solutions than the one I posted. But I think that gets kind of close to what James posted in his question. But seems he solved this problem or lost the interest in it... Maybe this post helps someone else :)
1

You need to express it in the form of key=value&key=other-value.

var searchType = ["employee", "admin", "users", "accounts"];
var keyName = "searchType";
for (var i = 0; i < searchType.length; i++) {
    searchType[i] = encodeURIComponent(keyName) + "=" + encodeURIComponent(searchType[i]);
}
var queryString = searchType.join("&");

Then you use the queryString as part of your URL or post data as normal.

4 Comments

Although your method of converting the array to a string is possible, it is not the most efficient way. It should be possible to pass an actual array object. I have done it in PHP many times, but this project is in PERL so I am hoping to find a way to properly convert an incoming JS array into a PERL array. From what I read this is possible, I just am unsure the proper way to go about it.
@James Hickman, Re "It should be possible to pass an actual array object.", Impossible. Only bytes can be sent over a socket. Data structures need to be serialized and recreated on the other end. Quentin serialized using application/x-www-form-urlencoded (because it will work with my @searchType = $cgi->param('searchType')). I would have gone with JSON (because it'll cause fewer headaches in the long run). But the point it that something needs to be used.
Unless I'm dealing with complex data structures, I prefer application/x-www-form-urlencoded data, since it can be generated with a form so you can reduce the dependancy on JavaScript. It will also be parsed automatically by every server side form library, so you don't need to write an extra JSON decoding step.
@JamesHickman: As suggested by ikegami and ThisSuitIsBlackNot, one way to do this is to use JSON. I added an example above. Please let me know whether that works for you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.