在ajax请求php函数后没有收到变量

时间:2015-11-02 02:25:43

标签: php jquery ajax

我正在开发一个搜索器,我创建了一个从db获取数据的函数,将每个广告保存在一个变量中并将分页(从另一个函数)保存到另一个变量中,这样它们就可以在数组中返回稍后会在html中打印出来。

它是这样的:你点击买或租按钮然后你去搜索页面(/ search?do?= buy / rent)然后你必须选择房产类型,可选择一个城市/区域和点击搜索。 Ajax通过post(到search.php,同一个文件)发送数据,隐藏第一个容器并显示第二个容器,其中包含页面末尾带有分页的属性列表。

这些是隐藏/显示容器的主要变量和脚本:

$mode           = filter_input(INPUT_GET, 'do', FILTER_SANITIZE_STRING); // buy or rent
$prop_type      = filter_input(INPUT_POST, 'prop_type', FILTER_SANITIZE_STRING); // res or com AJAX
$city           = filter_input(INPUT_POST, 'city', FILTER_SANITIZE_NUMBER_INT); // AJAX
$zone           = filter_input(INPUT_POST, 'zone', FILTER_SANITIZE_NUMBER_INT); // AJAX
$page_number    = filter_input(INPUT_GET, 'page', FILTER_SANITIZE_NUMBER_INT);

if (isset($page_number) && $page_number >= 1) {
    $cont1 = 'display: none;';
    $cont2 = NULL;
    // need a way to get the prop_type (the checked checkbox before changing the page) without using $_GET.
} else {
    $cont1 = NULL;
    $cont2 = 'display: none;';
}

这是功能:

