The outcome of a function within the $.ajax method is transformed into a string

Trying to pass an array of IDs using the $.ajax data variable is proving to be a challenge. The array is generated by a function, and I've noticed that if I define this function outside of the $.ajax call, it works fine. However, when I place the same function code inside the $.ajax (which is my preference), the array gets passed as a string instead.


        function mySort(){ // Do not pass hidden clones
            var items = [];
            $('#fp_parameters_list').children().each(function(){
                if ($(this).is(':visible')) {         
                    items.push($(this).attr('data-parameter-id'));
                }
            });
            return items;
        }

        // This results in correct ordering
        $.ajax({
            url: '/echo/json/',
            type: 'post',
            dataType: 'json',
            data: {
                ordering: mySort()
            }
        });

        // This results in ordering being passed as a string
        $.ajax({
            url: '/echo/json/',
            type: 'post',
            dataType: 'json',
            data: {
                ordering: function(){ // Do not pass hidden clones
                    var items = [];
                    $('#fp_parameters_list').children().each(function(){
                        if ($(this).is(':visible')) {         
                            items.push($(this).attr('data-parameter-id'));
                        }
                    });
                    return items;
                }
            }
        });
    

Here's the fiddle link for reference: http://jsfiddle.net/vxLrN/7/

You can observe that the first request sends ordering as an array, while the second one passes ordering as a string, even though the functions are identical. How can I keep the function inline and still get an array result? Thanks.

Answer №1

Ensure that you execute this unnamed function to correctly assign the desired outcome (an array of strings) to the ordering parameter:

data: {
    ordering: (function () { // Avoid passing hidden duplicates
        var items = [];
        $('#fp_parameters_list').children().each(function() {
            if ($(this).is(':visible')) {
                 items.push($(this).attr('data-parameter-id'));
             }
         });
         return items;
    })(); // <!-- Make sure to call the unbranded function here for its output
}

Answer №2

Instead of iterating through elements manually, you can simplify the process by using $.map to directly build the array.

$.ajax({
  url: '/echo/json/',
  type: 'post',
  dataType: 'json',
  data: {
    ordering: $.map($('#fp_parameters_list').children(':visible'), function(el) {
                 return $(el).data('parameter-id');
              })
  }
});

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

Populating a clickable list and form with a complex JavaScript object

I have a code snippet that takes an unstructured String and parses it into a JavaScript object. My next step is to integrate it into a web form. You can check out the demo here. The demo displays the structured object hierarchy and showcases an example of ...

One function in Typescript lodash is missing a default export

Is there a way to import just one function from lodash? I attempted it like this: import get from 'lodash/get'; Even after installing both lodash and @types/lodash, I encountered the following error message: @types/lodash/get/index"' ha ...

How can validation of input fields be implemented in React Js?

Currently, I am dealing with a variable (in my actual application it is an API) named data, which contains nested items. Starting from the first level, it includes a title that is already displayed and then an array called sublevel, which comprises multip ...

Create a basic chart using JavaScript

I am looking to replicate a specific chart using JavaScript. The red point in the chart is variable. So far, I have attempted to create it using the flot library: var d3 = [[7,7]]; $.plot("#placeholder", [{ data: d3, points: { show: true } }], { ...

Issue with Moment.js incorrectly formatting date fields to a day prior to the expected date

Currently, I am attempting to resolve a small issue in my code related to a tiny bug. In my React component, I have set an initial state as follows: const initialFormData = Object.freeze({ date: Moment(new Date()).format('YYYY-MM-DD'), pr ...

How to Automatically Close an Ajax Modal Popup After Executing Code in ItemCommand in ASP.Net

I am currently facing an issue with closing a ModalPopup after a code sequence is executed. The situation at hand involves coding a filebrowser for the company and everything seems to be working fine except for the downloading of files. I have implemented ...

Deleting an element from HTML using jQuery

In the midst of creating a system that allows users to construct their own navigation structure, I have encountered a stumbling block. The idea is that when a user lands on the site, they are presented with a list of available topics from which they can ch ...

What are the steps to achieve consistent response behavior in POSTMAN that matches that of a web browser?

Below is an example of my code: const express = require('express'); const app = express(); app.get('/', function (req, res) { res.setHeader('Content-Type', 'text/html'); res.write("First \n"); set ...

Adjusting image dynamically based on conditions

I need to dynamically display images on my HTML based on specific conditions using TypeScript. In my TypeScript file: styleArray = ["Solitary", "Visual","Auditory","Logical","Physical","Social","Verbal",]; constructor(){ for (var i = 0; this.sty ...

Navigating through Angular JS validation procedures step by step

I have a wizard in angular js consisting of multiple steps: <wizard on-before-step-change="log(event)" on-step-changing="log(event)" on-after-step-change="log(event)" user="user"> <step title="step 1"> </step> <step title="step 2"& ...

Creating dynamic animations by shifting the hue of an image on a canvas

Recently, I've been exploring the world of canvas tags and experimenting with drawing images on them. My current project involves creating a fake night/day animation that repeats continuously. After trying various approaches like SVG and CSS3 filters ...

Socketio: Issue: Isolated surrogate U+D83D is not a valid scalar value

I've been experiencing frequent crashes with my node.js server recently, all due to a recurring socket.io error. It seems that the client may be sending invalid UTF strings, causing an error in the utf8.js file. I'm getting frustrated with the co ...

State update failing to modify arrays

Shown below is an array that contains boolean values: const [state, setState] = React.useState({ [`${"checkedA"+index}`]: false, [`${"checkedB"+index}`]: false, [`${"checkedC"+index}`]: false, [`${"checkedD"+index}`]: false, }); ...

Access to data retrieval was restricted by CORS policies on my Node.js/Express REST API server

I am currently running a localhost node/express server that is designed to accept any post request with a body and then return the same body along with a message. To enable Cross-Origin Resource Sharing (CORS), I have integrated the cors node package into ...

Is the jquery autocomeplete plugin malfunctioning when using numbers in the input?

I encountered a requirement to display stock number suggestions within a search box. To achieve this, I decided to implement the Jquery autocomplete plugin. Through an ajax call to a function in my cfc, I was able to retrieve all the stock numbers and stor ...

Add new data to an existing array in Angular 7 without overwriting it

After clicking a button, I'm retrieving data from the WordPress API: <a (click)="initGetComments()">Get comments</a> This is the code snippet: export class AppComponent { commentsResults: CommentsItem[] = []; ...

How can we determine in JavaScript whether a certain parameter constitutes a square number?

I've developed a function that can determine whether a given parameter is a square number or not. For more information on square numbers, check out this link: https://en.wikipedia.org/?title=Square_number If the input is a square number, it will ret ...

Extracting URLs from dynamic JavaScript page using BeautifulSoup and Selenium

Seeking to extract all URLs from a Git repository where any email addresses appear. Utilizing The script: from bs4 import BeautifulSoup from selenium import webdriver url = 'https://grep.app/search?current=100&q=%40gmail.com' chrome = " ...

Tips on retrieving and showcasing information from various endpoints in React?

I am working with two different endpoints and I need to fetch data from both simultaneously in order to display it in one single element. For example, I want to show data from one table along with the corresponding name from another table if the product id ...

Operating with a multidimensional entity

I am aiming for an object structure like this: {"Red 1":53,"Blue 2":26,"Green 3":25} Based on the following example: I attempted to push data from within .each loop into the object. However, due to its multidimensional nature, I'm uncertain how to ...