Home > Net >  Ajax with jquery callback to php file on Wordpress
Ajax with jquery callback to php file on Wordpress

Time:08-16

I have the following situation trying to use Ajax in Wordpress.

1. The file to be called has only a tiny code like: <?php echo "Whatever" ?>

2. it is to be called to and by button onclick:

<button id="ajaxbtn" onclick="showPopup()" ></button>

<div id="ajax-input"></div>

3. Functions.php

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

function myajax_data() {
   wp_localize_script('ajax-wear', 'myajax',
   array(
      'ajax_url' => admin_url('admin-ajax.php')
    )
  );
}

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

function tablo() {
    ob_start();

    get_template_part(get_stylesheet_directory_uri() . 'extra-wear' );
    $result = ob_get_contents();
    ob_end_clean();

    $return = array('content' => $result);

    wp_send_json($return);

    wp_die();
}

4. Jquery

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

5. Present output. In the console there is information that XHR finished loading: Post "http//....." but nothing is really posted.

Has someone any idea what could be wrong with that code? my quess is point. 3 Any good advise highly appreciated.

CodePudding user response:

For what I see, you have two problems:

  1. the dataType: 'json' parameter, most probably because you're not sending data in a json format
  2. the "response.content" should be just "response"

Also, no idea if the URL you pass in "myajax.ajax_url" has been declared before this bit of code?

One more thing, "success" is depreciated since jQuery 1.8, and you should now use done() instead.

With all of that considered, how about trying this and see if it works?

$.ajax({
    type: 'post',
    url: 'path/to/your-ajax-file.php',
    data: { action: 'tablo' }
}).done(function(response) {
    console.log(response);
    $('#ajax-input').html(response);
});

I added a console.log(response); line in the function so you can also see the result in your JavaScript console, remove it once your script works!

Hope that helps!

CodePudding user response:

get_stylesheet_directory_uri() is apparently not a correct way to build a path to call a file in that function. Once amended the content returned.

  • Related