skip to Main Content

it may seem stupid, but i’m in it for a week, help me …

the "response" in xhr dev-tools chrome does not leave "0", it never returns the array I need …

Javascript code to get data from wordpress

$(document).on("click", "[data-show-home-list-series]", function () {
                var id = $(this).attr("data-show-home-list-series");
                $("[data-show-home-list-series]").removeClass("active");
                $(this).addClass("active");
                var $list = $("#homeSliderSerieList");
                $.post("wp-admin/admin-ajax.php", { getHomeSliderSeries: id }, function (html) {
                    var data = jQuery.parseJSON(html);
                    if (data.status == "success") {
                        var listing = data.list;
                        var lister = [];
                        for (var i = 0; i < 20; i++) {
                            var row = listing[i];
                            lister.push(seriePoster(row.url, row.rating, row.poster, row.title, row.cat, row.episode));
                        }
                        $list.parent(".itemsList").addClass("fadingOut");
                        setTimeout(function () {
                            $list.html(lister.join(""));
                            $list.trigger("destroy.owl.carousel");
                            createItemSlider();
                            $list.parent(".itemsList").removeClass("fadingOut");
                        }, 200);
                    } else {
                        return false;
                    }
                });
            });

PHP file to return data in array json to javascript show results in html.

wp-admin/admin-ajax.php (theme/inc/core/ajax.php)


function getHomeSliderSeries(){
// i Want see that bellow in xhr response to javascript:    
//{"status":"success","list":{}}

}

add_action( 'wp_ajax_getHomeSliderSeries', 'getHomeSliderSeries' );
add_action( 'wp_ajax_nopriv_getHomeSliderSeries', 'getHomeSliderSeries' );

My language is not very good, i hope you undestand, thanks atentiton!!

2

Answers


  1. The data you send in $.post is missing an action property. This property is responsible for telling the admin-ajax.php which function that is registered with a wp_ajax_{function_name} hook should be called.

    The value in the action property should match the function_name in wp_ajax_{function_name} and wp_ajax_nopriv_{function_name} to be called properly.

    Combine the action property with other properties that you want to send to the backend to pass the data that you need to send.

    // Set the action and get the id.
    var action = 'getHomeSliderSeries';
    var id = $(this).attr("data-show-home-list-series");
    
    // Create object to send data to backend.
    // This must include an action property with 
    // the name of the function on the backend.
    var postData = {
      action: action,
      id: id,
      example: 'Send any data as a property. You can also nest objects and arrays.'
    };
    
    $.post("wp-admin/admin-ajax.php", postData, function(response) {
      if (response.status == "success") {
        console.log(response);
      }
    }, 'json'); // Expect JSON from the backend. Now you don't need to parse.
    

    Now on the server side your getHomeSliderSeries should be called. All the other properties (action included) can now be accessed through the global $_POST variable with their corresponding keys.

    For a response, create an associative array with the data you want to return. This is the equivalent of an object in JavaScript. Encode the array to JSON and send it back. Now the frontend should see an object as a response.

    function getHomeSliderSeries(){
      // Get the id from the post request.
      $id = isset($_POST['id']) ? $_POST['id'] : null;
      $example_string = isset($_POST['example_string']) ? $_POST['example_string'] : null;
    
      // Create an associative array for the response.
      $response = array(
        'status'   => 'success',
        'id'       => $id,
        'example'  => $example_string
      );
    
      // Return the array as a JSON string.
      return json_encode($response);
    
      // Cuts connection by stopping the function.
      die(); 
    }
    
    add_action( 'wp_ajax_getHomeSliderSeries', 'getHomeSliderSeries' );
    add_action( 'wp_ajax_nopriv_getHomeSliderSeries', 'getHomeSliderSeries' );
    
    Login or Signup to reply.
  2. Try ajax callback function in functions.php

    function swt_ajax_data() {
      $id = isset($_POST['id']) ? $_POST['id'] : '';
    
      // Create an associative array for the response.
      $responsedata = array(
       'id'       => $id,
      ); 
      $result = array();
      
      // if need featch the data from the template un comment the bellow five lines and commented the sixth line
      //ob_start();
      //include('templatepatj');
      //$opr_html .= ob_get_contents();
      //ob_get_clean();
      // $result['data'] = $opr_html;
    
    
      $result['data'] = $responsedata;// POST array data.
      }
      return wp_send_json_success($result);
      }
    }
    
    add_action('wp_ajax_swt_ajax_data', 'swt_ajax_data');
    add_action('wp_ajax_nopriv_swt_ajax_data', 'swt_ajax_data');
    

    Localize your script and pass the admin ajax url

    // Register the script
      wp_register_script( 'ajax-script', 'path/to/myscript.js' );
       // Localize the script with new data
       $js_array = array(
       'ajaxurl' => admin_url('admin-ajax.php'),
    );
    wp_localize_script( 'ajax-script', 'swtobj', $js_array );
    // Enqueued script with localized data.
    wp_enqueue_script( 'ajax-script' );
    

    Try Js as like below.

    $(document).on("click", "[data-show-home-list-series]", function () {
      var id = $(this).attr("data-show-home-list-series");
      $("[data-show-home-list-series]").removeClass("active");
      $(this).addClass("active");
      var $list = $("#homeSliderSerieList");
    
      var data = {
      'action': 'swt_ajax_data', 'id': id
      };
      $.ajax({
        url: swtobj.ajaxurl,
        type: 'POST',
        data: data,
        cache: false,
        dataType: 'json',
        success: function (response, textStatus, jqXHR) {
          var response_data = response.data.data;
          if (response_data != "" || response_data.length != 0) {
            console.log(response_data);
            // write your code here
          } else {
            // write your code here
          }
        },
      });
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search