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 encountered when attempting to initiate a second screenshare on Chrome due to an invalid state

I am interested in utilizing Screensharing in Chrome. After following a guide and creating an extension to access the deviceId for getUserMedia, I was able to successfully start streaming my screen. However, when I attempted to stop the stream using the pr ...

Enhancing Bootstrap Carousel with various effects

My exploration of the web revealed two distinct effects that can be applied to Bootstrap Carousel: Slide and Fade. I'm curious if there are any other unique effects, such as splitting the picture into small 3D boxes that rotate to change the image? ...

Problem with jQuery ajax redirection

I have been using the script below to dynamically load pages on my website: var xhr; function Ajax(afile,adiv,arun,loader) { // Loading info if(loader==null) { gi("loaderdiv").style.display='inline'; } // Process Ajax var htm = afile.split(&apo ...

A guide to eliminating TextRow and inserting a string into JSON using NodeJs

To remove TextRow and add the string true to JSON in NodeJs, I have included the following code: NodeJs Code: function groupBy(objectArray, property) { return objectArray.reduce(function (acc, obj) { let key = obj[property] if (!acc[key]) { ...

Exploring the Possibilities of WebAudio API through Asynchronous Events

Is there a way to trigger events after an oscillator finishes playing using the webaudio API? I am attempting to update my Vue component reactively to display data in the DOM while a note is being played. Here's a snippet of my code: <template> ...

Where can you find the invalid character causing a syntax error in the jQuery $.ajax call?

My jQuery code is calling a WCF method, and although the method returns a Boolean true and logs successfully, the error handler displays "AJAX call failed in CallIsDataReady" with a "Syntax Error: Invalid character." This causes the callUpdateGrid function ...

Redis: Unable to establish a connection as net.connect is not recognized as a

I'm struggling to integrate Redis with nodejs Encountering issues during execution Despite using the same code, I am facing this error: Here's my code snippet: import { createClient } from 'redis' export const client = createClient({ ...

How can you customize the appearance of the filledInput component within a TextField component in Material UI?

I need some guidance on how to change the color of the FilledInput component within a TextField. Unlike InputProps, FilledInputProps are not directly accessible for styling with classes. Any suggestions on how I can customize the styling of the FilledInpu ...

Is there a way to turn off the pinch-to-zoom trackpad gesture or disable the Ctrl+wheel zoom function on a webpage

Take a look at this example - While zooming in on the image by pressing ctrl + scroll, the image zooms but the page itself does not scale. Only the image is affected by the zoom. I am attempting to replicate this functionality on my Next.js page. I have ...

Change web page in JavaScript using post data

Is there a method to utilize JavaScript for navigating to a new URL while including POST parameters? I am aware that with GET requests, you can simply add a parameter string to the URL using window.location.replace(). Is there a way to achieve this with ...

req.body is not defined or contains no data

I am facing an issue with my controllers and routers. bookController.js is functioning perfectly, but when I try to use userControllers for registration and login logic, req.body always appears empty. I tried logging the form data using console.log, but it ...

Controller Function Utilizing Private Variable in AngularJS

After stumbling upon an Angularjs example online, I found myself perplexed. The code snippet in question is as follows: angular.module("testApp",[]).controller("testCtrl", function($scope){ var data = "Hello"; $scope.getData = function(){ ...

AJAX retrieving data with a GET request

Looking to customize my page www.domain.com/page.php?x=1&y=2&z=3 Is there a way to assign values to the $_GET variables in an AJAX request using $.get()? $.get('page.php', {x: x, y: y, z: z}, function(){ }) How can I set the $_GET par ...

Storing data from an API response into the localStorage using Vue.js upon clicking

My objective is to save specific data in the browser's localStorage upon clicking a link. However, the output I receive is either undefined or completely empty. <li v-for="(category, index) in categories" :key="index"> ...

What are the steps to compile Sencha Touch using sencha-touch.jsb3?

I've been working on modifying the bundled sencha-touch.jsb3 file in an effort to decrease the size of the framework code. Here's what I've done so far: First, I downloaded the Sencha SDK Tools from I then made edits to SenchaTouch/sen ...

getting rid of the angular hash symbol and prefix from the anchor tag

I am having difficulty creating a direct anchor link to a website. Whenever I attempt to link to the ID using: where #20841 is my anchor tag. Angular interferes with the URL and changes it to: This functions properly in Chrome and Firefox, but i ...

Arranging JSON information based on category

I am currently populating an HTML table with data retrieved from a JSON file. It currently displays all the data in the order it appears in the JSON file, but I would like to organize it into different tables based on the "group" category in the file such ...

Missing parameter in the AJAX request

Looking for help with calling the AddCompare action method using an Ajax request in the View. The issue I'm facing is that the parameter sent to the AddCompare Action always has a value of zero, while the parameter value in the function AddToCompare ...

Issue occurring while trying to select an item from the dynamically generated options using AJAX

A JavaScript function is used in this code to select a specific option, with the option value being specified within a hidden element: $("select").each(function() { var id = $(this).attr('id'); var source = 'input:hidden[na ...

Send JSON data through a JQuery Ajax call and show the resulting response afterwards

I'm having trouble getting this code to work properly. I am using jQuery to capture the value of a dropdown selection, sending it via AJAX in JSON format to a PHP file, and then appending the response to a div with an id of #orderSummary. However, I n ...