0

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");
}

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

5 Comments

Thank you very much. But do you think in this part: .then((response) => { // show your thank you message }) am I able to redirect the user using the routing made with vue.js?
And if it's not a problem, what should I use instead of //someurl.bla, the url of my own page, right?
You should be able to redirect using router.push(). The first parameter of post() is the URL of your PHP script.
I created a method and bound it to my submit button. I changed the url and added router.push(). this.$http.post('../../index.php', { key: value }) And still I get cannot read property 'post' of undefined and Cannot POST, what should I change?
cannot read property 'post' of undefined means that this.$http is not defined. Without seeing your JS code, I can't even guess why this is. Also, as I said, I am not too familiar with Vue.js, but this example looks pretty straight forward: codepen.io/tutelagesystems/pen/pjBbxQ If you still have troubles, post another question with your JS code and ask the vue.js experts for help :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.