WP Ajax never returning any data / calling action

Question

I have a simple click function that gets the data of a radio button in a form and passes it to a function in my functions.php file. The problem is the Ajax never calls my action in my functions.php file. I always get “nothing found” as set in my ajax function.

Here is my code below, if anyone can spot the problem would be greatly appreciated.

JS:

$(".faq-category-select").on("click",function() {

var faqCategory = $(this).attr('value');
var str = '&faq_category=' + faqCategory + '&action=load_faqs_by_category';

$.ajax({
    type: "POST",
    dataType: "html",
    url: ajax_params.ajaxurl,
    data: str,
    success: function(data) {
        var $data = $(data);
        if($data.length){
            $("#faq-archive-content-wrap").append($data);
        } else{
            $("#faq-archive-content-wrap").append('<p>nothing found</p>');
        }
    },
    error : function(jqXHR, textStatus, errorThrown) {
        $loader.html(jqXHR + " :: " + textStatus + " :: " + errorThrown);
    }

});
return false;

});

HTML:

<form action="" id="faq-filter-form" method="post">

<h3>Heading 1</h3>

<input type="radio" name="faq-category-select" class="faq-category-select" value="value 1"><label>Value 1</label>
<input type="radio" name="faq-category-select" class="faq-category-select" value="Value 2"><label>Value 2</label>

<h3>Heading 2</h3>

<input type="radio" name="faq-category-select" class="faq-category-select" value="value 3"><label>Value 3</label>
<input type="radio" name="faq-category-select" class="faq-category-select" value="value 4"><label>value 4</label>

</form>

functions.php

 add_action ( 'wp_ajax_load_faqs_by_category', 'load_faqs_by_category' );
add_action ( 'wp_ajax_nopriv_load_faqs_by_category', 'load_faqs_by_category' );

function load_faqs_by_category() {

  $faq_category = (isset($_POST['faq_category'])) ? $_POST['faq_category'] : '';

  header("Content-Type: text/html");

    $output = '';
    $output .= 'you selected the'.$faq_category.'category';

  die($output);

}

wp_register_script( 'faq-ajax', get_template_directory_uri() . '/js/faq-ajax.js', '','',true );
wp_localize_script( 'faq-ajax', 'ajax_params', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
wp_enqueue_script( 'faq-ajax' );

--------------------------------------------------

>>> Share a link to this question, just copy and paste the code bellow on your web page <<<

<a href="https://www.wptricks.com/question/wp-ajax-never-returning-any-data-calling-action/">

WP Ajax never returning any data / calling action</a>
0
caffeinehigh 3 months 0 Answers 62 views 0

Leave an answer