What is the best way to send a JavaScript array to a Perl script using AJAX?

Is it possible to convert a JavaScript array passed via AJAX into a Perl array?

Accessing in Perl:

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

Result:

employee,admin,users,accounts

It appears that the first value in the Perl array (@searchType[0]) contains all the elements of the JavaScript array as a single string.

Answer №1

While this question may be outdated, it could still be of interest to someone else browsing through similar topics.

To pass a JavaScript array to Perl via Ajax, one method is to convert the array into a JSON object using "JSON.stringify(jsArray);" and then decode it in the Perl script. Below is a simple example where the first item of the 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";

Answer №2

Make sure to format it as

param1=value&param2=another-value
.

let filters = ["price", "category", "brand"];
let paramName = "filters";
for (let i = 0; i < filters.length; i++) {
    filters[i] = encodeURIComponent(paramName) + "=" + encodeURIComponent(filters[i]);
}
let paramsString = filters.join("&");

After that, you can include the paramsString in your URL or post request.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountering a 404 error indicating that the file cannot be found while attempting to log into an authentication system developed using express and node

Currently, I am in the process of developing a demonstration banking application that facilitates user sign up and sign in functionality using express.js and node.js. The API created accepts POST requests to /signup and /authenticate routes successfully wh ...

Error encountered: Denied access in AWS Transcription Node JS API

I have been working with the AWS transcription API in Node JS and my code looks like this: const tClient = new TranscribeClient({ region: "us-east-1", credentials: { accessKeyId: AWS_ID, secretAccessKey: SECRET, ...

Render multiple checkboxes with values from an array of objects passed as a prop to a child component using a v

I am facing an issue with my Vue components 'Parent' and 'Child'. Each child component has a checkbox with a :checked prop. In the Parent component, I iterate through an array of objects and pass props to the child. Although I can emit ...

Retrieve the data object in VueJS

(Regarding a currency conversion tool) In order to accurately convert currencies, I am looking to access an object structured like this: rates: AUD: 1.708562 SGD: 1.546211 When retrieving these rates from an API, they are not always in the desired o ...

What is the best way to incorporate multiple conditions within a React component?

When working in React, I have the ability to conditionally render any div using the following code snippet: {hasContent && <span>{value}</span> } Recently, I attempted to include two conditions as follows: {hasContent || hasDesc &am ...

Why isn't useEffect recognizing the variable change?

Within my project, I am working with three key files: Date Component Preview Page (used to display the date component) useDateController (hook responsible for managing all things date related) In each of these files, I have included the following code sn ...

Using JavaScript to modify the -webkit-animation-play-state

Hello, I'm currently facing a challenge in changing my css3 -webkit-animation-play-state property from paused to running upon clicking on another div. Does anyone have any suggestions on how I can achieve this? I believe JavaScript might be the way to ...

The compatibility between cross-fetch and React Native is currently not supported

I have developed an API wrapper that utilizes fetch to carry out the API requests. To ensure compatibility with Browsers, Node, and React Native, I incorporate cross-fetch. When testing the wrapper in Node, everything works fine. However, when using it in ...

Show only specific data from JSON results

I am trying to display a specific cryptocurrency's price without the need for curly braces or explicitly stating "USD". Currently, it appears as {"USD":0.4823} when using the following code: <script> $(document).ready(function () { ...

Using Sweet Alert to enhance the user confirmation experience on your website

I need to replace the standard confirm dialog with a customized one using Sweet Alert. The JavaScript function I want to use is located in the MasterPage. function checkDelete() { swal({ title: "Are you sure?", text: "You will not be able to r ...

What is the best approach to display data in React fetched from an API request? If this is not the right method, what changes should be made to the JSX rendering to convert

As I begin my journey with React, I find myself questioning the best practices for displaying data. Should I always break down components into smaller ones rather than having one large component render everything? It seems like a good practice, but I' ...

Is there a way to send the ID and value of a select field to AJAX without needing a form?

I have a specific select field named 'region_code' with an ID and value. I need to pass this ID in an ajax request. The input field is not contained within a form, but it has both a value and an ID. Can the value be retrieved in ajax as demonstr ...

Resizing nested elements while maintaining consistent padding dimensions

If you're looking to create a sleek foundation for a 200px wide, 30px high editable combobox that can be easily used with angular binding or other JavaScript data-binding solutions, consider the following HTML code. However, there's a desire to m ...

Removing a row from a table in a React component

I have incorporated a Table component from Material UI into my project to display data fetched from an external API. The table dynamically updates its rows based on events received through a web socket connection. One specific requirement I have is that wh ...

Issues with setSelectionRange functionality in JavaScript unit tests leading to unexpected behavior

Currently, I am utilizing the qunit framework to perform unit testing on interactions within an HTML element that has been dynamically created using jquery (specifically, var $textarea = $('')) in Chrome. Below is the code snippet I am employing ...

Having trouble sending data from AJAX to PHP

My goal is to implement a "load more" feature in my web app that automatically calls a PHP file to load additional products as soon as the page is fully loaded. In order to achieve this, I am using AJAX to call the PHP file: $(document).ready(function() { ...

How to utilize a parameter value as the name of an array in Jquery

I am encountering an issue with the following lines of code: $(document).ready(function () { getJsonDataToSelect("ajax/json/assi.hotel.json", '#assi_hotel', 'hotelName'); }); function getJsonDataToSelect(url, id, key){ ...

Tips for concealing an entire row of a table with Jquery

I am currently working on a system that involves a table with anchor tags named original and copy in each row. By clicking on these anchor tags, we are able to update the database whether the item is an original or a copy using ajax. However, I am facing a ...

Unable to display the complete JSON data using ng-repeat in AngularJS

Utilize ng-repeat to display data retrieved from a web service. Below is my controller JS (GetAllCtrl.js): https://i.stack.imgur.com/GAelG.jpg I have received JSON data: https://i.stack.imgur.com/0xkAU.jpg My goal now is to extract only company informati ...

conceal the mustard-colored dots within the overlay

Whenever I trigger the link, a modal window pops up, but it comes with an unwanted black background color and yellow dots. How can I prevent the yellow dots from showing up on the overlay? http://jsfiddle.net/y88WX/18/embedded/result/ <nav class="da-d ...