Last active
May 19, 2022 07:19
-
-
Save inorganik/846c52550db97454646054270e4f1270 to your computer and use it in GitHub Desktop.
MailChimp subscribe form with Angular 5 using jsonp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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.'; | |
}); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
What to do if want to check using localhost?