Search code examples
jqueryajaxwordpresscontact-form-7

How to sent ajax request after Successful form submission (Contact Form 7) with multiple within tabs Bootstrap 5


I have multiple Contact Form 7 Forms within Bootstrap 5 tab panel. I want to send Ajax request to send some data after each and every successful submission. I used wpcf7mailsent to achieve this. This works only for first tab form. Not for others. All forms within tabs working well and receiving the emails from those. Only thing is Ajax request not firing in other tabs. This is the code I am using so far.

var wpcf7Elm = document.querySelector( '.wpcf7' );
    wpcf7Elm.addEventListener( 'wpcf7mailsent', function( event ) {

        var dataSet = {set of serialized data};

        $.ajax({
            type: "POST",
            url: "url",
            data: dataSet,
            dataType:"JSONP",
            success: function(response) {
                console.log( response );
            },
            error: function (data, errorThrown) {
                console.log(errorThrown);
            }
        });

    }, false );`

This works only for first tab only. Whether I gone through other all tabs, this function only works for First Tab only.

Any help highly appreciated. Thanks


Solution

  • Looking at the code you included it seems you are only selecting one element instead of all ellements change document.querySelector( '.wpcf7' ); to document.querySelectorAll( '.wpcf7' ); to apply the function to all fields

    var wpcf7Elms = document.querySelectorAll( '.wpcf7' );
    for(i=0;i<wpcf7Elms.length;i++){
    var wpcf7Elm = wpcf7Elms[i];
    wpcf7Elm.addEventListener( 'wpcf7mailsent', function( event ) {
    
        var dataSet = {set of serialized data};
    
        $.ajax({
            type: "POST",
            url: "url",
            data: dataSet,
            dataType:"JSONP",
            success: function(response) {
                console.log( response );
            },
            error: function (data, errorThrown) {
                console.log(errorThrown);
            }
        });
    
    }, false );
    }`