Skip to content

Instantly share code, notes, and snippets.

@inorganik
Last active May 19, 2022 07:19
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save inorganik/846c52550db97454646054270e4f1270 to your computer and use it in GitHub Desktop.
Save inorganik/846c52550db97454646054270e4f1270 to your computer and use it in GitHub Desktop.
MailChimp subscribe form with Angular 5 using jsonp
import { Component } from '@angular/core';
import { FormControl, Validators } from '@angular/forms';
import { HttpClient, HttpParams } from '@angular/common/http';
interface MailChimpResponse {
result: string;
msg: string;
}
@Component({
selector: 'email-subscribe-form',
templateUrl: './email-subscribe-form.component.html'
})
export class EmailSubscribeForm {
submitted = false;
mailChimpEndpoint = 'https://username.us6.list-manage.com/subscribe/post-json?u=abc123&id=123&';
error = '';
constructor(private http: HttpClient) { }
// reactive form components
emailControl = new FormControl('', [
Validators.required,
Validators.email,
]);
nameControl = new FormControl('', [
Validators.required
]);
submit() {
this.error = '';
if (this.emailControl.status === 'VALID' && this.nameControl.status === 'VALID') {
const params = new HttpParams()
.set('NAME', this.nameControl.value)
.set('EMAIL', this.emailControl.value)
.set('b_123abc123abc123abc123abc123abc123abc', ''); // hidden input name
const mailChimpUrl = this.mailChimpEndpoint + params.toString();
// 'c' refers to the jsonp callback param key. This is specific to Mailchimp
this.http.jsonp<MailChimpResponse>(mailChimpUrl, 'c').subscribe(response => {
if (response.result && response.result !== 'error') {
this.submitted = true;
}
else {
this.error = response.msg;
}
}, error => {
console.error(error);
this.error = 'Sorry, an error occurred.';
});
}
}
}
@pathikvejani
Copy link

What to do if want to check using localhost?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment