Tips for Sending a Multidimensional Array through Ajax Requests

Is there a way to properly pass the inv array in ajax? Although I can see the inv array value in console.log, it seems like I am unable to retrieve the array on my php page.

<script>
var FilterCat=['Location','Name','City','Country','State'];
var inv =[];

for(var j = 0; j < FilterCat.length; j++) 
{
    var a =  FilterCat[j];
    a =[];
    var apply = document.getElementsByName("Filter['"+FilterCat[j]+"'][]");

    for(var i = 0; i < apply.length; i++) {
        if(apply[i].checked)
        {
            var F =  a.push(apply[i].value);
        }
    }
    inv[FilterCat[j]]=a;
}

$.ajax({
    type : "POST",
    url  : "../module/ApplyFilter.php",
    data :{data:inv},
    dataType :'JSON',
    success:function(response)
    {
        alert(response);
        console.log(response);
    }
});
<script>

Even though after the loop each array variable holds values, the data returned by ajax appears as an empty array.

In this code snippet, values are set category wise in respective arrays which need to be passed into a main array in ajax.

The Console response is formatted as follows:

City: Array(0)
length: 0
__proto__: Array(0)
Country: Array(0)
length: 0
__proto__: Array(0)
State: Array(0)
length: 0
__proto__: Array(0)
Location: Array(2)
0: "Distributore"
1: "Vendor"
length: 2
__proto__: Array(0)
Name: Array(0)
length: 0
__proto__: Array(0)
length: 0
__proto__: Array(0)

Answer №1

The query selector you are using is incorrect. You must specify the name attribute and enclose the entire value in quotes, not just the part inside the subscript. Additionally, an attribute selector should be within square brackets. The correct format should be:

var apply = document.querySelectorAll("[name='Filter["+FilterCat[j]+"][]']");

Other than that, your code should function properly. In PHP, the desired values will reside in $_POST['data']['Location'], $_POST['data']['Name'], and so on.

Although the extra data wrapper is unnecessary. If you use:

data: inv

You can access the values from $_POST['Location'], $_POST['Name'], etc., in PHP.

In both cases, these values will be arrays of checkbox selections.

To simplify the JavaScript code, you can enhance your selector by adding :checked so you won't need to check it in the loop.

var apply = document.querySelectorAll("[name='Filter["+FilterCat[j]+"][]']:checked");
var a = apply.map(el => el.value);
inv[FilterCat[j]]=a;

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

Submitting Forms Using Ajax and PHP

Here is the HTML page along with a PHP code snippet that I am using for testing form submission via AJAX. HTML PAGE: $('#but1').click(function(){ $('#frm1').submit(function(){ var dataString = $(this).serializeArray(); ...

Synchronously read a file in Node.js and return its contents as a string instead of a buffer

I need assistance with reading a file in Node.js as a string rather than a buffer. I am developing a program in Node.js and encountering an issue when attempting to read a file synchronously. The problem is that the file is returned as a buffer, not a stri ...

Tips for verifying a string date using the Ajax Control Toolkit (CalendarExtender) technology

I have a dilemma with two formatted TextBoxes that receive their text value from a CalendarExtender. I need to validate that the first TextBox is greater than the second one, but the values are coming in as strings rather than dates. Ho ...

Is Firefox preventing the running of asynchronous JavaScript code?

My experience with writing tests for my web application in the Selenium Framework has been smooth sailing with both Chrome and Edge. However, I've encountered a problem specifically with Firefox - the asynchronous script keeps timing out. I suspect i ...

Is it possible to enable sorting for every column in the b-table component?

After reviewing the information on sorting per column in the bootstrap-vue documentation, I am curious if it is possible to enable sorting for the entire table. ...

Learn how to utilize webpack for bundling a TypeScript library into a JavaScript script

Recently, I created a TypeScript library that I am currently using as an npm package. Here's a snippet of what it looks like: index.ts import * as peselManager from './pesel'; /** * Checks if a given PESEL number is valid. * * @param { ...

Attempting to retrieve JSON data through a customized Flickr API request results in a parsing error

Last night, I dedicated my time to experimenting with the 'getJSON' method in JQuery and using it against the Flickr API. While I was able to successfully implement examples from the JQuery documentation, my attempts at fetching JSON from custom ...

Youngster listens for guardian's occurrence in Angular 2

While the Angular documentation covers how to listen for child events from parents, my situation is actually the opposite. In my application, I have an 'admin.component' that serves as the layout view for the admin page, including elements such a ...

Implementing a click event on header elements within a full calendar component in a React application

I'm currently integrating full calendar into my project. I need to implement click events on the header buttons such as prev, next, today, and others. This is how I've set up full calendar with the specified header buttons: <FullCalendar d ...

The disappearance of the checkbox is not occurring when the text three is moved before the input tag

When I move text three before the input tag, the checkbox does not disappear when clicked for the third time. However, if I keep text three after the input tag, it works fine. Do you have any suggestions on how to fix this issue? I have included my code be ...

MongoSearch: A Geo-Targeted Search Engine tailored to your needs

For my new app project, I am using MongoDB, Express, JS, and Node to create a platform similar to Yelp. After some research, I discovered how to search for multiple fields within a campus schema (including campuses, restaurants, barbershops, and names). No ...

Is the post secure if a HTTP web page sends an ajax request to a HTTPS url?

If I developed an HTML/jQuery widget to be embedded on third-party websites with users of very limited technical knowledge and potentially missing SSL certificates, would the information posted securely through AJAX Post to a secure URL remain protected? ...

The placeholder attribute for input types does not display consistently across all browsers

I am experiencing an issue with the placeholder text in my input field. <input type="text" name='linkLabel{{index}}' autocomplete="off" class="input-large tight-form-url last remove-cross" required="required" placeholder="{{'linkLabel&ap ...

Exploring the map function in Angular and native JavaScript

Still getting the hang of angular, so there might be something I'm overlooking. I have a model containing a collection of objects with their own properties, and my goal is to generate a csv value based on the Text property of each object. I've ex ...

Utilizing Shopify API to seamlessly add items to cart without any redirection for a smoother shopping experience

Looking for a solution to submit an add to cart POST request without any redirection at all? I have tried changing return_to to "back" but that still reloads the page, which is not ideal. My goal is to smoothly add the item to the cart and notify the cli ...

Instancing prohibits me from adjusting the transparency or opacity of each specific child geometry

I am currently working on a project that involves a simple model made up of 1000 instances of spheres. In an effort to optimize performance by reducing the number of draw calls, I decided to implement instancing. However, I encountered an issue with changi ...

Sending additional parameter to a return function callback

In my current project, I'm utilizing a library function that follows this structure: let arr = [1,2,3] arr.forEach((item, i) =>{ doSomething(inputParam, (err, result)=>{ ... //Use err and result }); }) The err and resu ...

Error: Invalid character encountered during login script JSON parsing

I found this script online and have been experimenting with it. However, I encountered the following error: SyntaxError: JSON.parse: unexpected character [Break On This Error] var res = JSON.parse(result); The problem lies in the file below as I am unf ...

Issue with if statement when checking element.checked

Hey everyone, I'm currently working on a calculator app and running into an issue. I have set up 3 radio buttons and I would like to check them using an 'if statement' in my JS file. However, the problem is that the 'main' element ...

Receiving the outcome of an asynchronous function in JavaScript

async function retrieveKey() { try { var key = await dec.awsDecrypt('dev-frontend') return key; } catch(err) { } } //calling the function const result = retrieveKey() In the code snippet above, there is an asynchronous ...