0

I've been developing a website using WP and to display some database information in the front-end of the site i've created a plugin. Right now i want to include a filtering function for that same information using the plugin, but it does not work.

This is the file where i've created the filters, called show.php

<div class="container">
    <div class="row">
        <br />
        <div class="col-md-3">                              
            <div class="list-group">
                <h6>Modo de Confeção</h6>
                <div style="height: 180px; overflow-y: auto; overflow-x: hidden;">
                <?php

                $query =  "SELECT * FROM win_gab_modo_confecao ORDER BY designacaoModoConfecao";
                $result = $wpdb->get_results($query);
                foreach($result as $row)
                {
                ?>
                <div class="list-group-item checkbox" style="font-size: 14;">
                    <label><input type="checkbox" class="common_selector modoconf" value="<?php echo $row->idModoConfecao ?>"  > <?php echo $row->designacaoModoConfecao ?></label>
                </div>
                <?php
                }

                ?>
                </div>
            </div><br>

            <div class="list-group">
            <h6>Modo de Serviço</h6>
                <div style="overflow-y: auto; overflow-x: hidden;">
                <?php

                $query2 =  "SELECT * FROM win_gab_modo_servico ORDER BY designacaoModoServico";
                $result2 = $wpdb->get_results($query2);
                foreach($result2 as $row2)
                {
                ?>
                <div class="list-group-item checkbox" style="font-size: 14;">
                    <label><input type="checkbox" class="common_selector modoserv" value="<?php echo $row2->idModoServico ?>"  > <?php echo $row2->designacaoModoServico ?></label>
                </div>
                <?php
                }

                ?>
                </div>

            </div><br>
            
            <div class="list-group">
            <h6>Sub Categoria 1</h6>
                <div style="height: 180px; overflow-y: auto; overflow-x: hidden;">
                <?php

                $query3 =  "SELECT * FROM win_gab_sub_categorias WHERE subCategoria1 = '1' ORDER BY designacaoSubCategoria";
                $result3 = $wpdb->get_results($query3);
                foreach($result3 as $row3)
                {
                ?>
                <div class="list-group-item checkbox"  style="font-size: 14;">
                    <label><input type="checkbox" class="common_selector sub1" value="<?php echo $row3->idSubCategoria ?>"  > <?php echo $row3->designacaoSubCategoria ?></label>
                </div>
                <?php
                }
                ?>  
                </div>

            </div><br>

        
            <div class="list-group">
            <h6>Sub Categoria 2</h6>
                <div style="height: 180px; overflow-y: auto; overflow-x: hidden;">
                <?php

                $query3 =  "SELECT * FROM win_gab_sub_categorias WHERE subCategoria2 = '1' ORDER BY designacaoSubCategoria";
                $result3 = $wpdb->get_results($query3);
                foreach($result3 as $row3)
                {
                ?>
                <div class="list-group-item checkbox"  style="font-size: 14;">
                    <label><input type="checkbox" class="common_selector sub2" value="<?php echo $row3->idSubCategoria ?>"  > <?php echo $row3->designacaoSubCategoria ?></label>
                </div>
                <?php
                }
                ?>  
            </div>
        </div>

        <div class="col-md-9">
            <br />
            <div class="row filter_data">
            </div>
        </div>
    </div>
</div>

Right after this is where the problem is i believe. We begin the JS instructions that will call a file in the plugin's directory called fetch_data.php.

    $(document).ready(function(){

filter_data();

function filter_data()
{
    $('.filter_data').html('<div id="loading" style="" ></div>');
    var action = 'fetch_data';
    var minimum_price = $('#hidden_minimum_price').val();
    var maximum_price = $('#hidden_maximum_price').val();
    var modoconf = get_filter('modoconf');
    var modoserv = get_filter('modoserv');
    var sub1 = get_filter('sub1');
    var sub2 = get_filter('sub2');


    $.ajax({
        url:"fetch_data.php",
        method:"POST",
        data:{action:action, minimum_price:minimum_price, maximum_price:maximum_price, modoconf:modoconf, modoserv:modoserv, sub1:sub1, sub2:sub2},
        success:function(data){
            $('.filter_data').html(data);
        }
    });
}

function get_filter(class_name)
{
    var filter = [];
    $('.'+class_name+':checked').each(function(){
        filter.push($(this).val());
    });
    return filter;
}

$('.common_selector').click(function(){
    filter_data();
});

$('#price_range').slider({
    range:true,
    min:1000,
    max:65000,
    values:[1000, 65000],
    step:500,
    stop:function(event, ui)
    {
        $('#price_show').html(ui.values[0] + ' - ' + ui.values[1]);
        $('#hidden_minimum_price').val(ui.values[0]);
        $('#hidden_maximum_price').val(ui.values[1]);
        filter_data();
    }
}); 

});

Following this code, it calls the fetch_data.php like i mentioned above:

global $wpdb;

