abdelkader fattnassi
abdelkader fattnassi

Reputation: 29

function on Contact Form 7 submission not working

I'm using Contact Form 7 in Wordpress, What I want to do is to call a specific JavaScript function when the form I created is submited show popup successful. and this my code

    add_action('wpcf7_mail_sent', function ($cf7) {
    // Run code after the email has been sent
 $wpcf = WPCF7_ContactForm::get_current();
$wpccfid=$wpcf->id;
    // if you wanna check the ID of the Form $wpcf->id
     if ( '3854' == $wpccfid ) { // Change 123 to the ID of the form 
echo '
 <div class="modal" id="myModal2" role="dialog" style="display:block;" tabindex="-1">
    <div class="modal-dialog">
      <!-- Modal content-->
      <div class="modal-content no_pad text-center">
         <button type="button" class="close" data-dismiss="modal">&times;</button>
        <div class="modal-header heading">
          <h3 class="modal-title">Message Sent!</b></h3>
        </div>
        <div class="modal-body">

            <div class="thanku_outer define_float text-center">
                <h3>Thank you for getting in touch!</h3>
            </div>
        </div>
        <div class="modal-footer">
        </div>
      </div>

    </div>
    </div>
';
    }
});

I have an error and I don't know how to fix it

error

Upvotes: 1

Views: 1663

Answers (1)

Andrea Olivato
Andrea Olivato

Reputation: 2545

The wpcf7_mail_sent function is called in Ajax and the system expects the Ajax reply to be a JSON. So when you directly echo some HTML, that breaks the JSON and the Javascript can not parse it.

I wasn't able to find any example of usage of wpcf7_mail_sent that allowed custom HTML code, so it might not be possible to do so. The issue is that the code returns a message JSON variable and I think this should be plain text, not HTML.

Alternative 1: Edit DOM in Javascript

An alternative I've seen working is to use Javascript instead of PHP with a listener on the wpcf7mailsent event.

See example below:

<script>
    document.addEventListener( 'wpcf7mailsent', function( event ) {
            // Your code to edit the HTML goes here
    }, false ); 
</script>

You can find a bit more info on how to use this and how to get for example the form_id in this other answer: https://stackoverflow.com/a/46977796/1529324

Alternative 2: Redirect

Alternatively, you can redirect the user to a custom page, instead of showing the Ajax confirmation

<script>
document.addEventListener( 'wpcf7mailsent', function( event ) {
    if ( 'FORMID' === event.detail.contactFormId ) {
        location = 'REDIRECTURL';
    }
}, false );
</script>

Upvotes: 2

Related Questions