2

I'm developing a searcher and I made a function that gets the data from a db, saves each ad in a variable and saves pagination (from another function) in another variable, so they can be returned in an array to be printed in the html later.

It works like this: you hit a buy or rent button and you go to the search page (/search?do?=buy/rent) then you have to select the property type, optionally a city/zone and hit search. Ajax sends the data via post (to search.php, the same file), hides the first container and shows the second container that has the list of properties with a pagination at the end of the page.

These are the main variables and a script to hide/show containers:

$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;';
}

This is the function:

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);
}

This is the main code:

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';
}

This is the AJAX script that sends the checkbox value via post (it's not working correctly, I don't get an undefined error in $prop_type (I don't know why???) but I get it in $table2, that it's inside the 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();
        }
    });

});

It works perfectly if I manually set $prop_type = 'res';. Any ideas?

Another problem is that the pagination buttons link does not work, it just triggers the ajax script (they need to send the data, otherwise the script will restart when changing pages).

I really would appreciate any optimization to the scripts. Thanks.

3
  • Looks like your syntax is off from the jQuery site Commented Nov 2, 2015 at 2:27
  • Does that mean I can't send prop_type to search.php and execute again the whole php script without reloading? sorry i've never used ajax, i'm totally lost. Commented Nov 2, 2015 at 2:37
  • No, it doesn't mean that. I didn't look at an answer for you, but from the syntax, the success call should not be part of the data object. Commented Nov 2, 2015 at 2:38

2 Answers 2

1

You're mixing your javascript and php here.

In PHP you declare a variable with $varname, in Javascript, $ represents the jQuery operator. As such your code that says $prop_type is totally invalid since this is javascript code. You're telling jQuery to execute some functionality called prop_type which doesn't exist, and as such you're getting an error that this is undefined.

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

And change the line which reads prop_type: $prop_type, to prop_type: prop_type,

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, you're right. Now I'm getting undefined variable for $test and $pagination. I think the script is wrong, the success is inside data anyways I don't need that callback, just execute the hide/show(). Where can I do that?
0

If you want to import the <div class="results"></div> container with ajax:

you should use this tested and working code:

$(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;
    });
});

9 Comments

It's still not working, maybe is a url problem. I have .htaccess rules to redirect to index.php, i'm using dynamic links (in this case "/search" but i've already tried it). Any idea? I'm getting undefined index: echo $_POST['prop_type'];
The code above is tested and it's working, so firstly check the url and change it to url: "http://website.com/search",, secondly if you are redirecting to the home page you will not see the changes, so stop this rule from the htaccess, and finally can you please copy the whole error. Also you can console.log(data) in the .done(function(data){console.log(data)}) to see whats returning the php search file.
Ok the url is /search. I did alert(data); and I can see the whole html code, i can see echo 'prop type: ' . $_POST['prop_type']; it's working but just in the alert, in the page i still see undefined index... What's wrong?
is undefined index a javascript or a php error? If it is a Javascript error please copy the whole error here, if it is a php error then it's not from the script, it is from something else in your php code.
It's a php error: Notice: Undefined index: prop_type. I think the problem is that data is not printed in the html, doesn't jquery do that automatically?
|

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.