if(isset($_POST["action"]))
{
    $query = "
        SELECT * FROM win_gab_ficha_tecnica WHERE idFichaTecnica != '0' 
    ";
    if(isset($_POST["modoconf"]))
    {
        $conf_filter = implode("','", $_POST["modoconf"]);
        $query .= "
         AND modoConfecaoFichaTecnica IN('".$conf_filter."')
        ";
    }
   
    if(isset($_POST["modoserv"]))
    {
        $serv_filter = implode("','", $_POST["modoserv"]);
        $query .= "
         AND modoServicoFichaTecnica IN('".$serv_filter."')
        ";
    }
    
    if(isset($_POST["subcat1"]))
    {
        $subcat1_filter = implode("','", $_POST["subcat1"]);
        $query .= "
         AND subCategoria1 IN('".$subcat1_filter."')
        ";
    }
    
    if(isset($_POST["subcat2"]))
    {
        $subcat2_filter = implode("','", $_POST["subcat2"]);
        $query .= "
        AND subCategoria2 IN('".$subcat2_filter."')
        ";
    }
    
$result = $wpdb->get_results($query);
$total_row = $wpdb->rowCount();
    $output = '';
    if($total_row > 0)
    {
        foreach($result as $row)
        {
            

    $output .= '
                <div class="col-sm-4 col-lg-3 col-md-3">
                    <div style="border:1px solid #ccc; border-radius:5px; padding:16px; margin-bottom:16px; height:450px;">
                        <img src="image/'. $row['fotografiaFichaTecnica'] .'" alt="" class="img-responsive" >
                        <p align="center"><strong><a href="#">'. $row['nomeFichaTecnica'] .'</a></strong></p>
                        <p>Modo Confeção: '. $row['modoConfecaoFichaTecnica'].' MP<br />
                        Modo Serviço: '. $row['modoServicoFichaTecnica'] .' <br />
                        Sub-Categoria 1: '. $row['subCategoria1'] .' GB<br />
                        Sub-Categoria 2: '. $row['subCategoria2'] .' GB </p>
                    </div>
    
                </div>
                ';
            }
        }
        else
        {
            $output = '<h3>No Data Found</h3>';
        }
        echo $output;
    }

We've all the right calls in our plugin file for enqueuing scripts and all that stuff. When we load the wordpress page where this info is supposed to be displayed, the filtering simply does not work, and we get this console error:

jquery-1.10.2.min.js?ver=1.0:4 POST http://itamgabalgarve.pt/page-comidas/fetch_data.php 404 (Not Found)

Also, like i previosuly mentioned this is a plugin that displays the info in our custom-made theme. The page (in the theme) contains a function that calls the plugin and displays our info:

if (function_exists(get_comidas()))
1
  • 1
    Basically, you need to use the correct URL to the fetch_data.php, e.g. use a full absolute path (/example-path/fetch_data.php). But have you considered creating a custom REST API endpoint and then make your AJAX request to that endpoint? It's much much better than pointing to a static PHP file.
    – Sally CJ
    Oct 16, 2020 at 15:03

2 Answers 2

0

You need to add the ajax callback action on your plugin file or themes functions.php like as below:

add_action( 'wp_ajax_fetch_data', 'fetch_data_callback' );
add_action( 'wp_ajax_nopriv_fetch_data', 'fetch_data_callback' );

then you need to put all the featch_data.php code inside the callback function 'fetch_data_callback' like as below:

function fetch_data_callback(){
//your function code goes here
wp_die() // need to add end of the function
}

In Jquery

 var action = 'fetch_data';

 $.ajax({
        url:"<?php echo admin_url( 'admin-ajax.php' ) ?>",
        method:"POST",
        data:{action:action, minimum_price:minimum_price, maximum_price:maximum_price, modoconf:modoconf, modoserv:modoserv, sub1:sub1, sub2:sub2},
        success:function(data){
            $('.filter_data').html(data);
        }
    });
3
  • Thanks for such a quick reply! I've added the first piece of code in both files and it doesn't work still. The function fetch_data_callback is supposed to be under the add_action's right? This is not working still, i think i've done everything like you recommended... Oct 16, 2020 at 16:44
  • The order that you place the function and the add_action isn't vital - it can work either way, so that's not the issue. Some people place the add_action before, other's place it after. Oct 17, 2020 at 1:36
  • Thank you all for the solutions but i can't figure out what's the issue with my code, for some further knowledge and depth in it i've left a reply with more pieces of it, if you need so. Would appreciate if could help since i haven't got any replies to it! Oct 23, 2020 at 19:30
0

Thanks for your replies, but my code is still not working. At this point i really don't know what to do, i've been doing some tests and none seem to work. Reaching out with some additional code for context:

The ajax call in the show.php file is the following right now:

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

filter_data();

function filter_data()
{
    $('.filter_data').html('<div id="loading" style="" ></div>');
    var action = 'fetch_data';
    var modoconf = get_filter('modoconf');
    var modoserv = get_filter('modoserv');
    var sub1 = get_filter('sub1');
    var sub2 = get_filter('sub2');
    $.ajax({
   url:"<?php echo admin_url( 'admin-ajax.php' ) ?>",
   method:"POST",
   data:{action:action, modoconf:modoconf, modoserv:modoserv, sub1:sub1, sub2:sub2},
   success:function(data){
       $('.filter_data').html(data);
   }
   });
}

function get_filter(class_name)
{
    var filter = [];
    $('.'+class_name+':checked').each(function(){
        filter.push($(this).val());
    });
    return filter;
}

$('.common_selector').click(function(){
    filter_data();
});

});

Even though i've done everything like suggeste i still get the following error in both the plugin file or the functions file in my theme:

jquery-1.10.2.min.js?ver=1.0:4 POST http://itamgabalgarve.pt/wp-admin/admin-ajax.php 500 (Internal Server Error)

send @ jquery-1.10.2.min.js?ver=1.0:4
ajax @ jquery-1.10.2.min.js?ver=1.0:4
filter_data @ (index):323
(anonymous) @ (index):313
i @ jquery.min.js:2
fireWith @ jquery.min.js:2
ready @ jquery.min.js:2
K @ jquery.min.js:2

If you need any more piece of code let me know. Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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