2015-06-18 5 views
1

Plugin Class Файл:Wordpress - Вызов Ajax URL в плагин

function __construct() 
{ 
    add_shortcode('user_registration_form', array(
    $this, 
    'shortcode' 
)); 
} 
public function hook() 
{ 
    add_action('wp_ajax_get_product_serial_callback', 'get_product_serial_callback'); 
    add_action('wp_ajax_nopriv_get_product_serial_callback', 'get_product_serial_callback'); 
} 
public function product_serial_ajax() 
{ ?> 
<script type="text/javascript"> 
    jQuery(document).ready(function() { 
    alert('Hello World!'); 

    jQuery.ajax({ 
     type: 'GET', 
     url: "<?php echo admin_url('admin-ajax.php'); ?>", 
     //url: ajaxurl, 
     dataType : "JSON", 
     data : {action: "get_product_serial_callback"}, 
     //cache: false, 
     success: function(data){ 
     alert('Eureka')'; 
     } 
    }); 
    }); 
</script><?php 
} 
function csv_to_array($filename = '', $delimiter = ',') 
{ 
    //if(!file_exists($filename) || !is_readable($filename)) 
    //return FALSE; 
    $header = NULL; 
    $data = array(); 
    if (($handle = fopen($filename, 'r')) !== FALSE) { 
    while (($row = fgetcsv($handle, 1024, $delimiter)) !== FALSE) { 
     if (!$header) 
     $header = $row; 
     else 
     $data[] = array_combine($header, $row); 
    } 
    fclose($handle); 
    } 
    return $data; 
} 
function get_product_serial_callback() 
{ 
    $upload_dir = wp_upload_dir(); 
    $csvFile = $upload_dir['baseurl'] . '/Eragon-Serial.csv'; 
    $csv  = $this->csv_to_array($csvFile); //read csv 
    foreach ($csv as $serialnum) { 
    $serial_num_array[] = $serialnum['product_serial']; 
    } 
    $json_array = json_encode($serial_num_array); 
    echo $json_array; 
    die(); 
} 
function shortcode() 
{ 
    $this->product_serial_ajax(); //fetch product serial number 
} 

Однако, когда встречаются ajaxurl не определен, я изменил его ajaxurl, который формирует в ниже URL

http://example.com/wp-admin/admin-ajax.php?action=get_product_serial_callback 

This слишком не помогло.

Как я могу вызвать функцию get_product_serial_callback, чтобы получить значения JSON и установить эти значения в function(data)?

+0

