невозможно $ _GET получить данные в PDO, используя AJAX для фильтрации продукта - PullRequest
0 голосов
/ 06 января 2020

Невозможно отфильтровать продукт, используя PDO amd AJAX,

Ниже код загружает форму данных sql, используя PDO и AJAX, но когда я пытаюсь отфильтровать на основе Brand это не работает пробовал метод отладки var_dump, но ничего не помогает.

Может кто-нибудь помочь мне решить, как мне отфильтровать продукт, в коде чего-то не хватает?

HTML

<div class="md-radio my-1">
     <input type="radio" class="filter_all cate" name="cate" id="<?php echo str_replace(' ', '', $row['sca']); ?>" value="<?php echo $row['sca'] ?>">
     <label for="<?php echo str_replace(' ', '', $row['sca']); ?>">
            <?php echo $row['sca']; ?>
     </label>
</div>

СКРИПТ

$(document).ready(function () {
            var flag = 0;
            var fetching = false;
            var done = false;

            function filter_data() {
                // prevent concurrent requests
                if (fetching === true) {
                    return;
                }
                fetching = true;
                var data = {
                    action: 'fetch_data',
                    cate: get_filter('cate'),
                    brand: get_filter('brand'),
                    model: get_filter('model'),
                    sort: get_filter('sort'),
                    date: get_filter('date'),
                    offset: flag,
                    limit: 4
                };
                console.log($.param(data));
                $.ajax({
                    url: "fetch.php?" + $.param(data),
                    type: 'POST'
                })
                        .done(function (data) {
                            console.log('data received');

                            $('.filter_data').append(data); // append

                            // we reached the end, no more data
                            if (data === '<h3>No Data Found</h3>') {
                                done = true;
                            }

                            flag += 4;
                            fetching = false; // allow further requests again
                        })
                        .fail(function (error) {
                            console.log('An error occurred while fetching', error)
                            // TODO: some error handling
                        });
            }

            function get_filter(class_name) {
                var filter = [];
                $('.' + class_name + ':checked').each(function () {
                    filter.push($(this).val());
                });
                return filter;
            }
            $('.filter_all').click(function () {
                filter_data();
            });
            filter_data(); // commented out for debugging purpose
            var $window = $(window);
            var $document = $(document);
            $window.scroll(function () {

                if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight - 300 && fetching === false && done === false) {
                    console.log('infinite scroll');
                    filter_data();
                }
            });
        });

PHP

<?php

include("$_SERVER[DOCUMENT_ROOT]/include/config.php");
include("$_SERVER[DOCUMENT_ROOT]/include/function.php");

$query = "SELECT * FROM allpostdata WHERE sts = '1' AND mca='Vehicle'";

if (!empty($_GET['cate'])) {
    $query .= " AND sca IN (" . str_repeat("?,", count($_GET['cate']) - 1) . "?)";
} else {
    $_GET['cate'] = []; // in case it is not set 
}

if (!empty($_GET['brand'])) {
    $query .= " AND product_brand IN (" . str_repeat("?,", count($_GET['brand']) - 1) . "?)";
} else {
    $_GET['brand'] = []; // in case it is not set 
}

if (!empty($_GET['model'])) {
    $query .= " AND mdl IN (" . str_repeat("?,", count($_GET['model']) - 1) . "?)";
} else {
    $_GET['model'] = []; // in case it is not set 
}

if (empty($_GET['sort']) || $_GET['sort'][0] == "date") {
    $query .= " ORDER BY pdt DESC";
} elseif ($_GET["sort"][0] == "ASC" || $_GET["sort"][0] == "DESC") {
    $query .= " ORDER BY prs " . $_GET['sort'][0];
}

if (isset($_GET['limit'])) {

    if (!empty($_GET['offset'])) {
        $query .= " LIMIT " . $_GET['limit'] . " OFFSET " . $_GET['offset'];
    } else {
        $query .= " LIMIT " . $_GET['limit'];
    }
}
$stmt = $conn->prepare($query);
$params = array_merge($_GET['cate'], $_GET['brand'], $_GET['model']);
$stmt->execute($params);
$result = $stmt->fetchAll();
$total_row = $stmt->rowCount();
$output = '';
if ($total_row > 0) {
    foreach ($result as $row) {
        $parameter = $row['pid'];
        $hashed = md5($salt . $parameter);
        $output .= '<a href="/single_view.php?p=' . $row['id'] . '" class="w-xl-20 w-lg-20 col-md-3 col-6 p-1 p-lg-2">
                            <div class="card border-0 small">
                                <img class="card-img-top rounded-0" src="/upload/thumb/' . $row["im1"] . '" alt="Card image cap">
                                <div class="card-body pb-0 pt-2 px-0">
                                    <h6 class="card-title text-dark text-truncate">' . ucfirst(strtolower($row['tit'])) . '</h6>
                                    <h6 class="card-subtitle mb-1 text-muted text-truncate small">' . $row['product_brand'] . '&nbsp;/&nbsp;' . $row['mdl'] . '</h6>
                                    <p class="card-text"><strong class="card-text text-dark text-truncate">&#x20B9;&nbsp;' . $row['prs'] . '</strong></p>' . timeAgo($row['pdt']) . '
                                </div>
                            </div>
                        </a>';
    }
} else {
    $output = '<h3>No Data Found</h3>';
}
echo $output;
?>

1 Ответ

0 голосов
/ 06 января 2020

Вы отправляете данные с помощью параметров запроса GET, несмотря на определение вызова ajax как сообщения. Это риск для безопасности. Попробуйте изменить свой AJAX вызов на что-то вроде этого и замените свой $_GET материал на $_POST.

            $.ajax({
                url: '/your-form-processing-page-url-here',
                type: 'POST',
                data: data,
                mimeType: 'multipart/form-data',
                success: function(data, status, jqXHR){
                    alert('Hooray! All is well.');
                    console.log(data);
                    console.log(status);
                    console.log(jqXHR);

                },
                error: function(jqXHR,status,error){
                    // Hopefully we should never reach here
                    console.log(jqXHR);
                    console.log(status);
                    console.log(error);
                }
            });
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...