Amran
Amran

Reputation: 657

How to use `do_shortcode` with Contact Form 7 and Ajax

I made a plugin in wordpress for a form and ajax. When the page successful load the content via ajax, I want to use contact form 7 on the page. I use the do_shortcode() tag as explain on contact form 7 faqs but it's fail to display the form. Below are the example that I am doing:

function.php

add_action( 'wp_enqueue_scripts', 'ajax_test_enqueue_scripts' );

function ajax_test_enqueue_scripts() {

    wp_enqueue_script( 'season', plugins_url( '/form-submit.js', __FILE__ ), array('jquery'), '1.0', true );

    wp_localize_script( 'season', 'myAjax', array(
        'ajax_url' => admin_url( 'admin-ajax.php' )
    ));

}

add_action('wp_ajax_confirmRequest', '_myConfirmHandler');
add_action('wp_ajax_nopriv_confirmRequest', '_myConfirmHandler');

function _myConfirmHandler()
{
    if(isset($_POST['vehicle_no']))
    {
        $vehicle_no = $_POST['vehicle_no'];
        $email = $_POST['email'];

        echo "Your Data: <br>$vehicle_no <br>$email<p />";
        echo do_shortcode('[cfdb-table form="season parking form_copy" filter="your-platno=' . $vehicle_no . '"]');
        echo do_shortcode('[contact-form-7 id="6871" title="season parking form_copy"]'); 
    }

    exit;
}

form-submit.js

jQuery(document).ready(function($) {
    $('#submit_payment').click(function(e){
        e.preventDefault();
        var str = $("form[name=season-form]").serialize();
        $.ajax({
            type: "POST",
            url: myAjax.ajax_url,
            data: str + '&action=confirmRequest' 
        }).done(function(data){
            $("#result").html(data);
        });
    });
});
  1. It will just output [contact-form-7 id="6871" title="season parking form_copy"]
  2. I also use the Contact Form DB but that display the data without a problem.
  3. I made a research and found this similar problem but still I am unable to solve it. link
  4. If I write the code directly on the theme page, it will output the form without a problem. May I know how to solve it?

I am still in the processing of learning to develop with WP.

Upvotes: 0

Views: 2197

Answers (2)

BlueSuiter
BlueSuiter

Reputation: 567

Please update your WordPress, Contact Form 7 and Contact Form DB to their latest versions. I used the same for while finding for bugs in your code and found it working fine. I hope it will be helpful for you.

Upvotes: 1

heero
heero

Reputation: 268

H @Amran,

Change the below code:

add_action('wp_ajax_confirmRequest', '_myConfirmHandler');
add_action('wp_ajax_nopriv_confirmRequest', '_myConfirmHandler');

to

add_action('wp_ajax_myConfirmHandler', 'myConfirmHandler');
add_action('wp_ajax_nopriv_myConfirmHandler', 'myConfirmHandler');

See if the error still persist.

Change also your code exit() to wp_die()

Upvotes: 1

Related Questions