Using Laravel to submit a form with identical input names via AJAX

Seeking assistance with my ajax function. A form I have is submitting data with the same input name.

Without using JavaScript, I can insert multiple input data with the same name easily,

Here is the structure of the submitted data

{"_token":"CepbQkKwKziSRwDJKuqlEa5i4E21Y5jvSbmDNvqu","id":"7","service_name":["asfd","safd"]}

However, when implementing javascript, a concatenated string is sent to the controller which makes the service_name inaccessible.

formdata: "_token=CepbQkKwKziSRwDJKuqlEa5i4E21Y5jvSbmDNvqu&id=7&service_name%5B%5D=sdfg&service_name%5B%5D=gfds&_token=CepbQkKwKziSRwDJKuqlEa5i4E21Y5jvSbmDNvqu&id=8&_token=CepbQkKwKziSRwDJKuqlEa5i4E21Y5jvSbmDNvqu&id=9&_token=CepbQkKwKziSRwDJKuqlEa5i4E21Y5jvSbmDNvqu&id=10&_token=CepbQkKwKziSRwDJKuqlEa5i4E21Y5jvSbmDNvqu&id=11&_token=CepbQkKwKziSRwDJKuqlEa5i4E21Y5jvSbmDNvqu&id=18"

This is my javascript function:

jQuery("form.ajax").on("submit", function (e) {
  e.preventDefault();
  jQuery.ajax({
    url: "/admin/adminpanel/insertService/",
    type: "post",
    data: {
      formdata: $(".ajax#servicesForm").serialize()
    },
    dataType: "JSON",
    success: function (response) {
      console.log(response);
    },
    error: function (jqXHR, exception) {
      var msg = "";
      if (jqXHR.status === 0) {
        msg = "Not connect.\n Verify Network.";
      } else if (jqXHR.status === 404) {
        msg = "Requested page not found. [404]";
      } else if (jqXHR.status === 500) {
        msg = "Internal Server Error [500].";
      } else if (exception === "parsererror") {
        msg = "function Requested JSON parse failed.";
      } else if (exception === "timeout") {
        msg = "Time out error.";
      } else if (exception === "abort") {
        msg = "Ajax request aborted.";
      } else {
        msg = "Uncaught Error.\n" + jqXHR.responseText;
      }
    }
  });
});

Here is my PHP Controller Function:

public function insert(Request $request)
{
    
     return response()->json($request);
}

Answer №1

Utilize the FormData Object to easily send form data

const formData = new FormData();

formData.append("input-name", value1);
formData.append("input-name2", value2 OR array of values);


