0

Trying out AJAX request for the first time and facing problem. I want to load a php file on button click in Wordpress site. So far after researching, I got this code:

index.php file:

<button id="ajaxbtn">Ajax</button>
<div id="ajax">Some Text</div>

ajax.php file (the file i want to be loaded):

<?php echo "Hello!" ?>

functions.php file:

add_action( 'wp_enqueue_scripts', 'myajax_data', 99 );
function myajax_data(){

   wp_localize_script('menu_toggle', 'myajax', 
     array(
       'ajax_url' => admin_url('admin-ajax.php')
     )
   );  

}

add_action('wp_ajax_tablo', 'tablo');
add_action('wp_ajax_nopriv_tablo', 'tablo');

function tablo() {

  // Grab php file output from server
  ob_start();
  include(get_template_directory_uri() . '/ajax.php');
  $result['content'] = ob_get_contents(); 
  wp_send_json($result);
}

menu_toggle.js file (js file with ajax code):

$("#ajaxbtn").click(function () {
  $.ajax({
    type : 'post',
    dataType : 'json',
    url : myajax.ajax_url,
    data : {action: 'tablo'},
    success: function(response) {
      //load the fetched php file into the div
      console.log(response);
      alert(response);
      $('#ajax').append("hello"); 
      $('#ajax').load(response.content);
    }
  });
});

I can actually get alert(response);which alerts[object Object], and $('#ajax').append("hello"); displaying, so that means that ajax was connected right way and ajax request is working correctly. But $('#ajax').load(response.content); loading the same entire index page in #ajax div instead of loading the content of ajax.php file i actually want. I probably got the wrong code either in function tablo() of functions.php file, or in ajax code of menu_toggle.js file. The console.log(response); gives crazy amount of output. Can someone please help with this one?

1

Try using get_template_part() function. use ob_end_clean() to Clean the output buffer and turn off output buffering. I have use html() to append data jQuery('#ajax').html(response.content);. I have tested and working fine for me.

jquery :

jQuery("#ajaxbtn").click(function () {
    jQuery.ajax({
      type : 'post',
      dataType : 'json',
      url : myajax.ajax_url,
      data : {action: 'tablo'},
      success: function(response) {
        jQuery('#ajax').html(response.content);
      }
    });
  });

ajax function :

add_action('wp_ajax_tablo', 'tablo');
add_action('wp_ajax_nopriv_tablo', 'tablo');
function tablo() {
  // Grab php file output from server
  ob_start();
  get_template_part( 'ajax' );
  $result = ob_get_contents();
  ob_end_clean();
  $return = array('content' => $result);
  wp_send_json($return);
  wp_die();
}
| improve this answer | |

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.