Matt Altepeter
Matt Altepeter

Reputation: 956

PHP JSON Response Includes HTML Layout

I'm struggling with an issue here: I'm trying to create a jQuery/AJAX/PHP live search bar. I am calling search.php fine, but whenever I output the response in the console, I get the contents of my master.php file (which is just site-wide layout) along with the JSON-encoded results. I can't figure out what is causing this to happen.

Here is my jQuery:

$(function() {
$("#search-text").keyup(function() {
    var $res = $(".search-results");

    $.ajax({
        type: "POST",
        url: "search.php",
        data: { query: $(this).val() },
        cache: false,
        success: function(html) {
            $res.show();
            $res.append(html);
            console.log(html);
        },
        error: function(xhr, status, error) {
            console.log("XHR: " + xhr);
            console.log("Status: " + status);
            console.log("Error: " + error);
        }
    });

    return false;

});
});

And search.php:

$key = $_POST["query"];
$db = new Database();
$db->query("SELECT * FROM users WHERE firstname LIKE :key OR lastname LIKE :key OR firstname AND lastname LIKE :key");
$db->bind(":key", '%' . $key . '%');
$rows = $db->resultset();

echo json_encode($rows);

Thanks!

Upvotes: 0

Views: 306

Answers (2)

Herlon Aguiar
Herlon Aguiar

Reputation: 701

Write an exit() after the echo in search.php.
Like this:

$key = $_POST["query"];
$db = new Database();
$db->query("SELECT * FROM users WHERE firstname LIKE :key OR lastname LIKE :key OR firstname AND lastname LIKE :key");
$db->bind(":key", '%' . $key . '%');
$rows = $db->resultset();

echo json_encode($rows);

exit();

It should prevent showing the entire page.

Upvotes: 3

user3568303
user3568303

Reputation: 102

In search.php before sending $rows in json_encode() give one condition that will check $row is empty or not.like :
if(!empty($res))
    echo json_encode(array('status'=>'success','result'=>$rows));
else
    echo json_encode(array('status'=>'failed','result'=>[]));
In ajax check 
success: function(html)
{
    if(html.status=='success')
    {
            $res.show();
            $res.append(result.html);
            console.log(result.html);
     }
}
may be it will work..

Upvotes: 0

Related Questions