0

I am trying to prepare the following inputs

<input type="text" name="customer[firstname]">
<input type="text" name="customer[surename]">
<input type="text" name="customer[cuid]">

to use them in an ajax function to validate them with PHP. The array I will receive shall look like $data['customer']['firstname'].

This was my first attempt

$.each($('input[name^="customer"]').serializeArray(), function() {
    data[this.name] = this.value;
});

Problem: the array in the request looks like $data["[customer[firstname]"] and it is not pretty and I will have different keys like product[...], order[...]. Then I will need the "customer" as seperate key.

Then I thought about to remove and to replace the brackets and just to create my own array before sending. But there are more problems than I thought...

var data = {};

$.each($('input[name^="customer"]').serializeArray(), function() {
    let name = this.name.replace( ']', '' ).replace( '[', ',' ).split(',')[1];
    data['customer'].push({[name] : this.value}); // <- Error: push is not a function
    data = { 'customer' : {[name] : this.value} }; // <- Problem: data gets overwritten with the next key:value
    data['customer'][name] = this.value; // <- Error: `customer` not defined
});

This 3 examples are just a few I tried...

Does someone know how to solve this problem?

Alex Schwifty
  • 59
  • 3
  • 11
  • One possible solution: use data attribute to hold the key. `` then build array from scratch in the `each` block. I don’t think you need to serialize, either. – Tim Morton Jan 15 '20 at 23:24
  • I acuatally got it... Using ```data.customer[list] = this.value``` did it. Result will be ```Object{ customer: Object { key:value, key:value } }```, sending this with ajax call with receive the ```$_POST['data']['customer'][...]``` structure. I think I am getting a bit blind for this simple things. – Alex Schwifty Jan 15 '20 at 23:31

1 Answers1

1

Now it will works fine. Please check it.

var data = { customer: [] }; 
$.each($('input[name^="customer"]').serializeArray(), function() {
     var new_name = this.name.replace("customer[", "");
         new_name = new_name.replace("]", "");
         data['customer'].push(new_name);
         data['customer'][new_name] = this.value;
  });
rajesh
  • 209
  • 1
  • 8
  • Looks good but it does not use the "customer" as key for the array. ```array(10) { [0]=> string(30) "data[customer][firstname] : paul" [1]=> string(29) "data[customer][surname] : testname"``` – Alex Schwifty Jan 16 '20 at 13:27