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

Swapping out ChildNode data for HTML elements

When attempting to replace a node value with HTML content, I encountered an issue where the HTML tags were being displayed on the HTML page instead of applying the intended style. <style> .YellowSelection { background: yellow; } < ...

Unable to produce audio from files

Attempting to incorporate sound files into my project using https://github.com/joshwcomeau/redux-sounds but encountering difficulties in getting it to function. Below is the code snippet I utilized for setup. Unsure if webpack is loading the files correctl ...

Fixed navigation menu at the top of the screen

Can anyone help me with my navbar issue? I want it to stay on top of the page, but there's a huge gap between the top of the page and the nav bar. I've tried running a JS file, but it doesn't seem to fix the problem. Any ideas on how to make ...

Having trouble developing a custom jQuery tool for textareas

I am currently attempting to customize this script that mimics the Word 2007 minibar within a textarea. My approach involves encapsulating it in a plugin, but I am encountering an issue where it does not function properly with multiple textareas. If you w ...

Please enter a numerical value into the input field in a JavaScript form

<script> function loop() { var input = document.getElementById('inputId').value; for (var i = 0; i < input; i++) { var result = document.getElementById('outputDiv').innerHTML ...

Arrays of functions in C++

Struggling with an array of functions here. When trying to assign the functions to the array in the default constructor of the class, I keep getting this error message: "void (GameObject::*)()" cannot be used to initialize an entity of type "AlarmFuncti ...

The asterisk path is not processed by the Node command

Within my Test/Automation folder, I have multiple test cases such as a.js, b.js, c.js, and more. Currently, I am utilizing WebdriverJs Selenium to run these tests. To execute all the tests within the folder, I use the following command: node Test/**/*.js ...

Each time the website refreshes, Object.entries() rearranges the orders

After reading the discussion on Does JavaScript guarantee object property order? It seems that Object.entries() should maintain order. However, I encountered an issue with my Angular website where the order of keys in Object.entries() changed upon refres ...

Vue3 TypeScript may potentially have an object that is 'undefined'

This piece of code is Vue3 with TypeScript-based. export interface TenantDto { uuid: string; name: string; } export const useTenantStore = defineStore('tenant', { state: () => ({ tenants: [], }), actions: { setMyTenants: (pa ...

Concealing divs without values in ASP.NET MVC

I am working on an AJAX call to fetch data from the back-end and populate divs with it. Below is my code for the AJAX call: $(document).ready(function() { question_block(); }); function question_block() { $.ajax({ url: '@Url.Action(" ...

Having trouble changing my array state in react?

I'm having trouble understanding why my React state isn't updating with the following code: state = { popUpMessages:[] } popUpMessage(id,name) { console.log("id ",id,"name ",name) const addUserObject = { id, name }; const new ...

Validating forms using jQuery before making an Ajax call to submit them

I'm struggling to implement form validation before submitting it via Ajax to my php script. Despite researching on stackoverflow, I haven't found a solution that fits my needs. My form consists of 3 inputs and a submit button: <input type="t ...

Angular js is a powerful framework that allows for the seamless transition of views, except for the home

I am currently using the ng-animate module to implement sliding effects for my app views. Each route has its own unique slide animation. Take a look at my simple code below: HTML: <div ng-view ng-animate class="slide"></div> CSS: /*Animatio ...

Encountering an endless loop when utilizing cycle-idb with a text field for user input

Struggling to develop a basic test app that captures user input from a text field, displays it, and stores it using cycle-idb. Unfortunately, I've been stuck in an endless loop no matter what steps I take. Below is the complete main function: functi ...

Accessing form objects in Typescript with AngularJS

I am currently working with AngularJS and Typescript. I have encountered an issue while trying to access the form object. Here is the HTML snippet: <form name="myForm" novalidate> <label>First Name</label> <input type="text" ...

positioning a window.confirm dialog box in the center of the screen

I'm currently facing an issue with a dialog box that I have implemented successfully. However, I can't seem to get it centered on the page: <Button variant="danger" onClick={() => { if (window.confirm('Delete character?')) handle ...

Error message: Unexpected token "(" in the asynchronous aspect of Meteor

Currently running meteor version 1.5.1, I am facing a bug while attempting to import an npm module (kraken-api) on the server side: import KrakenClient from 'kraken-api'; > W20170726-22:02:48.177(2)? (STDERR) packages/modules.js:677 ...

Transforming a vertical table into a horizontal layout

I'm facing an issue with transforming the database object for table display. My database contains a table structured like this. name total date Awoc1 100 9/14/2022 Awoc1 200 9/15/2022 Awoc1 300 9/16/2022 Awoc2 100 9/14/2022 Awoc2 ...

Tips for removing a row from a table

I've been working on a responsive data table where each time I click an add button at the end of a row, a new row is added with the add button turning into a delete button. Below is the code I've implemented: The Table: <table id="invoice_ta ...

what strategies can be implemented to prioritize addressing validation errors in return forms

I'm currently working on a web application in asp.net mvc-5, and I have a contact form displayed in the middle of the Contact Us view. Here's the code snippet: <div class="col-sm-8 col-sm-push-4"> <h2>Contact Us1 ...