I learning angular 2, and I don\'t see any example on the web to send a simple contact form from angular 2 to php scrip.
My html template.
You seem to be stuck on the interface between Angular and PHP - it's understandable because it's not as trivial as accessing variables via the $_POST
superglobal.
By default, Angular submits data passed to it in the request body as a json string, so you have to access the raw request body and parse it into usable PHP variables.
The following example shows the most basic way to do this without extra frameworks or other dependencies. You could (and should) follow better organization practices and move this content to a service, but that's adding an extra layer of complication that isn't needed here:
import { Component, OnInit } from '@angular/core';
import {Http} from "@angular/http";
@Component({
selector: 'app-mailer',
template: ''
})
export class MailerComponent implements OnInit {
email : string;
name : string;
message : string;
endpoint : string;
http : Http;
constructor(http : Http) {
this.http = http;
}
ngOnInit() {
//This data could really come from some inputs on the interface - but let's keep it simple.
this.email = "hpierce@example.com";
this.name = "Hayden Pierce";
this.message = "Hello, this is Hayden.";
//Start php via the built in server: $ php -S localhost:8000
this.endpoint = "http://localhost:8000/sendEmail.php";
}
sendEmail(){
let postVars = {
email : this.email,
name : this.name,
message : this.message
};
//You may also want to check the response. But again, let's keep it simple.
this.http.post(this.endpoint, postVars)
.subscribe(
response => console.log(response),
response => console.log(response)
)
}
}
And the PHP script. Note that this checks for multiple request methods. It checks for an OPTIONS request too. See why this is nessesary.
In order to keep this as simple as possible, I've skipped sanitizing the input from Angular, which is considered a severe security issue. You should add that in for production facing apps:
email;
$name = $params->name;
$message = $params->message;
$recipient = 'targetInbox@exmaple.com';
$subject = 'new message';
$headers = "From: $name <$email>";
mail($recipient, $subject, $message, $headers);
break;
default: //Reject any non POST or OPTIONS requests.
header("Allow: POST", true, 405);
exit;
}