I have a form pushing to Zapier. I serialize the inputs into an array and then reduce it. Here's the code I use:
$(function() {
$("#lead-gen-form").submit(function() {
const formInputSerializedArray = $(this).serializeArray();
const ajaxData = formInputSerializedArray.reduce((acc, { name, value }) => ({ ...acc, [name]: value }), {});
$.ajax({
url: "",
type: "POST",
data: { ajaxData },
dataType: "jsonp",
cache: false,
success: function(data) {
window.location = "../sent";
},
});
return false;
});
});
This results in this, which is including the name of the const and adding brackets around the name of the input, when all I really want to pull is the name of the input:
ajaxData[utm_campaign]: test
ajaxData[utm_term]: 12
ajaxData[utm_content]: comm
ajaxData[utm_medium]: email
ajaxData[utm_source]: sig
What I am looking to make it result in is:
utm_campaign: test
utm_term: 12
utm_content: comm
utm_medium: email
utm_source: sig
CodePudding user response:
When data is serialized by Ajax as JSON, it will include the name of the object being passed in so that it will create correctly formed JSON. The anonymous object created by this data: { ajaxData }
gets turned into '{ "ajaxData": { "utm_campaign": ... } }'
Simply remove the surrounding {}
(use just data: ajaxData
) and you will get the expected '{ "utm_campaign": ... }'