Reputation: 315
I am using PHP and Vue.js with vue-router. I've got a php form handler that sends emails. I would like to redirect the user to a certain component from my vue app when the email is sent. Is there a way to make it work? I created a component Thankyou.vue and would like to somehow embed it in my php file.
if(mail($address, $msg, $headers)) {
header("Location: http://mypage.com/thankyou");
}
Upvotes: 0
Views: 710
Reputation: 3038
I'm not too familiar with vue.js, so don't nail me down on the JS part :-)
Anyway, what you should do is POST your data to PHP with AJAX and return JSON and correct HTTP headers.
POST the data in JavaScript and handle the response promise:
this.$http.post('//someurl.bla', { key: value })
.then((response) => {
// show your thank you message
})
.catch(error => {
console.log(error);
});
Handle errors in PHP:
/**
* exits the script and returns a HTTP 400 and JSON error message
* @param str $msg error message
*/
function dieError($msg) {
http_response_code('400');
echo json_encode(['error' => $msg]);
exit;
}
// check form data
if (!$_POST['parameter']) {
dieError('Parameter "Parameter" is missing.');
}
// do stuff, build the mail content etc.
// throw an error if the mail is not sent (note the !)
if(!mail($address, $msg, $headers)) {
dieError('Error sending mail');
}
// if the script arrives here, everything was fine, the status code will be 200 OK
Upvotes: 1