I'm trying to send form data to an API for integration into a CRM. It needs to send in valid JSON format, per posting instructions. I'm having some trouble since I've never done anything like this before.
First, I gather the form data into an object, then stringify it. All variables are strings gathered from the form.
var allFormValues =
{
"First": fNameInput,
"Last": lNameInput,
"Referrer": "guid",
"Type": "guid",
"Primary": phoneAreaInput + phonePrefInput + phoneLineInput,
"Email": emailNameInput,
"Details": "question" + answer
}
var formData = JSON.stringify($(allFormValues).serializeArray());
Then, I set up an AJAX request to post it to the API
$.ajax({
type: 'POST',
url: 'theapiurl,
beforeSend: function(request) {
request.setRequestHeader('Content-Type', 'application/json');
request.setRequestHeader('Accept', 'application/json');
}
data: formData,
success: function(data) {
console.log(data);
}
});
But it's not working. Can anyone provide any guidance here? Thanks in advance.
EDIT: I can't grab form data directly since Squarespace names their form inputs weird names. I did figure this out though -- turns out my JSON construction was off. It was assigning objects to the values, so I had to use the toString() method when assigning values, like so:
var allFormValues =
{
"First": fNameInput.toString(),
"Last": lNameInput.toString(),
"Referrer": "redacted",
"Type": "redacted",
"Primary": phoneAreaInput.toString() + phonePrefInput.toString() + phoneLineInput.toString(),
"Email": emailNameInput.toString(),
"Details": details.toString()
}
then send it off with
$.ajax({
type: 'POST',
url: 'redacted',
data: allFormValues,
beforeSend: function(request) {
request.setRequestHeader('Content-Type', 'application/json');
request.setRequestHeader('Accept', 'application/json');
},
success: function(data) {
console.log(data);
},
error: function(data){
console.log(data);
}
});