frollo February 2016

Wordpress AJAX request always return 0

I'm developing a WordPress theme and in my frontend I need to show some information when the user hovers over a post preview. I use AJAX to retrieve the needed information instead of loading extra data for each post, but all my AJAX queries return 0.

This is an excerpt of my functions.php:

add_action( 'wp_ajax_nopriv_pgsc_ajax_get_supporters', 'pgsc_ajax_get_supporters' );
add_action( 'wp_ajax_pgsc_ajax_get_supportes', 'pgsc_ajax_get_supporters' );

function pgsc_ajax_get_supporters()
{
  $politicianId = $_POST['postId'];
  $field = get_field_object('lista', $postId);
  $values = get_field("lista", $postId);
  $lists = array();
  foreach($values as $val) {
    $listName = $field["choices"][$val];
    $logo = get_field("logo", $val)["sizes"]["thumbnail"];
    $lists[$listName] = array("permalink" => get_post_permalink($val), "logo" => $logo);
  }
  wp_reset_query();
  echo json_encode($lists);
  wp_die();
}

And this is the AJAX call from my JavaScript:

function open_supporter_bar(postId, barId)
{
  var bar = "#bar_" + barId;
  jQuery(bar).hide("slow");
  jQuery(bar).html("");
  jQuery.ajax({
    url : pgsc.ajaxurl,
    type : "POST",
    data : {
      action : "pgsc_ajax_get_supporters",
      postId : postId
    },
    success : function(result) {
      alert(result);
      html = compose_supporter_list(result);
      jQuery(bar).html(html);
      jQuery(bar).show("slow");
    },
    error : function(error) {
      alert("Check the error log!");
    }
  });
}

I've already tried replacing wp_die() with die() but the result is the same

Answers


Musa February 2016

Use wp_send_json to output json for a wordpress ajax request

add_action( 'wp_ajax_nopriv_ajax_pgsc_supporters', 'pgsc_ajax_get_supporters' );
add_action( 'wp_ajax_pgsc_supporters', 'pgsc_ajax_get_supporters' );

function pgsc_ajax_get_supporters(){
    $politicianId = $_POST['postId'];
    $field = get_field_object('lista', $postId);
    $values = get_field("lista", $postId);
    $lists = array();
    foreach($values as $val){
      $listName = $field["choices"][$val];
      $logo = get_field("logo", $val)["sizes"]["thumbnail"];
      $lists[$listName] = array("permalink" => get_post_permalink($val), "logo" => $logo);
    }
    wp_reset_query();
    wp_send_json($lists);
}


Mark February 2016

you have misspelled your function on the action hook.

add_action( 'wp_ajax_pgsc_ajax_get_supportes', 'pgsc_ajax_get_supporters' );

should be:

add_action( 'wp_ajax_pgsc_ajax_get_supporters', 'pgsc_ajax_get_supporters' );

Post Status

Asked in February 2016
Viewed 2,676 times
Voted 5
Answered 2 times

Search




Leave an answer