1

Hi I'm building a WordPress theme and I need to use contact form 7 plugin on it, but I can't figure out the correct way to send the form data to the plugin.

here is my post service:

import {
  Injectable
} from '@angular/core';

import {
  HttpClient,
  HttpHeaders
} from '@angular/common/http';

@Injectable()
export class FormsService {
  constructor(private http: HttpClient) {}

  postForm(url, form) {
    return this.http.post(url, form, {
      headers: new HttpHeaders().set('Content-Type', 'multipart/form-data'),
    })
  }
}

and the component part that use the service:

onSubmit() {
    const fd = new FormData();
    fd.append('your-name', this.name);
    fd.append('your-email', this.email);
    fd.append('your-message', this.message);
    fd.append('your-subject', this.sumbject);

    const url = `/wp-json/contact-form-7/v1/contact-forms/${this.form_id}/feedback`;

    this.sendMsg.postForm(url, fd).subscribe(
      data => {
        console.log(data);
      },
      err => console.log({
        error: err
      })
    )

    this.submitted = true;
  }

At this point the server response that the message was submitted ok, but when I go to the WP admin page, non of the field get the values.

But If I use postman with this url and params the form all works as I want.

I also found another solution that works but its not the angular way as I want to be.

the solution

 onSubmit() {
    const url = `/wp-json/contact-form-7/v1/contact-forms/${this.form_id}/feedback`;
    this.submitted = true;
  }

 sendData(url) {
    let XHR = new XMLHttpRequest();
    const FD = new FormData();
    FD.append('your-name', this.name);
    FD.append('your-email', this.email);
    FD.append('your-message', this.message);
    FD.append('your-subject', this.subject);


    // Define what happens on successful data submission
    XHR.addEventListener('load', function(event) {
      alert('Yeah! Data sent and response loaded.');
    });

    // Define what happens in case of error
    XHR.addEventListener('error', function(event) {
      alert('Oups! Something went wrong.');
    });

    // Set up our request
    XHR.open('POST', url);

    // Send our FormData object; HTTP headers are set automatically
    XHR.send(FD);
  }

1 Answer 1

4

I found my solution, the problem was on the headers definitions of my service, the correct way is:

postForm(url, body) {
  var headers = new HttpHeaders();
  headers.append('Content-Type', 'application/form-data');
  return this.http.post(url, body, {headers: headers })
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.