Transmit two arrays through AJAX

Initially, I aim to construct a basic array with information from the input

Then, I intend to iterate through and create an array using the rows from the table.

Insert your code here.

var first_array = {
  "warehouse": $("#warehouse").val(),
  "pricelist": $("#pricelist").val(),
  "date": $("#date").val(),
  "docstatus": "DR",
  "paymentterm": $("#paymentterm").val()
}

var second_array = []; //Credit to sagar1025 for assisting in creating the second array
$("#table_main tbody > tr").each(function() {
  var cells = $(this).find('td');
  second_array.push({
    "line": $(cells[0]).html(),
    "code": $(cells[1]).html()
  });
});

/*Here is my ajax*/

$.ajax({
  data: {
    array1: first_array,
    array2: second_array
  },
  url: "<?php echo base_url() ?>main/save_data",
  type: 'POST',
  async: false,
  cache: false,
  success: function(response) {

  },
  error: function() {
    toastr.error('ERROR', '', {
      progressBar: true,
      closeButton: true
    });
  }
});

Next, I need to iterate through the second array in my php file. Below is how I declare one variable from the first_array

$docstatus   = trim($this->input->post('array1[docstatus]', TRUE));
$array       = $this->input->post('array2[]', TRUE);

I am utilizing codeigniter

Answer №1

Here is a method to insert or append multiple elements into an array

var new_array = [];
$("#table_form tbody > tr").each(function() {
    var cells = $(this).find('td');
    new_array.push({
      "line_number": $(cells[0]).html(),
      "item_code": $(cells[1]).html()
    });
});

The Ajax request should look something like this:

$.ajax({
    data: {
        originalArray: first_array,
        updatedArray: new_array
    },
    url: "<?php echo base_url() ?>main/update_data",
    type: 'POST',
    async: false,
    cache: false,
    success: function(response) {

    },
    error: function() {
        toastr.error('ERROR', '', {
            progressBar: true,
            closeButton: true
        });
    }
});

Answer №2

It seems like there may be some confusion between arrays and objects in JavaScript. In JavaScript, arrays are represented by square brackets [], for example: var array=[1,2,3,4]. On the other hand, objects are denoted by curly braces {}, for instance: var Obj={color:"red"}.

When making an ajax call, you can send an object that contains either arrays or objects based on your requirements. For example:

var globobj={}
var first_object= {
  "warehouse": $("#warehouse").val(),
  "pricelist": $("#pricelist").val(),
  "date": $("#date").val(),
  "docstatus": "DR",
  "paymentterm": $("#paymentterm").val()
} 
var second_object= {
"line": $(celdas[0]).html(),
"code": $(celdas[1]).html()
} 
globobj.first_object=first_object
globobj.second_object=second_object

By combining both objects into the globobj, you can use it to make your ajax call seamlessly.

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

There seems to be a limitation in JS/JQuery where it is unable to append HTML that spans

I am encountering an issue with retrieving data in a div element. It seems that the function provided does not work correctly for files larger than a single line of code or even possibly a string. What can be done to resolve this? <ul class="dropdo ...

Ways to implement variables in Jade that are transmitted through res.render

Firstly, I would like to apologize for any errors in my English. In my router file, I have the following code: exports.index = function (req, res) { res.render('./game/main', {name:req.session.name, menuOp:'Home'}); } Additionally, ...

Is it possible to make asynchronous calls to an external API without causing any drag on the overall speed of the website?

Currently, I operate an online store where at the end of the page, I integrate the eBay API with items related to the main product. Unfortunately, I have noticed that this integration causes a significant delay in the overall page loading by 4 to 10 secon ...

The legends on the Google chart are having trouble being displayed accurately

Take a look at the screenshot below to pinpoint the sample issue. While loading the graph UI with Google Charts, the legends data is showing up but not appearing correctly. This problem seems to occur more frequently on desktops than on laptops. Any advi ...

Moving from the landing page to a specific tab in Ionic 2+ using dynamic navigation

Upon launching the application, users are greeted with a landing page called IntroPage, featuring two prominent buttons labeled BUY and SELL. Clicking on either of these buttons will navigate users to the corresponding buy or sell Tab. In my quest to achi ...