Проверка ответа [здесь] (http://stackoverflow.com/questions/28022456/how-to-receive-data -from-database-via-jquery-wordpress-js/28022806 # answer-28022806) –

+0

проверить мой ответ – sarath

+0

@ShahRukh, если вы могли бы опубликовать код на основе вышеуказанного требования – Slimshadddyyy

ответ

0

проверить этот код

добавить load_product Funtion в sepearate JS и загрузить его.

function load_product(){ 
     jQuery.ajax({ 
      type: "GET", 

      url: ajaxurl, 
      dataType : "JSON", 
      data : {action: "get_product_serial_callback"}, 
      //cache: false, 
      success: function(data){ 
      alert('Eureka'); 
      } 
     }); 
    } 

отредактированный код

function __construct() 
     { 
      add_shortcode('user_registration_form', array(
      $this, 
      'shortcode' 
     )); 
      $this->hook(); 
     } 
     public function hook() 
     { 

      add_action('wp_ajax_get_product_serial', array($this,'get_product_serial_callback')); 
      add_action('wp_ajax_nopriv_get_product_serial',array($this,'get_product_serial_callback')); 
      add_action('init',array($this, 'my_script_enqueuer')); 
     } 




      function my_script_enqueuer() { 

wp_localize_script('more_script', 'myAjax', array('ajaxurl' => admin_url('admin-ajax.php'))); 
      wp_register_script('more_script', plugins_url('bootstrap/js/product-serial.js', __FILE__),array('jquery')); 

      wp_enqueue_script('more_script'); 

      } 
        public function product_serial_ajax() 
        { ?> 
        <script type="text/javascript"> 

         load_product(); 

        </script><?php 
        } 
        function csv_to_array($filename = '', $delimiter = ',') 
        { 
         //if(!file_exists($filename) || !is_readable($filename)) 
         //return FALSE; 
         $header = NULL; 
         $data = array(); 
         if (($handle = fopen($filename, 'r')) !== FALSE) { 
         while (($row = fgetcsv($handle, 1024, $delimiter)) !== FALSE) { 
          if (!$header) 
          $header = $row; 
          else 
          $data[] = array_combine($header, $row); 
         } 
         fclose($handle); 
         } 
         return $data; 
        } 
        function get_product_serial_callback() 
        { 
         $upload_dir = wp_upload_dir(); 
         $csvFile = $upload_dir['baseurl'] . '/Eragon-Serial.csv'; 
         $csv  = $this->csv_to_array($csvFile); //read csv 
         foreach ($csv as $serialnum) { 
         $serial_num_array[] = $serialnum['product_serial']; 
         } 
         $json_array = json_encode($serial_num_array); 
         echo $json_array; 
         die(); 
        } 
        function shortcode() 
        { 

        $this->product_serial_ajax(); //fetch product serial number 
        } 
+0

sarath: Он говорит 'ajaxurl не определен' – Slimshadddyyy

+0

Я только что обновил код .check. – sarath

+0

Sarath: Да, я проверил только ваш обновленный код. Также PLS см. 'Hook()' в моем обновленном вопросе – Slimshadddyyy

0

Plugin Class Файл:

function __construct() 
    { 


     add_shortcode('user_registration_form', array($this, 'shortcode')); 
     wp_register_script('product-serial', plugins_url('bootstrap/js/product-serial.js', __FILE__),array('jquery')); //custom jquery for product serial 
     wp_enqueue_script('product-serial'); //custom jquery for product serial 

     $this->hook(); 
    } 

    public function hook() 
    { 
     add_action('wp_ajax_get_product_serial', array($this,'get_product_serial')); 
     add_action('wp_ajax_nopriv_get_product_serial',array($this,'get_product_serial')); 
    } 

    public function product_serial_ajax(){ ?> 

     <script type="text/javascript">load_product();</script> 

     <?php 
    } 



    //convert csv data into array 
    function csv_to_array($filename='', $delimiter=',') 
    { 
      //if(!file_exists($filename) || !is_readable($filename)) 
      //return FALSE; 

      $header = NULL; 
      $data = array(); 
      if (($handle = fopen($filename, 'r')) !== FALSE) 
      { 
        while (($row = fgetcsv($handle, 1024, $delimiter)) !== FALSE) 
        { 
          if(!$header) 
            $header = $row; 
          else 
            $data[] = array_combine($header, $row); 
        } 
        fclose($handle); 
      } 
      return $data; 
    } 


    //get product serial number 
    function get_product_serial(){ 


     $upload_dir = wp_upload_dir(); 
     $csvFile = $upload_dir['baseurl'].'/Eragon-Serial.csv'; 
     $csv = $this->csv_to_array($csvFile); //read csv 

     foreach ($csv as $serialnum){ 
       $serial_num_array[] = $serialnum['product_serial']; 
     } 

     $json_array = json_encode($serial_num_array); 
     echo $json_array; 
     die(); 
    } 

    function shortcode() 
    { 
     $this->product_serial_ajax(); //fetch product serial number 
    } 

Seperate JS файл

function load_product(){ 
    var result=""; 
    jQuery.ajax({ 
     type: "GET", 
     url: ajaxurl, 
     async: false, 
     dataType : "JSON", 
     contentType: 'application/json; charset=utf-8', 
     data : {action: "get_product_serial"}, 
     //cache: false, 
     success: function(data){ 
      result = data; 
      return result; 
     }, 
     error: function() { 
     alert('Unexpected error occured. Please try again.'); 
    } 
    }); 

} 

PS: помещая следующее в header.php моей темы работал для меня

<script type="text/javascript"> 
    var ajaxurl = "<?php echo admin_url('admin-ajax.php'); ?>"; 
    </script> 
+0

Sarath: Как получить ответ json-данных на функцию 'product_serial_ajax'? Ajaxurl, который я вижу в ответ, это http: //example.com/wp-admin/admin-ajax.php? Action = get_product_serial' – Slimshadddyyy

+0

Это сработало? – sarath

+0

попробуйте оповещение (данные); после успеха линии: функция (данные) { – sarath

Смежные вопросы