Issue with sending array as parameter in ajax call in Laravel

I am currently encountering an issue while attempting to pass an array through an AJAX request.

<input type="text" name="item_name[]">
<input type="text" name="address">

 $(document).on('click', '#save_info', function () {
        var address = $("#address").val();
        var item_name = $("[name^='item_name']");

       $.ajax({
            url: '/save_information',
            dataType: "json",
            type: 'POST',
            data: {
                _token: '{{ csrf_token() }}',
                address: address,
                item_name: item_name,
          }
        });
    });

Upon checking my controller, I attempted to access the item_name variable from the request but encountered an error. The code snippet below shows my attempt:

    $item_name = $request->item_name;
    $array_count = count($item_name);

This implementation is causing an error for me. Could someone provide guidance on how to correctly save array values using a loop? Thank you in advance.

Answer №1

@John Doe you have the option to make this code more concise using serializeArray.

    $(document).on('click', '#save_info', function () {
      var serializedData = $("[name^='item_name']").serializeArray();
      serializedData.push(
        {
          name: "address", value: $("#address").val()
        },
        {
          name: "_token", value: '{{ csrf_token() }}'
        },
      );
      $.ajax({
        url: '/save_information',
        dataType: "json",
        type: 'POST',
        data: serializedData
      });
    });

Alternatively, if you are utilizing a <form>, you can achieve the same with minimal code:

  $(document).on('click', '#save_info', function () {
      $.ajax({
        url: '/save_information',
        dataType: "json",
        type: 'POST',
        data: $('form#myform').serialize(),
      });
    });
`

Answer №2

The content of the item_name variable is a DOM Node rather than input values. To correct this, you should define it as either

var item_name = $("[name^='item_name']").val()
or
var item_name = $("[name^='item_name']").value

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

Error: An unexpected TypeError occurred while attempting to fetch an array or collection from MongoDB Atlas

As a beginner in the world of Express and Mongoose, I am currently working on retrieving an object from MongoDB Atlas using Mongoose.Model for educational purposes. In CoursesModel.js, I have defined the schema for my collections and attempted to fetch it ...

Retrieving time zone using offset with javascript

I am looking for a way to schedule time-based events on my server operating in UTC time. For the user interface, I need to input 2 parameters: The local time when the scheduled event should trigger The timezone offset Instead of displaying timezone n ...

Which is causing the block: the event loop or the CPU?

example: exports.products = (req, res) => { let el = 1; for (let i = 0; i < 100000000000000; i++) { el += i; } console.log(el); ... ... ... res.redirect('/'); }; If I include a loop like this in my code, which resour ...

Check to see if the property of the object does not exist within the array and update as

My goal is to add the variable content into the database content using the $push method, but only if the content.hash doesn't already exist in the database. I want to avoid duplicating information unnecessarily. return shops.updateAsync({ "user": u ...

The onClick event for "history.go(0)" is functional in Internet Explorer, but it does not work in Mozilla Firefox. What can be done to address this problem specifically for Mozilla browser?

After experimenting with different browser compatibility, I have discovered a way to clear all fields when clicking the "New" button. By using the code onClick="history.go(0)", the fields are successfully emptied in IE but unfortunately fail in Mozilla. ...

Activate Bootstrap 5 dropdown exclusively when positioned above its parent element

I am facing an issue with a Bootstrap 5 dropdown menu placed within a div. When I click the icon, the dropdown appears but only those options that overlap the parent div can be hovered/clicked. In the provided screenshot, the 'Action' option fun ...

"Drag and drop elements that automatically snap to a grid and move with

I'm trying to create a small, square div that follows the mouse cursor, but I want it to snap to a 3x3 pixel grid. Here is what I have so far: $(document).mousemove(function(e) { window.x = e.pageX; window.y = e.pageY; if(window.x % 9 === 0 ){ ...

JavaScript function is returning 'undefined' instead of an integer

My JavaScript/jQuery function is not functioning correctly and instead of returning an integer, it returns undefined. function __getLastSelectedCategory(table_id) { if ( jQuery('.categories_table[data-table-id="1"]').find('td.active&apo ...

Morgan middleware in Express.js specifically targeting unsuccessful requests for logging purposes

Currently, I am facing an issue with my middleware setup in Express.js while using Morgan. The problem arises because Morgan is only logging requests that return error code 302 (redirected), which happens when my middleware encounters an error and redirect ...

explore the route with the help of jquery scrolling feature

Is there a way to implement scrolling functionality for tab headers similar to this demo? I have a list of elements within a div that I need to scroll like the tabs in the demo. I attempted to achieve this by setting the position of the inner elements to ...

Rasa bot encountering issues with bad requests and CORS proxy problems

Rasa Core Version 13.7 NLU Version 14.6 OS Windows 10 Python Version 3.5 I have developed a Rasa chatbot and successfully trained both the NLU and dialogue models. While I was able to run the bot smoothly in the console, encountering no issues, we faced ...

Displaying the fields of the selected [object Object] in the console.log

Currently, I am utilizing "express": "3.2.6",, nodeJS v0.10.25, and "express-myconnection": "1.0.4",. The database connection appears to be functioning properly. However, when attempting to query in my view: console.log("Data: " + rows); The output rece ...

Is it possible for a Vue.js build to encounter errors due to unregistered components?

Exploring a component template... <template> <Unknown></Unknown> </template> In the context of this template, Unknown could be either a globally registered component or not. Upon encountering this scenario at runtime, an informa ...

Here is a way to retrieve the name of a ref object stored in an array using Vue.js 3 and Typescript

I have a Form, with various fields that I want to get the value of using v-model and assign them to ref objects. In order to populate my FormData object with this data, I require both the name and the value of the ref objects. Unfortunately, I am struggli ...

Attempt the axios request again if the response is null or missing

await axios .post( executeBatch, { headers: { "Content-Type": "application/json", "x-access-token": localStorage.getItem("token"), }, } ) .then( ...

Calculate the total value of each individual subject from the checkbox's data-id, presented in a string format and separated by commas

<div> <input type="checkbox" id="Q_1_ck1" value="R" data-id="Environmental Science, Physical Education, Agriculture, Yoga, "> <label class="custom-control-label" for="Q_1_ck1"> ...

Harnessing the power of VUE.js: Exploring the versatility of V-bind with Array and

I've encountered an issue with an app I'm currently working on. In my project, I am utilizing Vue.js to create the front-end and attempting to apply two classes to a div within a v-for loop. The first class is bound with a filter that functions ...

Refresh the current page with jQuery Mobile when it is clicked

I have a multi page template in jQuery Mobile. How can I refresh the current page when clicking on a hyperlink or button? I am using JQM version 1.4.5 Despite trying the code suggested in how to refresh(reload) page when click button in jQuery Mobile, it ...

Receiving a "Route not found" error even after specifying the route

I am currently using Rails version 4.2.3 and encountering an issue while attempting to create an AJAX method that calls a controller method. However, I keep receiving a no-router error. Here is the code snippet from my coffee script: updateAll = (arg) -&g ...

AngularJS Multi-select Dropdown Filter Logic

Thank you for taking the time to review my query. Currently, I am working on an AngularJS UI-Grid project where I have incorporated a Multi-select Drop-down Menu for the "First Name" column. However, I am facing challenges in implementing the logic similar ...