Home > OS >  Concatenate Ajax serialized data
Concatenate Ajax serialized data

Time:03-29

I have a form with a input field where users introduces data. I use Ajax to send it and I want for every field to send to concat. a value. So if the user introduce test. The visible result should be www.google.com/test. This is my code:

<form>
<input type="text" id="test" name="test">
</form>

Ajax

$(document).ready(function() {
    if ($("#formid").length) {
        $("#formid").submit(function(event) {
            var form = $(this);
            var url = form.attr('action');
            $.ajax({
                type: "POST",
                url: url,
                data: form.serialize(),
                //success...

And when I doo ...data: form.serialize() '&test=' testtest, it will just add another value to the id test. How can I do the concat?

CodePudding user response:

If you are sure your users have modern browsers, you can use FormData API to modify the contents, then use URLSearchParams API to serialize it, for example:

let formData = new FormData(document.getElementById('formid'));
for (let key of formData.keys()) {
   formData.set(key, 'http://'   formData.get(key))
}

var url = form.attr('action');
$.ajax({
    type: "POST",
    url: url, 
    data: new URLSearchParams(formData).toString()
}); 

Edit: an example to match a list of keys but not all keys:

let formData = new FormData(document.getElementById('formid'));
let specialKeys = ['specialKey1', 'specialKey2'];
for (let key of formData.keys()) {
   if(specialKeys.includes(key)) formData.set(key, 'http://'   formData.get(key))
}

var url = form.attr('action');
$.ajax({
    type: "POST",
    url: url, 
    data: new URLSearchParams(formData).toString()
}); 

Edit: To handle the case of duplicate keys in forms, we can't unambiguously use .get and .set methods, instead we should append the data to a new form data, for example:

let formData = new FormData(document.getElementById('formid'));
let specialKeys = ['specialKey1', 'specialKey2'];
let modifiedFormData = new FormData(); 
for (let [key, value] of formData.entries()) {
    if(specialKeys.includes(key)) {
        modifiedFormData.append( key, 'http://'  value )
    }else{
        modifiedFormData.append( key, value )
    }
}
let newDataAsString = new URLSearchParams(modifiedFormData).toString();
var url = form.attr('action');

$.ajax({
    type: "POST",
    url: url,
    data: newDataAsString,
});
  • Related