简体   繁体   中英

vanilla JS AJAX call function in PHP ? WP_query

Im having trouble trying to call my function in my Function.php this is the function

  1. enqueue script & localize
function my_enqueue() {

    wp_enqueue_script( 'wc_shop', get_template_directory_uri() . '/wc_shop.js', array('') );

    wp_localize_script( 'wc_shop', 'a_product_filter',
            array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
}
add_action( 'wp_enqueue_scripts', 'my_enqueue' );

  1. the Function thats in function.php that im trying to call that filters product
add_action('wp_ajax_a_product_filter', 'a_product_filter');

add_action('wp_ajax_nopriv_a_product_filter', 'a_product_filter');
function a_product_filter() {
  echo "called";
  $args = array( 
              'post_type'    => 'product', 
              'posts_per_page' => 5, 
              'product_tag'    => 'FEMALE' //just for testing without passing a variable
              );
        
        // Create the new query
        $loop = new WP_Query( $args );
        
        // Get products number
        $product_count = $loop->post_count;
        
        // If results
        if( $product_count > 0 ) :
        
          echo '<ul class="products">';
          
            // Start the loop
            while ( $loop->have_posts() ) : $loop->the_post(); //global $product;
            
              //global $post;
              wc_get_template_part( 'content', 'product' );

              echo '<a href="'.get_permalink($product_id).'">'.get_the_title($product_id).'</a>';
              
              if (has_post_thumbnail( $loop->post->ID )) 
                echo  get_the_post_thumbnail($loop->post->ID, 'shop_catalog'); 
              else 
                echo '<img src="'.$woocommerce .'/assets/images/placeholder.png" alt="" width="'.$woocommerce->get_image_size('shop_catalog_image_width').'px" height="'.$woocommerce->get_image_size('shop_catalog_image_height').'px" />';
          
            endwhile;
          
          echo '</ul><!--/.products-->';
        
        else :
        
          _e('No product matching your criteria.');
        
        endif; // endif $product_count > 0
}
  1. this is the call I'm calling from the front end i cant even get the a_product_filter to echo 'called'
function ajax_call_test(){
  // data to be sent to the POST request
  let _data = {
    action : 'a_product_filter',
    
  }

  fetch(a_product_filter.ajax_url , {
    method: "POST",
    body: JSON.stringify(_data),
    headers: {"Content-type": "application/json; charset=UTF-8"}
  })
  .then(response => response.json()) 
  .then(json => console.log(json));
  
}

I keep getting 400 Bad Request can someone help me and tell me what is wrong with this

Just like what I have stated in the comments, the backend requires you to send a request in normal POST fashion, not in JSON.

So use application/x-www-form-urlencoded as your header and send query string in the body, not JSON.

let _data = { action : 'a_product_filter', product_something: 'value that i want to send to the server'};
fetch(a_product_filter.ajax_url, {
    method: 'POST',
    body: (new URLSearchParams(_data)).toString(),
    headers: { 'Content-type': 'application/x-www-form-urlencoded' }
})
.then(response => response.text())
.then(product_html => document.getElementById('container').insertAdjacentHTML(product_html));
// put the markup created by server and put it inside somewhere in the frontend

Then on the backend, prepare for that request. Here's an untested code that you can use in the server. So that when the front end requests it, your server (the PHP code that will handle the request will give out the markup with the product you want to respond).

Just follow this idea. Create the markup and respond ( echo and exit ).

add_action('wp_ajax_a_product_filter', 'a_product_filter');
add_action('wp_ajax_nopriv_a_product_filter', 'a_product_filter');
function a_product_filter() {
    // $variable = $_POST['product_something'];
    $html_markup = _e('No product matching your criteria.');
    $args = array( 
        'post_type' => 'product', 
        'posts_per_page' => 5, 
        'product_tag' => 'FEMALE' //just for testing without passing a variable
    );
    $loop = new WP_Query($args);
    if ($loop->found_posts > 0) {
        // get template in string
        ob_start();
        wc_get_template_part('content', 'product');
        $template = ob_get_contents();
        ob_end_clean();
        $html_markup = '<ul class="products">';
        foreach ($loop->get_posts() as $post) {
            $html_markup .= '<li>'; // initialize list item    
            $html_markup .= $template; // add the template
            $html_markup .= '<a href="' . get_permalink($post->ID) . '">' . get_title($post->ID). '</a>'; // link and title
            $html_markup .= has_post_thumbnail( $loop->post->ID) ? get_the_post_thumbnail($post->ID, 'shop_catalog'); : '<img src="placeholder.jpg" />' ; // image of product
            $html_markup .= '</li>'; // end list item
        }
        $html_markup .= '</ul>';
    }

    echo $html_markup;
    exit;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM