Skip to content Skip to sidebar Skip to footer

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 th

Solution 1:

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.


Solution 2:

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..

Post a Comment for "PHP JSON Response Includes HTML Layout"