Home > Net >  JQuery Ajax neat way to send input arrays in the request?
JQuery Ajax neat way to send input arrays in the request?

Time:01-27

Looks like my main issue was using .val() when I should have been using map, thank you @Barmar!

Though I'm still looking for a way to achieve the second array structure at the bottom of my post. It seems like the HTML structure would have to be:

<div>
   <input type="text" name="student[1][name]">
   <input type="number" name="student[1][score]">

   <input type="text" name="student[2][name]">
   <input type="number" name="student[2][score]">

   <input type="text" name="student[3][name]">
   <input type="number" name="student[3][score]">
</div>

The challenge with this is the ID number is dynamic, so I'm not sure how to fit this in a Jquery selector. Would I just be selecting by "student" i.e.

let input_names = $('input[name^="student["]').map(function() {
    return this.value;
}).get();

I have a lot of inputs that are of the same kind so I want them in arrays, i.e.

<div>
   <input type="text" name="name_[1]">
   <input type="number" name="score_[1]">

   <input type="text" name="name_[2]">
   <input type="number" name="score_[2]">

   <input type="text" name="name_[3]">
   <input type="number" name="score_[3]">
</div>

The number in-between the brackets is the ID grouping related elements together. I want to be able to send all the values in arrays in an AJAX request but can't seem to figure it out. Only the first elements get sent, not an array

let input_names = $('input[name^="name_"]').val();
let input_scores = $('input[name^="score_"]').val();

$.ajax({
    url: "../util/funcs.php",
    async: true,
    data: {
        a: "backendFunction",
        input_names: input_names,
        input_scores: input_scores
    }
})
.done(function(data) {
    console.log("Success");
})
.fail(function() {
    console.log("Error");
.always(function() {
    // alert( "complete" );
});

I want a way to neatly send them to the backend, either as separate arrays by name parameter or ideally grouped by ID. So the $_REQUEST would look something like:

[ids] =>
    [1, 2]
[names] =>
    ["alex", "john"]
[scores] =>
    [30, 70]

Or even better:

[1] =>
    [name]  => "alex"
    [score] => "30"
[2] =>
    [name]  => "john"
    [score] => "70"

Unfortunately either way I try, the AJAX only seems to send the first of each input, rather than arrays. Please help!

CodePudding user response:

.val() only returns the value of the first element that matches the selector, not all of them. You need to loop over all the matches to get all the values.

let input_names = $('input[name^="name["]').map(function() {
    return this.value;
}).get();
let input_scores = $('input[name^="score["]').map(function() {
    return this.value;
}).get();

CodePudding user response:

Here is a solution to get your desired object format:

$(function() {
  let result = $('input').map(function() {
    return { name: this.name, value: this.value };
  }).get().reduce((acc, obj) => {
    let num = obj.name.replace(/[^\d] /g, '');
    let key = obj.name.replace(/_.*$/, '');
    if(!acc[num]) {
      acc[num] = {};
    }
    acc[num][key] = obj.value;
    return acc;
  }, {});
  console.log('result:', result);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
   <input type="text" name="name_[1]" value="Alex">
   <input type="number" name="score_[1]" value="101">
   <input type="text" name="name_[2]" value="Berta">
   <input type="number" name="score_[2]" value="102">
   <input type="text" name="name_[3]" value="Dora">
   <input type="number" name="score_[3]" value="103">
</div>

Output:

result: {
  "1": {
    "name": "Alex",
    "score": "101"
  },
  "2": {
    "name": "Berta",
    "score": "102"
  },
  "3": {
    "name": "Dora",
    "score": "103"
  }
}

Notes:

  • first, get all input elements and build an array of { name, value } objects
  • then, use a .reduce() to accumulate the desired object format
  • tweak the .replace() of num and key if you have different name input patterns
  • Related