Ajax Function call is always returning 0 in front end(without plugin) [closed]

First things first

You have a few errors in your code.

  • The table for terms is called wp_terms instead of wp-terms
  • The query $qry is not correct, the inner query has an invalid WHERE-clause: SELECT term_id as term_id FROM wp_term_taxanomy = 'category' should be SELECT term_id as term_id FROM wp_term_taxanomy WHERE taxonomy = 'category'
  • Improvement: Use the $wpdb->prefix instead of the static wp_ (not all WordPress installations use wp_
  • You register your AJAX function in a template, instead of your functions.php

Cleaned up

You could use a Code like this:

Your Template File

<?php

    get_header();
    global $wpdb;

    $qry = "select * from {$wpdb->prefix}terms where term_id IN ( SELECT term_id as term_id FROM {$wpdb->prefix}term_taxanomy WHERE taxonomy = 'category' )";

    $data = $wpdb->get_results( $qry );

    foreach( $data as $term ) {
?>
        <div class="checkbox" id="checkpadding">
         <label>
            <input type="checkbox" class="catclass" value="<?php echo $term->term_id; ?>">
            <span id="checktext"><?php echo $term->name; ?></span>
          </label>
        </div>
<?php
    }

<script>
jQuery(document).ready(function() {

    jQuery('.catclass').change(function () {

        if (this.checked) {
            var catid = ((this.value));
            var ajaxurl="<?php echo admin_url("admin-ajax.php'); ?>';
            jQuery.ajax({
                url: ajaxurl,
                data: {
                    'action': 'getpost',
                    'catid': catid
                },
                success: function (data) {
                    alert(data);
                    if(data.type == "success") {
                        alert("success");
                    }
                    else {
                        alert("AJAX error")
                    }
                },
                error: function (errorThrown) {
                    console.log(errorThrown);
                }
            });


        }
    });
});
</script>
<?php

    get_footer();

?>

Your functions.php

You add the rest to your functions.php:

<?php

    add_action('wp_ajax_getpost','getpost');

    add_action('wp_ajax_nopriv_getpost', 'getpost');

    function getpost() {

        echo "hi";
        die();

    }

?>

You should be fine in this case.

Debugging

Consider firing your AJAX call without the variable from the select, to ensure it is registered properly.

Afterwards, create an $array for your response, which you send back to the browser using wp_send_json(), so you can handle your values like data.type etc. in your script.

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)