How to escape HTML elements when fetching an array in PHP using Javascript?

I think the problem is in the "aif.php" file"

I am trying to fetch and display an array using PHP but the HTML element <br> is showing up in my result from the following scrip. I know I have to escape the HTML tags but I'm just not sure how! Also, any other advice on this code would be greatly appreciated (i.e. is there any redundancy or areas to improve? Thanks.

HTML
<DOCTYPE! html>
<html>
    <head>
        <title>The Auditors' Report: Data Entry</title>
        <link rel="stylesheet" type="text/css" href="style.css">
    </head>
    <body>
        <header><h1>Work Station<h1></header>
        <div = id="leftnav">
        <h2>Select Action</h2>
        Name: <input type="text" id="name">
        <input type="submit" id="grab" Value="Grab">
        </div>
        <div id="content"></div>
        <script src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
        <script src="aif.js"></script>
        </body>
</html>
PHP - config (filename: "config.php")
<?php
$dbhost = "localhost";
$dbname = "x";
$dbuser = "y";
$dbpass = "z";
$dsn = "mysql:host=$dbhost;dbname=$dbname";
$dbh = NULL
?>
PHP - query / resulting content (filename: "aif.php")
<?php
require "config.php";
$dbh = new PDO($dsn, $dbuser, $dbpass);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$sql = "SELECT * FROM table1 LIMIT 0,10";
$sth = $dbh->prepare($sql);
$sth->execute();
while ($row = $sth->fetch(PDO::FETCH_ASSOC)) {
    echo $row['field1'],"<br>";
    echo $row['field2'],"<br>";
    echo $row['field3'],"<br>";
}
?>
Javascript
$('input#grab').on('click', function() {
    var name = $('input#name').val();
    if ($.trim(name) !='') {
        $.post('aif.php', {name: name}, function(data) {
            $('div#content').text(data);
        });
    }
});

Answers


If you want to html encode a line like this:

this is <br /> a test

into a line like this:

this is &lt;br /&gt; a test

Use the nifty little function described here: JavaScript/jQuery HTML Encoding


I made a simple error in the Javascript. I wanted to pass back HTML and not TEXT.

With the following change, the PHP is rendered properly:

$('div#content').text(data);

to

$('div#content').html(data);

Need Your Help

The “right” way to route map a REST API

node.js routing

Im working on a small node/angular application

GWT Celltable only displaying 15 rows

java gwt

I'm having an issue where our cell table is only displaying 15 rows. I have something like the following: