Search code examples
javascriptangularpostform-submitangular-httpclient

POST form to FormSubmit with HttpClient and Angular


FormSubmit is super great for easy lightweight form submission. I am using it in my Angular app and attempting to POST the form with the HttpClient, but I just can't seem to get it right. I am guessing my POST url is wrong but I am at a loss figuring out what the correct method is.

Here is my the onSubmit function:

  onSubmit() {
    this.submitted = true;
    if (this.contactForm.invalid) {
      return;
    } else {
        this.formSubmit.sendForm(JSON.stringify(this.contactForm.value));
    }
  }

Here the HttpClient service:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class FormsubmitService {
  constructor(
    public httpClient: HttpClient
  ) { }

  sendForm(formData) {
    console.log('Form Data:', formData);
    this.httpClient.post('https://formsubmit.io/send/<TOKEN HERE>', formData)
      .subscribe(
        (response) => console.log("Response:", response), (error) => console.log("Error:", error));
  }
}

Error response:

enter image description here

enter image description here


Solution

  • Good day! Can you try it out?

    onSubmit() {
      this.submitted = true;
      if (this.contactForm.valid) {
        const formData = new FormData();
        const { value } = this.contactForm;
        for (const key in value) {
          formData.append(key, value[key]);
        }
    
        this.formSubmit.sendForm(formData);
      }
    }