开发者

Ajaxed loaded content doesn't behave as it should

开发者 https://www.devze.com 2023-04-04 13:55 出处:网络
There is a page template called post-plain-body that prints the title and body of the post passed. The page named AjaxLoader uses this template. If for example I call /ajaxloader with id as a $_POST[\

There is a page template called post-plain-body that prints the title and body of the post passed. The page named AjaxLoader uses this template. If for example I call /ajaxloader with id as a $_POST['id'] value, the contents of that post will be displayed.

This is called via jQuery on the main page. It actually loads the contents of a post/page to a specific context.

One of the pages I load, contains a Contact Form 7 form. The form is displayed but when I submit it, it goes to a /ajaxloader/#wpcf7-f2-p34-o1 instead of using Ajax to validate the form.

This is the page template.

<?php
/*
Template Name: Ajax Loader
*/

// Load contact form 7 scripts
if ( function_exists( 'wpcf7_enqueue_scripts' ) ) {
    wpcf7_enqueue_scripts();
   开发者_运维问答 wpcf7_enqueue_styles();
}

// Gets the content only from a post. Used in ajax loading
if(isset($_POST['id'])):
    $post = get_post($_POST['id']);
    if ($post) : setup_postdata($post); 
        ?>
        <div <?php post_class() ?> id="post-<?php the_ID(); ?>">
            <h2><?php the_title(); ?></h2>
            <?php the_content(); ?>
        </div><?php
    endif;
else:?>
    <h2>Page not found</h2><?php
endif;
?>

And the jQuery that is loading the content is the following

function load_page(pid) {
    $("#page_preview").load("ajaxloader/", {id:pid},function(){
        $('#page_preview').fadeIn(300);
        $('#page_loading').hide();
    });
}

EDIT

The <form> isn't attached to the Contact Form 7 scripts as it should. I found this using javascript debugging in firebug. Normally, it should have two handlers attached to click and submit events. Any suggestions why it isn't attached?


It looks like contact-form-7 is calling load_page() function upon submit. You might want to check how you have defined the event handler that is calling load_page().

It might also be that contact form 7 uses a function of the same name load_page() and causing some conflicts.

You should give us the weighted down version on jsfiddle.


I found the solution. Might seem trivial to somebody, but anyway I thought I should share.

On page templates that you use to load content only (no headers, sidebars etc) using Ajax, do the following:

  1. add wp_head();
  2. add the page template (as in the question above)
  3. add wp_footer(); to the bottom

If somebody has more info on the procedure, please contribute :)


Call this on AjaxComplete:

var ajaxContainer = $('#somediv_id'),
    newCF7 = $('.wpcf7 > form', ajaxContainer);
    newCF7.attr('action', "#" + newCF7.attr('id'));
    wpcf7.initForm( newCF7 );
0

精彩评论

暂无评论...
验证码 换一张
取 消