Search code examples
javascriptphpjqueryhtmlmarkup

Text not marking up


I am writing a page which allows a tournament director (TD) to add players to an event. When the TD goes to search for a player I want the search results to appear on keyup below the search input (without needing to refresh the page). At this stage I have 2 php pages and 1 js page and have the live search happening, but the output is not getting marked up. I have written a piece of code to convert a PHP $_SESSION[''] array to a javascript array, but my brain is frying and I'm not sure where to go from here.

I effectively want the processed version of this code as output (presuming the SQL returns only 1 player named John Smith)

<tr></td> 123 </td><td> John Smith </td></tr>

My main php page has:

<table border='1px'>
<tr><th colspan='6'> <?php echo ($eName . " - " . $vn); ?></th></tr>
<tr><th>Player ID</th>
<th>Player Name</th>
<th>Place</th>
<th>Points</th>
<th>Cash</th>
<th>Ticket?</th></tr>

<tr><td colspan='3'>Search <input type='text' id='newsearch'</input>
</table>
<br>

<div id="newsearch-data"> </div>

<script>
 var players = [];   
</script>    

<?php

//Makes php array into js array
foreach ($_SESSION['players'] as $id){
echo "<script> players.push('" . $id . "') </script>";
}

?>
<script src="http://code.jquery.com/jquery-1.8.0.min.js"> </script>
<script src="global.js"> </script>

js page:

$('input#newsearch').on('keyup', function(){
    var newsearch = $('input#newsearch').val();
    if ($.trim(newsearch)!= "") {
        $.post('newsearch.php', {newsearch: newsearch}, function(data) {
            $('div#newsearch-data').text(data);
        });
    }
});

And 2nd php page

<?php
  session_start();
  unset($_SESSION['players']);
if (isset($_POST['newsearch']) === true && empty($_POST['newsearch'] === false)){
require 'dbconnect.php';

$term = $_POST['newsearch'];
$terms = "%" . $term . "%";

$_SESSION['players'] = array();

$query = ("SELECT * FROM players WHERE Username LIKE '$terms'");
$run_query = mysqli_query($dbcon, $query);

        while ($dbsearch = mysqli_fetch_assoc($run_query))
         {
         array_push ($_SESSION['players'],$dbsearch['PlayerID']);
           echo "<tr><td>" . $dbsearch['PlayerID'] . "</tr></td>";

         }}?

How can I output a new row on a html table rather than raw html code?


Solution

  • replace $('div#newsearch-data').text(data);

    with $('div#newsearch-data').html(data);

    $.text() escapes the input string and you should use it when you know the input is a string, and that you want to preset it "as is". If the input includes actual HTML that you want to inject into the DOM, $.html() is your friend :-)