1

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);
        });
    }
});
Ben
  • 1,013
  • 4
  • 16
  • 34

2 Answers2

0

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: HTML-encoding lost when attribute read from input field

Community
  • 1
  • 1
Steve Wellens
  • 20,506
  • 2
  • 28
  • 69
  • I tried this and replaced the `<` with `<` and `>` with `>` but I still get a parse error. I do not now how to incorporate the nifty function you linked to in my javascript above. Could you show me how? Here is the error I get with "hard coding" the brackets `<` and `>` `
    Parse error: syntax error, unexpected '&'`. Many Thanks.
    – Ben Dec 30 '12 at 02:09
0

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);
Ben
  • 1,013
  • 4
  • 16
  • 34