Skip to content Skip to sidebar Skip to footer

Possible To Change Names/serialization Output In Jquery?

So, I have a form that I'm submitting via JQuery/Ajax HTML:

Solution 1:

I assume you cannot change the name attributes of the form fields (e.g. name="contactfirst_name" to name="contact[first_name]").

So if you have to do it on submit, you could put the serialized post data into a variable and then do some searching/replacing to transform it to the way you want.

<script>
$(function () {
    $("button").on('click', function () {
        var formData = $('.emailsignup').serialize();

        formData = formData.replace(/contactfirst_name/, 'contact%5Bfirst_name%5D');
        // do more replacing for the other fields like the above...
        $.post("path/to/index.php", formData, function () {
            // do stuff
        });
    });
});
</script>

Solution 2:

Just save serealized data to local var. Then replace keys with a one you need.

var serialized;

serialized = $(".emailsignup").serialize();
serialized = serialized.replace(/contact([^=]+)/, 'contact[$1]');
serialized = encodeURIComponent(serialized);

$.post("path/to/index.php", serialized);

Solution 3:

So I feel like an idiot - the issue was that the data was being posted in a serialize fashion. I was able to achieve what I needed by setting ID's to each field and then renaming the names through .setAttribute. I'm sure this is super bulky and could be much more simple/elegant, but hey, I'm learning:

functionquoteRequest() {
var fName = document.getElementById("fname");
var lName = document.getElementById("lname");
var contactEmail = document.getElementById("email");
var productQty = document.getElementById("qty");
var additionalInfo = document.getElementById("additionalinfo");
var product = document.getElementById("product");
var productnum = document.getElementById("productnum");
fName.setAttribute('name', 'contact\[first_name\]');
lName.setAttribute('name', 'contact\[last_name\]');
contactEmail.setAttribute('name', 'contact\[email\]');
productQty.setAttribute('name', 'contact\[qty\]');
product.setAttribute('name', 'contact\[product\]');
productnum.setAttribute('name', 'contact\[productnum\]');
document.getElementById("quoteform").submit();
}

Post a Comment for "Possible To Change Names/serialization Output In Jquery?"