I am requesting something using WP AJAX through admin-ajax.php .

But I've noticed, that response from my ajax hook is modified by admin-ajax.php - it buffers the hook function output and posts back the whole HTML tree - the whole template, including header, footer, content template....

Is there a cleaner way how to request ONLY content outputted by the hook function than wrapping header, footer, etc. in conditions?


HTML & JS in frontend display PHP file

  <div id="ajaxTester">AT</div>
  $('#ajaxTester').click( function(){
    //!!!HERE WAS A MISTAKE - MISSING "ECHO" BEFORE "admin_url"!!!
    $.post( '<?php admin_url('admin-ajax.php'); ?>', { "action" : "myAjaxFunc" }, function( data ){
      $('body').append( data );
    } );
  } );

Added to functions.php

  function myAjaxFunc(){
    //... some output
    echo "some output";    
  add_action("wp_ajax_myAjaxFunc", "myAjaxFunc"); 

Note: it seems like it's taking the output as a post and trying to push it through theme template...

EDIT2 - found it:

I forgot to put echo before admin_url('admin-ajax.php'); so it was requesting home page and sice homepage was using function to display also first few posts, it "worked",

Now only extra-content problem left is that it's adding 0 code after the output - this was actually solved here already:

Why does WordPress add 0 (zero) to an Ajax response?

  • 2
    What you describe is not done by admin-ajax.php as default. Can you post your code? – cybmeta Apr 24 '15 at 10:50
  • You code doesn't say much. With that info your problem can not be reproduces. Please, add all the relevant code or we can not help you. – cybmeta Apr 25 '15 at 9:30
  • If that is all the relevant code, I think nobody here can tell you why your ajax request is loading footer, header and so on because we can not reproduce the issue. You say "maybe the function is ....", who knows, post the code. – cybmeta Apr 25 '15 at 11:01
  • You see, you posted the code and we can see the problem, including you. ;) – cybmeta Apr 25 '15 at 11:38
  • 1
    By the way, you forget to die() or exit() at the end of myAjaxFunc() after the output is sending out. – cybmeta Apr 25 '15 at 11:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.