function get_prop_data($prop_type, $city, $zone, $page_number, $table, $targetpage) {

    if ($prop_type == 'res') {
        $table2 = 'res_prop';
    } else if ($prop_type == 'com') {
        $table2 = 'com_prop';
    }

    if ($city != 0) {
        $optional_cond = ' WHERE t2.city = ' . $city;
        $optional_cond2 = NULL;

        if ($zone != 0) {
            $optional_cond2 = ' AND t2.zone = ' . $zone;
        }
    } else $optional_cond = $optional_cond2 = NULL;

    $mysqli = new mysqli('127.0.0.1', 'db', '123456', 'name');

    // pagination
    if ($stmt = $mysqli->prepare('SELECT COUNT(id) FROM ' . $table)) {
        $stmt->execute();

        $stmt->bind_result($totalitems);

        $stmt->fetch();

        if (!isset($page)) {
            $page = (int)$page_number <= 0 ? 1 : (int)$page_number;
        }

        $limit = 4;

        if ($page > ceil($totalitems / $limit)) {
            $page = ceil($totalitems / $limit);
        }

        $start = ($page - 1) * $limit;

        $stmt->close();

        if ($stmt = $mysqli->prepare(' SELECT t1.id, t2.*
                                       FROM ' . $table . ' t1
                                       INNER JOIN ' . $table2 . ' t2 ON t2.id = t1.id
                                       ' . $optional_cond . $optional_cond2 . '
                                       LIMIT ?, ?')) {
            $stmt->bind_param('ii', $start, $limit);
            $stmt->execute();

            $stmt->bind_result($id, $id, $type, $status, $bhk, $baths, $area1, $area2, $age, $description, $price, $city, $zone, $img1, $img2, $img3, $img4);
            $test = "";
            while ($row = $stmt->fetch()) {
                if ($status === 0) {
                    $possesion = 'En construcción';
                } else if ($status === 1 || $status === 2) {
                    $possesion = 'Inmediata';
                } else $possesion = 'Desconocida';
                if ($prop_type == 'res') {
                    $is_res = '<p><span class="bath">Bed</span>: <span class="two">' . $bhk . ' BHK</span></p>
                            <p><span class="bath1">Baths</span>: <span class="two">' . $baths . '</span></p>';
                } else $is_res = NULL;
                $test .= '<div class="box-col">
                        <div class="col-sm-6 left-side ">
                            <a href="/single?id=' . $id . '"> <img class="img-responsive" src="' . $img1 . '" alt=""></a>
                        </div>
                        <div class="col-sm-6 middle-side">
                            <h4>Disponibilidad: ' . $possesion . '</h4>
                            ' . $is_res . '
                            <p><span class="bath2">Built-up Area</span>: <span class="two">' . $area1 . ' m²</span></p>
                            <p><span class="bath3">Plot Area</span>: <span class="two">' . $area2 . ' m²</span></p>
                            <p><span class="bath4">Age of property</span>: <span class="two">' . $age . ' Year(s)</span></p>
                            <p><span class="bath5">Price</span>: <span class="two">' . $price . ' €</span></p>
                            <div class="right-side">
                                <a href="/contact" class="hvr-sweep-to-right more">Contact Builder</a>
                            </div>
                        </div>
                        <div class="clearfix"> </div>
                    </div>
';
                $pagination = functions::getPaginationString($page, $totalitems, $limit, $adjacents = 1, $targetpage, $pagestring = "&page=");
            }
        } //else echo "Statement failed: " . $mysqli->error . "<br>";
    } //else echo "Statement failed: " . $mysqli->error . "<br>";

    return array($test, $pagination);
}

这是主要代码:

if (empty($_GET)) {
    echo 'under construction';
}
else if (isset($mode) && $mode == 'buy') {
    $table = 'to_sell';
    $targetpage = '/search?do=buy';;

    if (isset($prop_type)) {
        $data = get_prop_data($prop_type, $city, $zone, $page_number, $table, $targetpage);
        $test = $data[0];
        $pagination = $data[1];
    }
}
else if (isset($mode) && $mode == 'rent') {
    $table = 'to_rent';
    $targetpage = '/search?do=rent';;

    if (isset($prop_type)) {
        $data = get_prop_data($prop_type, $city, $zone, $page_number, $table, $targetpage);
        $test = $data[0];
        $pagination = $data[1];
    }
}
else {
    echo 'invalid url';
}

这是通过post发送复选框值的AJAX脚本(它没有正常工作,我在$prop_type中没有得到未定义的错误(我不知道为什么???)但我明白了在$table2中,它位于if ($prop_type == ''))内:

$('.search, .pagination').click(function() { // search button and change page

    if ($('#res_prop').is(':checked')) {
        $prop_type = $('#res_prop').val();
    }
    else if ($('#com_prop').is(':checked')) {
        $prop_type = $('#com_prop').val();
    }

    $.post('search.php', { // same file, maybe self
        prop_type: $prop_type,
        city: $('select[name=city]').val(), // optional
        zone: $('select[name=zone]').val(), // option value="0" by default
        success: function(){
            $('.cont-1').hide();
            $('.cont-2').show();
        }
    });

});

如果我手动设置$prop_type = 'res';,它的效果非常好。有什么想法吗?

另一个问题是分页按钮链接不起作用,它只是触发ajax脚本(它们需要发送数据,否则脚本将在更改页面时重新启动)。

我真的很感激脚本的任何优化。感谢。

2 个答案:

答案 0 :(得分:1)

你在这里混合你的javascript和php。

在PHP中,您使用$ varname声明一个变量,在Javascript中,$表示jQuery运算符。因此,你的$ prop_type代码完全无效,因为这是javascript代码。您告诉jQuery执行一些名为prop_type的功能,而这种功能并不存在,因此您会收到一个未定义的错误。

if ($('#res_prop').is(':checked')) {
    var prop_type = $('#res_prop').val();
}
else if ($('#com_prop').is(':checked')) {
    var prop_type = $('#com_prop').val();
}

并将标有prop_type: $prop_type,的行更改为prop_type: prop_type,

答案 1 :(得分:0)

如果要使用ajax导入<div class="results"></div>容器:

你应该使用这个经过测试和运行的代码:

$(document).ready(function(){
    $('.search, .pagination').click(function() { // search button and change page
        $prop_type = '';

        if ($('#res_prop').is(':checked')) {
            $prop_type = $('#res_prop').val();
        }
        else if ($('#com_prop').is(':checked')) {
            $prop_type = $('#com_prop').val();
        }

        $.ajax({
            method: "POST",
            url: "go.php",
            data: { 
                'prop_type': $prop_type, 
                'city': $('select[name="city"]').val(),
                'zone': $('select[name="zone"]').val() 
            }
        }).done(function(data) {
            var _html = $.parseHTML(data);
            $('.cont-1').hide();
            $('.cont-2').show();
            $(_html).each(function(i, el) {
                if (el.className == 'results') {
                    $('.results').html($(el).html());
                };
            });
        });

        return false;
    });
});