mark
mark

Reputation: 165

Using ajax to fetch products from wordpress database

I am using WordPress to build a custom products page (page1.php).

I'm using Ajax on the custom products page(page1.php), to call an other page that contains the code below (page2.php), to fetch products from the wordpress database using the code below.

<?php  
    $args = array(
        'post_type'      => 'product',
        'posts_per_page' => 10,
        'product_cat'    => 'hoodies'
    );

    $loop = new WP_Query( $args );

    while ( $loop->have_posts() ) : $loop->the_post();
        global $product;
        echo '<br /><a>' . woocommerce_get_product_thumbnail().' '.get_the_title().'</a>';
    endwhile;

    wp_reset_query();
?>

The code above actually works fine when I dont call it through AJAX (i.e. load it directly from www.localhost/wordpress/page2.php), but when I call it through ajax on page1.php, I get the following error;

Fatal error: Uncaught Error: Class 'WP_Query' not found in C:\xampp\htdocs\wordpress-fully-custom\wp-content\themes\storefront\page2.php:9 Stack trace: #0 {main} thrown in C:\xampp\htdocs\wordpress-fully-custom\wp-content\themes\storefront\test-page2.php on line 9

how do I fix this please?

Thanks

Upvotes: 0

Views: 6863

Answers (3)

Sajjad Hossain Sagor
Sajjad Hossain Sagor

Reputation: 518

There Are Tons of tutorials available there about wordpress ajax. You better look at these tuts....

Wordpress Official Ajax Tutorial

Sitepoint Ajax Tutorial With Some Good Examples

Code Tuts Tutorial For Frontend Ajax

Smashing Magazine Ajax Tutorial

And Now lets give you a quick ajax example here :

jQuery(document).ready(function(){
   jQuery(".ajax_button_to_click").click(function(event){
    // event.preventDefault(); enable this if you want to stop click 
   behavior
    var ajax_form_input_value = jQuery('#ajax_input_value').val();
    var ajax_text = jQuery('#ajax_text_value').text();
    jQuery.ajax({
       method: "POST", // http request method
       url: ajaxurl, // indicates wp-ajax.php file which will handle the request
       data: {'action':'ajax_function_name', //function name which will handle the ajax request inside your plugin or theme's functions.php file
              'ajax_text_data':ajax_text, //text data to send with the ajax request
              'ajax_form_value: ajax_form_input_value ' }, //form input data to send with the ajax request
       success:function(data) { //on ajax request success run all inside this method
        alert(data); 
    },
    error: function(errorThrown){ //if ajax fails then run this method
        console.log(errorThrown);
      }
    });
  });
});

And now the ajax request handling part on the backend.

First Add Js ajaxurl var :

add_action('wp_head', 'prefix_ajaxurl');

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

Second Add Ajax Action function

function ajax_function_name(){ // function name should be same defined in ajax request action var.
     $text = $_POST['ajax_text_data'];
     $input_data = $_POST['ajax_form_value'];
     echo $text;
     echo $input_data;
     die(); //you must write die(); to avoid echoing extra 0;
 } 
 add_action( 'wp_ajax_ajax_function_name', 'ajax_function_name' ); ?>

Upvotes: 0

Sunil Dora
Sunil Dora

Reputation: 1472

Here I have been tried for my theme and it's working nice!

Hope this will work for you.

Scipt code for AJAX CALL:

jQuery('#productDataSubmit').click(wc_load_all_products);
    function wc_load_all_orders() {
        jQuery("#wc-products").html("");

        jQuery.ajax({
            type: "POST",
            url: ajax_details.ajax_url,
            data: {action: 'get_wc_products'},
            success: function (data) {
                var products = jQuery.parseJSON(data);
                jQuery('#wc-products').html(products.product_html);
            }
        });
        return false;
    }

actions to call AJAX functions for returning products (add this into functions.php)

    add_action('wp_ajax_get_refund_data', 'get_wc_products');
    add_action('wp_ajax_nopriv_get_refund_data','get_wc_products');

function for getting products (add this into functions.php)

     /**
     * AJAX function for products.
     */
    function get_wc_products() {
    $html="";
    $varition_args = array(
            'post_type' => 'product',
            'posts_per_page' => 10,
            'product_cat'    => 'bags'
        );
        $variation_query = new WP_Query($varition_args);
    }


    if ($variation_query->have_posts()) {
            while ($variation_query->have_posts()) {
                 $variation_query->the_post();
                 global $product;
                 $html.= '<tr>';
                 $html.= '<td>'.get_the_ID().'</td>';
                 $html.= '<td>'.get_the_title().'</td>';
                 $html.= '<td>'.$product->get_price_html().'</td>';
                 $html.= '</tr>';
            }
    }

    //Returns records
    $data = [];
    $data['product_html'] = $html;
    }

Upvotes: 3

Nick
Nick

Reputation: 16606

When you're viewing the page directly, the WP_Query class much be getting imported somehow. Since this is not happening via AJAX, you may want to include it explicitly on that page. Could do something like:

include_once "path/to/wp-includes/class-wp-query.php";

Upvotes: 0

Related Questions