Form AJAX submission

Hey.

I am setting up a form but don’t want to redirect on submission but instead notify on the same page.

The form uses react-hook-form for validation.

Validation works fine but I think I am failing with the specifics around the final submission.

My form looks like the below (Box as=“form” because using ChakraUI)

    <Box
      as="form"
      data-netlify="true"
      name="callback"
      method="post"
      onSubmit={handleSubmit(onSubmit)}
    >
      <input type="hidden" name="callback" value="callback" />
   //...the rest of the form

handleSubmit is the react-hook-form function which handles validation before onSubmit happens which as I said is working fine.

In onSubmit I am doing this:

const onSubmit = (values, event) => {
event.preventDefault()

console.log(new URLSearchParams(values).toString())
// name=TEST&phone=0124567890&subject=other

fetch("/", {
  method: "POST",
  headers: { "Content-Type": "application/x-www-form-urlencoded" },
  body: new URLSearchParams(values).toString(),
}).then(res => {
  if (res) {
    alert("worked")
  } else alert("failed")
})

}

It’s within the fetch that I think I am failing. values is correctly received and can be formatted correctly. But other than that I’m not sure where I am going wrong.

I don’t think you need to use URLSearchParams to submit a form. Here’s how I do it in plain JS:

var contactForm = document.querySelector('.contact-form')
contactForm.addEventListener('submit', function(event) {
  event.preventDefault()
  var XHR = new XMLHttpRequest()
  var formData = new FormData(contactForm)
  XHR.addEventListener('load', function() {
    /* submitted */
  })
  XHR.addEventListener('error', function() {
   /* error */
  })
  XHR.open('POST', '#')
  XHR.send(formData)
})

My guess would be that, if adapted correctly, it’d work in React as well.

1 Like

Hey there,
A few suggestions: can you take a look at the request in the browser dev tools and see if it’s formatted correctly there, in the POST? If you want to drop a link to your Netlify URL where the form lives, we can give more instruction on how to do that!

The other thing is that you made need to create a FormData object and pass that to the URLSearchParams, as shown in our docs here:

Let us know how it goes!

I managed to get one of my forms working, however, I have a second form which operates in nearly the same way.

The submit of the first (working) form now looks like this

const onSubmit = (values, event) => {
event.preventDefault()
setIsSubmitting(true)

fetch("/", {
  method: "POST",
  headers: { "Content-Type": "application/x-www-form-urlencoded" },
  body: encodeFormSubmission({ "form-name": "callback", ...values }),
})
  .then(() => {
    setSuccess(true)
    setIsSubmitting(false)
    event.target.reset()
  })
  .catch(err => {
    console.log(err)
    setSuccess(false)
  })

}

This works perfectly fine. My second form (not working) looks like this:

const onSubmit = (values, event) => {
event.preventDefault()
setIsSubmitting(true)
fetch("/", {
  method: "POST",
  headers: { "Content-Type": "application/x-www-form-urlencoded" },
  body: encodeFormSubmission({ "form-name": "contact", ...values }),
})
  .then(() => {
    setSuccess(true)
    setIsSubmitting(false)
    event.target.reset()
  })
  .catch(err => {
    console.log(err)
    setSuccess(false)
  })

}

The two main differences are the values and form-name.

The values are received and encoded properly. The exact same as the working form. But when testing submission, only the first form is received, the second form seems to successfully send but doesn’t appear in the dashboard.

Hi, @neil-morgan. About this:

Our support team can help troubleshoot the actual form but not your code above. Troubleshooting third-party code like this javascript isn’t covered in the scope of our support. Even for Enterprise customers (unless they have a custom support contract), we don’t troubleshoot third-party code. My point being, we are not refusing to help because this is on the community site. We almost never troubleshoot third-party code.

Questions about custom code are welcome here on this forum but you will be relying on other community members for that troubleshooting. Someone else here may be willing to troubleshoot but our support team general speaking simply doesn’t have the bandwidth available to look at custom code.

Note, if you send us a link to the live form as Jen mentioned, our support team would be happy to take a look at what is being sent to our form handler. We cannot troubleshoot the javascript but we can confirm if the form submission to our form handler is being sent correctly or not. (In other words, we can troubleshoot the POST itself but not the code that generates it.) If that would be helpful, please let us know.

About the real form URL, you can post that information publicly or you can private message (PM) that to one of our support staff. I’ve confirmed that PMs are enabled for your community login. Please keep in mind that only one person can see the PM and this will likely mean a slower reply than posting the information publicly. Please feel free to reply to however you prefer though.

1 Like

Hello and thank you for getting back to me.

My two forms can be found here (at the bottom):

And here:

Kind regards

Neil

1 Like

Hi, @neil-morgan. I don’t know how this unresolved topic slipped through the cracks but I’m replying now.

I took a look and I think I’ve found the root cause. The form submission is using a form-name value of “contact”. However, no such form is defined in the site HTML:

https://app.netlify.com/sites/dev-site/forms

An HTML only version of the form is a requirement and there is more about this in the following support guide:

If you create a pure HTML-only version of that form somewhere, that will cause the forms processing to create the form handlers so the AJAX submissions will work as expected.

If there are any other questions about this, please let us know.