Skip to content Skip to sidebar Skip to footer

How Can I Pass A Javascript Array Through Ajax To A Perl Script?

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,adm

Solution 1:

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><scriptsrc="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 pathdata: { 'searchType': jsArrayJson},
                            success: function(res) {alert(res);},
                            error: function() {alert("did not work");}
                    });
                })

            })

        </script></head><body><buttonid="test" >Push</button></body></html>

processJsArray.pl

#!/usr/bin/perluse 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 arrayprint $q->header('text/plain;charset=UTF-8'); 
print"first item:"."\n";
print $myJsArray[0]."\n";

Solution 2:

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.

Post a Comment for "How Can I Pass A Javascript Array Through Ajax To A Perl Script?"