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

Switching a material-ui input control instead of a textfield for materials-ui-datepicker: the ultimate guide

Within my React application (v16.3), I am utilizing the DatePicker component from the material-ui-pickers library to render date-picker controls. This particular component renders a Material-UI TextField. However, I am interested in modifying it to only di ...

Tips for resolving the issue of 'no serverless pages built' during deployment of a Next.js application on Vercel

Recently, I've been encountering the same two errors while trying to deploy my NextJs app: // and will just error later on Error: No serverless pages were built. You can learn more about this error here I'm stuck and unsure of how to resolve bo ...

When using Javascript's querySelector, often times it returns null

Here is the HTML code I am working with: <button class="pop-btn"> Pop </button> While I was able to style this button using CSS, I encountered a problem when trying to select it in Javascript: const Population_div_Button=document. ...

Well, it appears that I am having trouble establishing a connection between the users in this chatting application

I'm encountering a problem with establishing a connection between two users. I have already installed express and socket.io, but for some reason, the message is not getting through to the receiver's end. The code seems to be running fine as I can ...

Simple steps to update array key values in PHP

I am attempting to retrieve word counts from HTML documents stored in a specific folder. <?php $rii = new RecursiveIteratorIterator(new RecursiveDirectoryIterator('fulltext/course')); $fulltext_course_files = array(); foreach ($rii as $f) { ...

default choice in dropdown menus

I need to populate my option fields with data retrieved from a database. I encountered an error in the console: Error: [$compile:ctreq] Controller 'select', required by directive 'ngOptions', can't be found! I am confident that t ...

Dynamic Text Labels in Treemap Visualizations with Echarts

Is it possible to adjust the text size dynamically based on the size of a box in a treemap label? I haven't been able to find a way to do this in the documentation without hardcoding it. Click here for more information label: { fontSize: 16 ...

Trying to work through solving the issue of accessing document.frames["someframe"].function in Chrome instead of IE

I am encountering an issue with my code that is working in Internet Explorer but not in Chrome. try { top.document.frames["myFrame"].compare(); } catch(err) { alert("This is not executed."); } Any suggestions on how to resolve this compatibility pr ...

What is the process for uploading a file using the client's file path?

I'm fascinated by the way Sonic Living is able to identify and upload your iTunes library XML file with such ease. Unlike other upload libraries I've explored, it prompts user approval before automatically uploading the XML file based on client O ...

Retrieve the 90 days leading up to the current date using JavaScript

I've been searching for a way to create an array of the 90 days before today, but I haven't found a solution on StackOverflow or Google. const now = new Date(); const daysBefore = now.setDate(priorDate.getDate() - 90); The result I'm looki ...

Creating an image selection feature using ejs and express: a step-by-step guide

As I develop a blog site with a unique post management system using node, express, moongoDB, and EJS, everything seems to be running smoothly. However, the challenge arises when attempting to integrate Cloudinary uploaded images from my mongoDB to allow fo ...

Xpath-Utilizing a variable within an XPATH expression is necessary

Currently, I am utilizing Selenium-webdriver and facing an issue while trying to select an element based on its "text" using xpath. Since the value is subject to change, I am utilizing a variable. I am looking for a solution to resolve this problem or an a ...

Changing a URL parameter based on the element's width is a simple task when

I'm trying to display elements on a page by replacing a string in the URL parameter with the width of each element of a certain class. I'm new to JavaScript, so any help would be appreciated! Here's an example of the HTML for objects on the ...

Programmatically adding route resolve in Angular using $routeProvider

Is it possible to dynamically add Angular's resolve after it has been initially defined in the app? Let's say we have a setup with routes like this: app.config(['$routeProvider', function ($routeProvider) { $routeProvider ...

Learn how to dynamically insert input data into a table based on a specific ID in React JS!

[Help needed! I am trying to store the marks, id, and name values of each cell in objects of an array. However, I am not getting the correct answer. Can someone guide me on how to properly store the marks and id of each cell in objects of an array? const [ ...

Tips for capturing the current terminal content upon keypress detection?

After successfully installing the terminal on a test page, I am looking to highlight matching parentheses within it. This is similar to what is done in this example: I have a working solution in place and now need to integrate it with the terminal. ...

Filtering data in Laravel can be efficiently achieved by utilizing Laravel's ORM hasmany feature in conjunction with Vue

Hey there, I'm currently working with Laravel ORM and Vue 2. I've encountered some issues with analyzing Json data. Here's my Laravel ORM code: $banner = Banner::with('banner_img')->get(); return response()->json($banner); ...

Tips for integrating the connect-orientdb module with the Express framework

My objective is to establish a connection between my server code, written in nodejs using the expressjs framework, and my database which is built on orientdb. Initially, I aimed to store sessions in the database but encountered difficulties when trying to ...

The Fancybox iFrame is not appearing on the screen

I am facing an issue with the html and javascript code I have. The html looks like this: <ul> <a class="iframe" href="/posting/form?id=8"><li>Publish</li></a> </ul> and I am using the following javascript: <scr ...

Tips for designing a three-dimensional egg shape using Three.js?

I'm looking to create a unique egg shape using Three.js, but I seem to be missing the correct equation. Below is the code I currently have, utilizing LatheGeometry. Can anyone provide some guidance? var r0 = 40 var r1 = r0/4; var inc = Math.PI/r0; po ...