Converting a JavaScript array to formData

Struggling with sending an array via Ajax to PHP.

For more information, visit jsfiddle https://jsfiddle.net/CraigDavison/9spyn7ah/

 function autoPopulate() {
   var cast = "John Wayne, Julia Roberts, Kevin Spacey";
   cast = cast.split(', ');
   var arr_cast = [];

   $.each(cast, function() {
      arr_cast.push(this);
   });
   return_ajax_result('app/handlers/get_cast_ids.php', {cast: arr_cast});
}

Aiming to convert a string of movie actors into an array. This list should be associated with "Cast" as cast=[actor 1, actor 2, actor 3].

The issue arises when attempting to append this to the formData because it remains empty.

Would appreciate any insights on this matter. Thank you!

Answer №1

To create another array, you don't actually need to use the .each function because by splitting your string with commas, you are already creating an array for the variable cast. Your ajax method appears to be correct, but you can simplify it by using the request body instead of FormData since FormData is typically used for file uploads.

When handling errors, it is advisable to name your callback value something like err or error for better readability and understanding, both for yourself and others.

I have made some modifications to your code in the forked fiddle:

function autoPopulate() {
  var cast = "John Wayne, Julia Roberts, Kevin Spacey";
  cast = cast.split(', ');
  return_ajax_result('app/handlers/get_cast_ids.php', {cast});
}

function return_ajax_result(url, params) {
  var request = $.ajax({
    method: 'post',
    url: url,
    data: params,
    beforeSend: function() {
      $(".ng-loading-container").addClass("ng-loading-container-show");
    },
    success: function(result) {
      console.log(result);
    },
    error: function(err) {
      console.log(err);
    },
  });
};

autoPopulate()

You can view the updated fiddle here: fiddle

Answer №2

There is no requirement for formData in this scenario.

Simply assign the params to your data variable

  var request = $.ajax({
    method: 'post',
    url: url,
    data: params,
    ...
  });

Jquery will handle all the necessary operations automatically.

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

Angular 6: Utilizing async/await to access and manipulate specific variables within the application

Within my Angular 6 application, I am facing an issue with a variable named "permittedPefs" that is assigned a value after an asynchronous HTTP call. @Injectable() export class FeaturesLoadPermissionsService { permittedPefs = []; constructor() { ...

Switching the GET method to DELETE in nodeJS can be accomplished using an anchor tag

Let's say I have a link in my EJS file like this: <a href="/user/12">Delete</a> In my route file, I have the delete code set up like this: router.delete( '/user/:id', function ( req, res ) { // code for delete operation }); ...

Encountering a Next.js error while trying to link to a dynamic page

My current folder structure is as follows: - blog (directory) -- index.js (list of all blog articles) -- [slug].js (single article) Whenever I am inside index.js, the code looks like this: const Blog = props => { const { pageProps: { articles } } = ...

Find the total of values in an array that may be null or undefined

In this scenario, I have an array that looks like this: myData = [[2, null, null, 12, 2], [0, 0, 10, 1, null], undefined]; The goal is to calculate the sum of each sub-array, resulting in an array like this: result = [16, 11, 0]. The ...

Harness the power of Highcharts through an Ajax request to retrieve a JSON file

I am having an issue using Highcharts with a JSON file from an external server. When I try to bind the returning file to the chart in my ASP.NET MVC application, it doesn't work. Here is the code I have attempted: http://jsfiddle.net/Q6ngj/2/ jQuery ...

Display PDF blob in browser using an aesthetically pleasing URL in JavaScript

Using Node, I am retrieving a PDF from the server and sending it to my React frontend. My goal is to display the PDF in the browser within a new tab. The functionality works well, but the URL of the new tab containing the PDF is not ideal. Currently, the U ...

Utilize React-router to display child components on the webpage

Recently, I've encountered some challenges with this code. I have a component that takes in a child as a prop, which is meant to serve as the foundation for all the pages I am hosting. Base.jsx : import React from 'react'; import PropTypes ...

Trigger a PHP script to execute whenever a user updates a row in a MySQL/WordPress database

I am currently in the process of developing a small web application that will retrieve data from a specific row in a database on a WordPress based website. This data will be used to populate an announcers section for a radio station on another website. Th ...

"Unexpected error: .jqm is not defined as a

Having an issue with a jqm function that I need help with. <span class="smaller gray">[ <span class="blueonly"><a href="javascript:void(0)" rel="nofollow" onclick="javascript:jQuery(\'#s ...

A tool designed to create a function that can fetch information from a JSON file

Currently, I am working on a function that accepts arguments and combines them to form a line for searching data in a JSON file. To accomplish this, I have initialized a variable for the readFileSync and then added the function's arguments to it in or ...

Discover the step-by-step process of combining an array with JSON to create the desired outcome

I am working with a JSON array that looks like this: var row={ shopId: 3, shopName: '1', address: 'abc', contactNumber: 1234 } Alongside, I have another array: var data= [ { imageId: 1, shopId: 3, imageUrl: 'aaa' }, ...

Is it possible for me to sum up each row in the table and then deactivate it using a checkbox?

I am facing an issue with my code. The problem arises when I utilize the each() function; it iterates from the first cell to the end of the row, fetching every value along the way. What I actually want is for it to retrieve the value from each row individu ...

React is unable to identify the property that was passed to a styled-component in Material UI

Custom Styled Component Using Material-UI: import { Typography } from '@material-ui/core'; const CustomText = styled(Typography)<TextProps>` margin-bottom: 10px; color: ${({ textColor }) => textColor ?? textColor}; font-size: ${( ...

JQuery AJAX click event not triggering

I'm currently working on a project to create a dynamic website where users can update text fields directly from the site. However, I've encountered an issue on the 'admin' page where nothing happens when the button is pressed to set the ...

Webpack attempting to load build.js from a nested folder

I am in the process of setting up a Vue app with Vuetify and Vue Router. Everything works fine when I load the base URL "/", and I can easily navigate to /manage/products. However, if I try to directly access /manage/products by typing it into the address ...

Learning the process of connecting functions to events

// param {id:'buttonId', action : function(event[,param1, param2] ){}, behavior:function(event[,param1, param2] ){} } CustomButton = function(parameters) { var buttonElement = document.getElementById(parameters.id); // how c ...

Executing multiple nested `getJSON` requests in a synchronous manner using jQuery

I am facing an issue with my code that connects to an API using $.getJSON. It retrieves JSON data and then iterates three times through a for loop because the data has 3 objects. During each of these iterations, it makes another $.getJSON call to fetch spe ...

The issue of req.files being undefined in Express.js

I am aiming to upload files to s3 without depending on any middleware like multer. Below is the code snippet of my approach: <form role="form" action="/send" method="post"> <input type="file" name="photo" class="form-control"/> <button ...

Upon removing items using AJAX, the page automatically scrolls upwards

Description : Hey there! I've been working on developing an online food ordering website. Everything's going great, but I've hit a roadblock with the shopping cart feature. Problem: Whenever I try to delete an item from the cart using AJAX, ...

How can I properly implement a Closure or IIFE to manage an onclick event in ReactJS?

I'm encountering an issue while attempting to utilize the this object in an event handler. An undefined error related to the this object keeps popping up. My development stack includes ReactJS and Redux as well. class Chat extends Component { c ...