x-www-form-urlencoded multiple keys in ajax

i have this code in ajax

var settings = {
    "url": "https://sample.com",
    "method": "POST",
    "timeout": 0,
    "headers": {
        "Authorization": basicauth,
        "Content-Type": "application/x-www-form-urlencoded"
    },
    "data": {
        
        "key": "value1",
        "key": "value2"
      }
};

$.ajax(settings).done(function(response) {
    console.log(response);
});

when i execute that code it only submit the value2. How can i make it submit the value1 and value2?

Answer

Having duplicate keys in an object will just have the previous values overwritten. To send multiple values with the same key with $.ajax you can pass an array as the value. By default $.ajax uses PHP style parameters so [] will be appended to your key, to avoid this you have to set the parameter traditional: true.

var settings = {
    "url": "https://sample.com",
    "method": "POST",
    "timeout": 0,
    "headers": {
        "Authorization": basicauth,
        "Content-Type": "application/x-www-form-urlencoded"
    },
    "data": {
        
        "key": ["value1", "value2"]
    },
    traditional: true,
};

$.ajax(settings).done(function(response) {
    console.log(response);
});