In order to determine if components linked from anchor elements are visible on the screen in Next.js, a thorough examination of the components

Currently, I am in the process of developing my own single-page website using Next.js and Typescript. The site consists of two sections: one (component 1) displaying my name and three anchor elements with a 'sticky' setting for easy navigation, a ...

Exploring the realm of arrays in jQuery and JavaScript

Seeking assistance as a beginner in Javascript/jQuery, I am looking for guidance on the following challenge: I have created a basic form with 7 questions, each containing 3 radio buttons/answers (except for question 5 which has 8 possible choices). My goa ...

Utilizing C in WebAssembly to return string values

Is it possible to retrieve a JavaScript string from a WebAssembly function? https://dev.to/azure/passing-strings-from-c-to-javascript-in-web-assembly-1p01 - not functional C #include <stdio.h> #include <string.h> void jsPrintString(const ch ...

"Problem with AngularJS: Unable to display data fetched from resource using ng-repeat

I am currently working on an AngularJS application that retrieves data from a RESTful API using $resource. However, I have encountered an issue where the view is not updating with the data once it is received and assigned to my $scope. As a beginner in An ...

The website that had been functioning suddenly ceased operations without any modifications

It seems like this might be related to a JavaScript issue, although I'm not completely certain. The website was working fine and then suddenly stopped. You can find the URL here - Below is the HTML code snippet: <!DOCTYPE html> <html> ...

ReactJS is giving me an error message: "Uncaught TypeError: Unable to access property 'ownerDocument' since it is null."

Trying to create a bar chart using D3 and render it with React's render method. Below is my index.js file: import React from 'react'; import ReactDOM from 'react-dom'; import './Styles/index.css'; import BarChart from &a ...

Python openpyxl Array Registration:

I'm currently working on Python code using the Openpyxl module to read and write data in Excel. I've encountered an issue with handling arrays and declaring multiple variables, making the task a bit challenging. Is there anyone who can offer assi ...

Instructions to load all distinct words from a particular file into an array and showcase them in C++

I'm currently stuck trying to figure out how to identify a unique word within a file. So far, I've managed to load all the words and store them in an array as shown below: char *arr=new char[100]; char ch; fstream my_file("name.txt"); if (!my_fil ...

To ensure that quotes are correctly handled in a string being passed to a JavaScript function within an `onclick`

I am facing an issue with a cycle in a jspx file that I have. The cycle looks like this: <c:forEach var="var" items="${dataFile.list.rows}"> <li> <div> <a href="#" onClick="myFunct('${var.url}','escape(${var ...

When using the v-for directive with an array passed as props, an error is

I encountered an issue while passing an array of objects from parent to child and looping over it using v-for. The error message "TypeError: Cannot read property 'title' of undefined" keeps appearing. My parent component is named postsList, whil ...

Transferring an image between two <td> cells within the same table

For a project, I'm working on creating a Checkers game. I have the checker board and pieces ready, but I'm struggling with the movement logic. My goal is to enable the image to move or transfer from one td element to another when clicked. A frie ...

Identify changes in attributes on elements that are updated automatically

On my webpage, I want to have two select boxes that are connected so their values always match. Here's an example: Imagine a page with two selects: <select class="myselector"> <option value='1'>1 <br> < ...

Display a progress bar that shows completion based on the maximum value supplied

I successfully created a progress bar using HTML, CSS, and Javascript. It functions perfectly up to a provided value of 100. However, if a value higher than 100 is given, the progress completes but the value continues to change until it reaches the maximum ...

Manipulating object information within a nested for loop

I have a variable called jobs in my scope, which is an array containing objects for each department along with their respective data. [ “Accounting”: { “foo” : “foo”, “bar” : "bar" }, “Delivery”: { ...

The 'propTypes' property is not found on the 'typeof TextInput' type declaration

Trying my hand at creating a react-native component using Typescript for the first time, but I ran into an issue on line 51: Property 'propTypes' does not exist on type 'typeof TextInput Couldn't find any helpful information on similar ...