jquery ajax load php into specified div

I’m trying to load a php file into a div#main when a link is clicked. The html content loads but the actual php code included in the file does not. Here’s what I’ve got:

Link to trigger everything:

Read More
<a id="nav" href="http://domain.com/inc/file.php">

jQuery:

jQuery(document).ready(function($) {

    $("#nav").on('click', function (e) {
        e.preventDefault();
        $("#main").empty();

        $.ajax({
            url: $("#nav").attr('href')
        }).done(function(data) { 
            $('#main').html(data); // display data
        });
    }); 

});

Code from file.php (mostly WordPress functions):

<div id="hostels" class="section cf">

    <?php get_a_post(31); ?>

    <article id="swiss" <?php post_class('swiss bg col span-1-3'); ?> role="article">
        <h3>
            <a href="<?php the_permalink(); ?>">
                <span class="logo-pl-small"><?php include(TEMPLATEPATH . '/library/svg/logo.svg'); ?></span>
                <span class="">Swiss Cottage &ndash; London UK</span>
            </a>
        </h3>
        <?php if ( has_post_thumbnail()) { the_post_thumbnail(); } ?>
        <div class="entry-content">
            <?php the_excerpt(); ?>
            <?php edit_post_link( __( 'Edit', 'bonestheme' ) ); ?>
            <?php if ( get_post_meta($post->ID, 'vidlink', true) ) { 
                echo apply_filters('the_content', get_post_meta($post->ID, 'vidlink', true)); 
            } ?>
         </div>
    </article>

</div>

OUTPUT:

<div id="main">
    <div id="hostels" class="section cf">
    </div>
</div>

The file begins to load but as soon as <?php get_a_post(31); ?> is reached, the file does not continue to load.

I could be wrong, but I thought that by using $.ajax the php code would execute on the server and code it outputs would load into my #main div.

Related posts

Leave a Reply

2 comments

  1. So I’ve got this somewhat working.
    I found this tutorial for Ajax Powered Loops with jQuery and WordPress from which I discovered that (as I had guessed) the files I created need to understand WordPress functions. For this I need to include:

    require_once('../../../../wp-load.php');
    

    In my case that’s the relevant path from file.php.

    There’s still some issues such as shortcodes generated from plugins not working fully, but that’s beyond the scope of my original question.

    There’s a lot of useful info relating to ajax and WordPress in the tutorial above though, if anyone is having similar issues I’d recommend having a read.

  2. Instead of

    $.ajax({
      url: $("#nav").attr('href')
    }).done(function(data) { 
      $('#main').html(data); // display data
    });
    

    why not the more simple

    $("#main").load('http://domain.com/inc/file.php');
    

    ??