Search code examples
javascriptphpwordpresscontact-form-7

How do I return variables from serverside back to the clientside script?


I found this article by the plugin author: https://contactform7.com/redirecting-to-another-url-after-submissions/ but the problem is that it redirects to a URL that is known beforehand. I need to know the URL as a response from the server, because the redirect URL will depend on the submitted values.

I can log the event:

document.addEventListener('wpcf7mailsent', function(event) {
    console.log(event);
}, false);

But I am not at all sure how much of the data is provided by the server and how much by the client script. I tried altering the submission like this:

add_action('wpcf7_posted_data', 'alter_input');

function alter_input($data) {
    $data['your-message'] = 'Something totally different here.';
}

But my alteration seems to have no effect on what data the event object contains. I have trouble finding where exactly the response (if any) is formulated and what filters or actions apply.

EDIT: I reworded the question; too many answers and comments get stuck into the why, which is irrelevant, or try to suggest "other approaches", which isn't what I asked, instead of just sticking to the how.


Solution

  • Well, I managed to find what I was looking for. The AJAX request to the server returns actually only three variables, eg:

    {
        into:"#wpcf7-f19-p59-o1",
        message:"An error occurred. Please try again later.",
        status:"mail_failed"
    }
    

    So no luck there. There is no hook or filter to modify the response serverside, to add more variables. And even if there was a way, the clientside javascript is not coded in such a way that it would be easy to overwrite singular methods to achieve the functionality that I want. It would require an ugly copy pasta of hundreds of lines to change just a couple little things.

    Thus my verdict is that this is not doable, at least not for now, unless the plugin author decides to make some changes that could accommodate this kind of functionality, wink wink. I'll just implement a form processing action myself. That'll be less work.