jQuery.ajax({
url: "/admin/adminpanel/insertService/",
type: "post",
data: {
  formData: formData
}

Answer №2

After some experimenting, I came up with a solution:

To start, I initialized an array and stored all occurrences of input[name='service_name[]'] in it.

Next, I used ajax to send the data and successfully inserted it.

var serviceArray = new Array(), id;
jQuery.map($("input[name='service_name[]']"), function(obj, index) {
    serviceArray.push($(obj).val());
});

This is how my ajax script looked like:

jQuery.ajax({
    url: "/admin/adminpanel/insertService/",
    type: 'post',
    data: {
        'service_name': serviceArray,
        'id': id
    },
    dataType: 'JSON',
    success: function(response) {
        console.log(response);
    }
});

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

Employing the Map function in React leads to an error that is undefined

Upon simplifying my code, it seems that I am encountering an unresolved issue with the map function being used in different locations. I have noticed that code from examples running on platforms like Codepen does not work in my locally created react app p ...

Navigating a collection of objects in JavaScript: A step-by-step guide

My data consists of objects in an array with the following structure: [{\"user\":\"mcnewsmcfc\",\"num\":11},{\"user\":\"ManCityFNH\",\"num\":7}]; To clean up the array, I'm using this code: ...

Storing a JavaScript array in a MySQL table using Ajax and PHP

Currently, my goal is to pass an array through AJAX to PHP and then save it in a table. The PHP script (running on a WAMP server) <?php $servername = "localhost"; $username = "root"; $password = "xx"; $dbname = "xx"; $myArray = $_POST['myAr ...

Ensure the Firebase real-time database in Javascript purges the active session upon tab or browser closure

I need to implement a feature in my Firebase real-time database project using JavaScript where the current session is logged out automatically after closing the tab or browser. When I log in with my email and password, if I copy the URL and paste it into ...

Having trouble updating the sequelize-cli configuration to a dynamic configuration

Encountering an issue while attempting to switch the sequelize-cli configuration to dynamic configuration, following the instructions in the documentation. I have created the .sequelizerc-file in the project's root directory and set up the path to con ...

Utilizing jQuery for seamless communication between parent and child iFrame windows

On my webpage, there is an iFrame containing a table where I want to add a click event to the rows. The challenge is retrieving the selected row within the iFrame from the parent window. The goal is to define a class for a clicked table row like this: $( ...

This TypeScript error occurs when the props are not compatible and cannot be assigned to

Hello fellow Internet dwellers! I am a novice in the world of coding and TypeScript, seeking some assistance here. I am attempting to extract an array of objects from props, transform it into a new object with specific information, and then return it - ho ...

Ways to retrieve the text of the chosen radio button label with the help of jQuery

There is a radio button on my webpage that looks like this: <div id="someId"> <label class="radio-inline"> <input name="x" type="radio" onchange="GetSelectedVal();">Yes</label> <label class="radio-inline"> ...

Mapping choices array in ReactJS using the id as a key reference

Looking for assistance with JavaScript as I am relatively new to it. I have a page displaying scheduled exams, and clicking on "Learn more" opens a modal where you can edit exam details. Currently, the modal displays selected equipment and allows changing ...

I am experiencing difficulty with Three.js rendering textures from my planet constructor function

I am facing an issue with my function that is supposed to create a 3D object (a planet) using orbital parameters and texture images from a dataset. Strangely, the textures are not rendering when I use StandardMaterial or PhongMaterial, even though they wor ...

Incorporating a new parameter into the JSON response from SoundCloud

Currently, I am in the process of developing an app utilizing the SoundCloud JavaScript API. My approach involves fetching the JSON data from: http://api.soundcloud.com/resolve.json?url=http://soundcloud.com/matas/hobnotropic&client_id=YOUR_CLIENT_ID ...

JavaScript code to use Angular expressions in an HTML document

I am facing an issue with using Angular expressions inside JavaScript within an ng-repeat loop on my HTML page (note that the app and controller have been declared elsewhere): <div ng-repeat="eleRubrique in scopeComplet"> <script type="text ...

How can I animate SVG paths to fade in and out sequentially?

My current code is causing the path to fade in/out all at once instead of one after the other var periodClass = jQuery(this).parent().attr("class"); jQuery("svg path").each(function(i) { var elem = jQuery(this); if (elem.hasClass(periodClass)) ...

Tips for arranging a group of objects based on a nested key within each object

i have a collection of objects that I need to sort based on their id. here is the information: { 1918: { id: "1544596802835", item_id: "1918", label: "Soft Touch Salt Free Mint 500 ml (000001400045)", combo_items: false } 6325: { ...

Can you increase all px measurements in Notepad++ by a factor of X?

Looking for help with a large HTML image map that contains over 3000 lines of images with specific top/left pixel positions. I'd like to replace these images with larger ones, which would require increasing all the pixel references by a certain amount ...

Using jQuery to dynamically add a value to a comment string

Is there a way to dynamically include tomorrow's start and end times in the message for the setupOrderingNotAvailable function if today's end time has passed? The current message states that online ordering will be available again tomorrow from 1 ...

What is the method for retrieving the title element from the Json data?

I am attempting to extract JSON data from http://omadbapi.com/?s= for a search script, but I am encountering difficulties in retrieving the Title element from this particular JSON: { "Search": [{ "Title": "Sherlock Holmes: A Game of Shadows", ...

Converting a string into a regular expression using JavaScript

I am attempting to change the color of a text element when specific variations of the word "hello" are entered into an input field. While this works with a regular string comparison, it fails when using a regular expression. <input id="input" type="inp ...

Is there a way in Vue.js to create a description list (dl) using v-for?

The v-for directive in vue is truly remarkable. I am currently faced with a situation where I need to create a description list similar to this. To achieve this, I have to generate two DOM elements for each item in my array: <dl class="row"> < ...

The extent of locally declared variables within a Vue component

Within this code snippet: <template> <div> <p v-for="prop in receivedPropsLocal" :key="prop.id" > {{prop}} </p> </div> </template> <script> export default ...