0

Need some help, I use the latest version of the plugin and WP.

I have even set up a blank test theme just to confirm that my actual theme is not the problem.

Basically, I have a Contact Form 7 on one page. If this page is loaded directly in the browser, the content and the form are shown as they should be.

If I load this page via ajax, the content is shown as it should be but the form is not. Instead only the shortcode of the Contact Form 7 plugin is shown.

Here is the example function from the test theme.

function th_test_ajax()
{
$page_id = $_POST['page_id'];

$args = array(
    'page_id' => $page_id,
    'post_status' => 'publish',
    'post_type' => array('page')
);

$wp_query = new WP_Query($args);

if ($wp_query->have_posts())
{
    while ($wp_query->have_posts())
    {
        $wp_query->the_post();

        the_content();
    }
}

die();
}
add_action('wp_ajax_load_content', 'th_test_ajax');
add_action('wp_ajax_nopriv_load_content', 'th_test_ajax');

Here is the jQuery part.

jQuery(document).ready(function($) {
$('body').on('click', '#load_page', function(e){
    e.preventDefault();

    $.ajax({
        type: 'POST',
        url: th.ajax_url,
        data: { action: 'load_content', page_id: $(this).data('page-id') },
        cache: false,
        dataType: 'html'
    }).done(function(response) {
        $('#content').html(response);
    });
})
});

Here is the index.php, the "data-page-id='29'" is the page where the shortcode is.

<html>
<?php
wp_head();
?>
<body>
<div id="content">
<p>
<?php
if (have_posts()) 
{
    while (have_posts())
    {
        the_post();

        the_content();
    }
}
?>
</p>
<p id="content">first content!</p>
<a href="/kontakt" id="load_page" data-page-id="29">ajax</a>
</div>
</body>
<?php
wp_footer();
?>
</html>

I have even tried other plugins that have shortcode and added them to the same page and they work via ajax.

Only the Contact Form 7 for some reason is not working.

Any ideas?

user3537395
  • 83
  • 1
  • 6
  • You can't output shortcode using ajax. Because when doing ajax request the `admin-ajax.php` doesn't know about `shortcodes.php` file. You don't have access to whole wp environment when request with ajax. – Rahil Wazir Apr 15 '14 at 19:18
  • If I use a random plugin that requires shortcodes, it works, why if there isn't access to the whole wp environment via admini-ajax.php? That's the thing that confuses me. If all shortcodes would not be working via admin-ajax.php then okay, makes sense. But all that I've tried do work except for the contact form 7. – user3537395 Apr 16 '14 at 08:24
  • I suggest you to see this http://stackoverflow.com/a/13614297/2706988 answer – Rahil Wazir Apr 16 '14 at 08:35

1 Answers1

0

You need to call this:

var ajaxContainer = $('#somediv_id'),
    newCF7 = $('.wpcf7 > form', ajaxContainer);
    newCF7.attr('action', "#" + newCF7.attr('id'));
    wpcf7.initForm( newCF7 );
Tusko Trush
  • 422
  • 3
  • 15