0
add_action( 'wp_footer', function () { ?>
  <script type='text/javascript' id='ajax'>
    const ajaxUrl = "<?php echo admin_url('admin-ajax.php'); ?>";
    async function httpRequest(url = '', data = {}, method = 'POST') {
      const response = await fetch(url, { method: method, 
        credentials: 'same-origin',
        headers: { 
          'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
          'Cache-Control': 'no-cache',
        },
        body: new URLSearchParams(data)
      });
      return response.text();
    }

    document.querySelector('#roll-title-btn').addEventListener('click', async function() {
      const searchTerm = document.getElementById('roll-title');
      if (searchTerm.value.trim().length) {
        const result = await httpRequest(ajaxUrl,  { action: 'filter_ajax', 'roll-title': searchTerm.value });
        console.log(result);
      }
    })
  </script>
<?php } );

add_action( 'wp_ajax_nopriv_filter_ajax', 'filter_ajax' );
add_action( 'wp_ajax_filter_ajax', 'filter_ajax' );
function filter_ajax() {
  echo "TESTING";
  wp_die();
}

Whenever I am trying to send an HTTP request it is throwing 400 bad requests and prints 0 as result. Trying to implement a filter plugin but the above code snippets aren't working at all. I have tried multiple solutions from StackOverflow but none worked.

1 Answer 1

0

Here I am sharing my working code which I was developed by today so you can check here.

//First I enqueue script using action in function.php file
wp_enqueue_script( 'custom-js', get_stylesheet_directory_uri().'/assets/js/custom.js', array(), '1.0.0', 'true' );
//Then I localize custom js for admin ajax
wp_localize_script( 'custom-js', 'my_ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
//I choose action and javascript object "my_ajax_object"

//Now I create custom.js as per mentioned above path
$(function(){   
    $('#capture').click(function(){
    //capture is button id.
    //here is the ajax call
    var value = '123';
    jQuery.ajax({
                    type: "post",
                    dataType: "HTML",
                    url: my_ajax_object.ajax_url,
                    data : {action: "my_ajax_object","value":value},
                    success: function(msg){
                        console.log(msg);
                    }
                });

    });
});
//Now I wrote ajax function
add_action( 'wp_ajax_nopriv_my_ajax_object', 'my_ajax_object' );
add_action( 'wp_ajax_my_ajax_object', 'my_ajax_object' );

function my_ajax_object()
{
    $value = $_POST['value'];
    $response = '<p>value is '.$value.'<p>';
    return $response;

    wp_die();
}

Not the answer you're looking for? Browse other questions tagged or ask your own question.