victors
victors

Reputation: 1

WooCommerce AJAX-powered plugin - Error 500 ajax-admin.php

I am trying to build a simple plugin that inserts a simple AJAX powered button into a WooCommerce product page. Upon the press of the button, I would like to return the current product data to my Javascript code to be handled on the front end.

This is the callback function that gets executed upon click.

I get error: wp-admin/admin-ajax.php 500 (Internal Server Error)

function myfunction() {
     //gets executed;
    global $product;
    $name = $product->get_name();
    echo $name;
  wp_die();
 }

In debug.log it becomes apparent that the global $product variable is not available: PHP Fatal error: Uncaught Error: Call to a member function get_name() on null.

Notes:

Anyone has encountered this before and found a fix ?

Upvotes: 0

Views: 1173

Answers (2)

banstola
banstola

Reputation: 47

You need to register the ajax endpoint as below in your plugin

 add_action('wp_ajax_myFunction','myFunction');

then from your javascript you can do following

              var postData = {
                    'product-id': productId,
                    'action':'myFunction'
                };

                $.ajax({
                        'type':'POST',
                        'url': ajaxurl,
                        'dataType':'json',
                        'cache':false,
                        'data':postData,
                        success: function(response)
                        {

//more stuffs do ot 

                        },
                        error: function(xhr, textStatus, errorThrown)
                        {
                           // handle error 
                        }

                    }

Then at backend function myFunction

   $postItems = filter_input_array(INPUT_POST, ['product-id' => 'string']);

//$postItems will contain product-id which you can use to do more things 

// this gives $product object with public method like get_title

 $product = wc_get_product( $product_id );

 $name = $product->get_title();

 wp_send_json_success( array('name'=>$name), 200);
            exit();

Hope this helps!

Upvotes: 0

Sumit Parkash
Sumit Parkash

Reputation: 196

You need to pass the product id from ajax request. Then in your php callback function you can get product object from that id using woocommerce function.

/ /Get $product object from product ID $product = wc_get_product( $product_id );

Upvotes: 0

Related Questions