O
O
OlegSedoy2018-03-29 06:09:19
JSON
OlegSedoy, 2018-03-29 06:09:19

How to return html to json?

I'm reinventing the wheel, all that's left is to put the wheels on. Download more button. I can't figure out how to return html data.
Script:

$('.more__btn').on('click', function(event) {
    event.preventDefault();


    var exclusion = [];
    var items = $('.products__item').each(function(index, el) {
      exclusion.push($(this).attr('id'));
    });

    var data = {};
    data.action ='ajax_more';
    data.nonce_code = myajax.nonce_code;
    data.el = exclusion;

    console.log(data);
  

    $.post(myajax.url, data, function(data, textStatus, xhr) {
      if ( textStatus == 'success') {
            var response = $.parseJSON(data);
            console.log(response.bar);
            
          } else {
            console.log(textStatus);
          }
        });

  });


ajax function
if( wp_doing_ajax() ){
  add_action('wp_ajax_ajax_more', 'more_items' );
  add_action('wp_ajax_nopriv_ajax_more', 'more_items' );

  function more_items(){

    if ( empty($_POST['nonce_code'])) {
      wp_send_json_error([
        'message' => 'Извините, nonce_code не существует!'
      ]);
    }

    if ( !check_ajax_referer('9mVb5o3gZLg2wvyKslDzHRJr', 'nonce_code', false )) {
      wp_send_json_error([
        'message' => 'Извините, проверочные данные не соответствуют!'
      ]);
    }

    $exclusion = $_POST['el'];

    $args = array(
      'posts_per_page' => 1,
      'post_type' => 'product',
      'post__not_in' => $exclusion
      
    );

    $query = new WP_Query( $args );

    if ( $query->have_posts() ) {
      while ( $query->have_posts() ) {
        $query->the_post();

        $test = get_template_part('/template/loop/loop', 'product'); 
      }
    } else {
      echo "Товаров нет";
    }

    wp_reset_postdata();

    wp_send_json_success([
    "foo" => 'yes',
    "bar" => $test,
    ]);


  }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander, 2018-03-29
@lebonnet

try like this

$.ajax({
    url: myajax.url,
    type: 'POST',
    data: data,
    dataType: 'json',
    success: function (d) {
        console.info(d);
    },
    error: function (xhr, type, msg) {
        console.log(xhr, type, msg);
    }
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question