0

I am using ajax to load a new post in wordpress. Here is the basic code:

function test(){
    var menuitem = document.getElementsByTagName('nav')[0].childNodes;
    for(var i= 0; i < menuitem.length; i++)
    {
        bindEvt(menuitem[i], "click", loadajax);
    }
};
function loadajax (event) {
    event.preventDefault();
    xhr = new XMLHttpRequest();
    xhr.onreadystatechange  = function(){
        var content = document.getElementsByTagName('article')[0];
        if(xhr.readyState  == 4){
            if(xhr.status  == 200) {
                content.innerHTML = xhr.responseText;
            } else{
                content.innerHTML = 'Cannot connect to server. Check your internet connection'}
        }
    }; 

    xhr.open('GET', this.href, true);
    xhr.send();

}
bindEvt(window, "load", test);

It works fine, only it loads the entire new post with menu, header, footer, etc... I only need the content and the comments. Is there any way using ajax to specifically ask wordpress for those contents or is the only way possible to do this to get the entire page and then extract only the content I need out of it and repost it?

Maybe make a specific template page for it? but how would I go about getting that working.

I hope I have been clear. Please tell me if not! First attempt at a Wordpress Theme/PHP.

Thanks for your help!

2
  • 2
    If you're willing to use JQuery, it'd be much easier and it does most of the work for you. Note how .load() can be used with a selector: api.jquery.com/load Commented Sep 9, 2012 at 22:53
  • how would it be different using jquery? It would still just load the entire page, not just the content. Commented Sep 9, 2012 at 22:55

2 Answers 2

5

You could use a template, but you'd need to write your own and it'd get a little fiddly. Andrew M.'s comment about a jQuery solution is correct, as are you: you would still be downloading the entire document, but you could only insert the part you want quite easily. See the section on loading page fragments for more details, but for the sake of expedience:

$('#result').load('ajax/test.html #container');

would load test.html and insert the contents of that document's #container element into the #result element on the parent page. Easy as pie.

This will, of course, result in as much server load and cost as much bandwidth as fully rendering the source page, though fortunately images and such will only be loaded if they're part of the rendered section. This overhead shouldn't be anything to worry about unless you have a massive amount of traffic, however.

Let's say that you want the server to just send the data you need in the first place: how you'd go about this depends on what other needs you have of the WordPress instance.

If you need to load just one page, and you don't have humans looking at the original page directly, then it's simple - write a template that consists only of:

while ( have_posts() ) : the_post();
  echo '<h2>';
  the_title();
  echo '</h2>';
  the_content();
endwhile;

and set that template for the post in question.

But if you need people to look at the post on the source page as well, you're going to have to create a theme with a singles template as described above as well as install a theme switcher plugin, and pass the necessary mojo to invoke your machine-readable theme in your AJAX request. Which is a little complicated.

Sign up to request clarification or add additional context in comments.

3 Comments

I like pure better. Only takes 3 or 4 more lines to get the right data out of it. What would be the template way in theory?
@SnippetSpace My replies were a bit too long for the comments, so I edited them into the answer.
Certainly. And if you're getting into WordPress templating... well, my condolences. :)
0

So, I came here looking for a similar solution to the one proposed by by the OP[cmplieger].

I've previously used the method described by sudowned. I made a WordPress theme like that. The page used header detection, optionally loaded the headers and then loaded the content, optionally footer.
It's a great theme and loads super fast. It's really the best method...

however...

I thought it'd be great to have something that works on browser side only though, so this post inspired me to write it:

note: This is not the way I would do this. I'd really suggest the way that sudowned suggested above. However there may be some situations that you might have no other way,

Soooo....

/* requires jQuery */
// some assumptions:
// you are using jQuery
// the pages you are calling are inside
// the same domain as the page calling them.
// 

Slice of HTML
<div id="content"> <div id="list"> <ul> <li name="//fiddle.jshell.net/isme/j4ygp3nn/show/">Page 1</li> <li name="//fiddle.jshell.net/isme/gmvj0ohg/show/">Page 2</li> </ul> </div> </div>

A splash of CSS:
#list ul { list-style-type: none;} #popc { margin-top: 20px; margin-left: 20px;} #list ul li { text-decoration: underline; color: #343434; margin-bottom: 5px; cursor: pointer;} #popcontent { background: #ffffff; border: 1px solid #000000; width: 80%; min-width: 80%; margin-left: auto; margin-right: auto; height: 80%; min-height: 300px; position: absolute; display: none; top: 10%; left: 10%; border-radius: 12px;} #x_it { text-align: center; float: right; width: 17px; border: solid 2px #000000; color: #000000; background: red; border-radius: 12px; padding-left: 0px; padding-right: 1px; padding-top: 2px; padding-bottom: 0px; margin-right: 10px;
font-family: sans-serif; font-weight: bold; cursor: pointer;}

Spread a liberal layer of jQuery:

   jQuery("#content").after("\  
      <div id=\"popcontent\">\  
           <p id='x_it'>X</p>\  
 <div id='popc'></div></div>");  

   popc = jQuery("#popc");  
   popcontent = jQuery("#popcontent");  
  jQuery("#x_it").click(function() {  
     popcontent.fadeOut("fast");  
   });  

jQuery("#list ul li").click(function()  
                                 {  
                     popc.html("");  
                     popc.load(jQuery(this).attr("name") + \  
                     " #main_content");  
                     popcontent.fadeIn("fast");  
                                 });  

`

I posted a working demo on fiddle: https://jsfiddle.net/isme/jjok5kus/34/

The real trick here is in the load call.
the second argument is "#main_content". This tells the load function to only load that element in to your chosen div. See the manual for jQuery.load()

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.