2

Plugin Class File:

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
}

However, when encountered ajaxurl is not defined, I changed it ajaxurl which forms in below URL

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

This too did not helped.

How can I call get_product_serial_callback function in order to fetch the JSON values and set those values in function(data) ?

3
  • Check answer here Commented Jun 18, 2015 at 12:04
  • @ShahRukh if you could post the code based on above requirement Commented Jun 18, 2015 at 12:36
  • try to use method "POST" instead of "GET" method.... Commented Jun 18, 2015 at 13:31

2 Answers 2

0

check this code

add this load_product funtion in sepearate js and load it.

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

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

edited code

    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
                    }
Sign up to request clarification or add additional context in comments.

7 Comments

sarath: It says ajaxurl is not defined
Sarath: Yes I have checked with your updated code only. Also pls see hook() in my updated question
How do I check if its being called ? Also I have created a new .js for load product and included inc _construct() which alerts. Moreover it delas with user registration on frontend
use view source and search js . cut all the code in the hook() and add after end of the class.
.JS is being called and can see in source. Placed hook() code at the end of class and still it says ajaxurl is not defined. What if we change URL to <?php echo admin_url('admin-ajax.php'); ?>. I do not understand why it does not call the ajax function ?
|
0

Plugin Class File:

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 file

    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.');
    }
    });

}

P.S: putting the following in the header.php of my theme worked for me

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

2 Comments

Sarath: How do I get json data response to function product_serial_ajax ? The ajaxurl I see in response is http://example.com/wp-admin/admin-ajax.php?action=get_product_serial
try alert(data); after the line success: function(data){

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.