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?
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 :-)
You need .html() to render output as a HTML rather than .text(), because .text() will output the result as a raw data, then try this solution instead :
$('div#newsearch-data').html(data);
Live example - credited to #Peter Bailey for live example.
References
http://api.jquery.com/html/ - .html()
http://api.jquery.com/text/ - .text()
Related
I'm having an issue with a PHP page that generates an HTML document. On the page, there is a form that has a <select> box, and each <option> inside has a value with the URL parameters to use when changing the window location when the form is "submitted". The issue is that I noticed is that one of the parameters is a name, and when that name has a space in it, it breaks the window location because the space remains in the URL.
I've tried simply doing a str_replace() on the string before it generates the <option> tag, and when I view the <option> in Firefox' inspector, it DOES contain a %20 instead of a space, but when I look at the URL bar after clicking the <option>, it still retains the space instead of the %20. Can anyone tell me what's wrong with the following snippet?
print("<form name=sel1>");
print("<select size=10 style='width:200;font-family:courier,monospace;
font-weight:bold;color:black;' ");
print("onchange=\"location = this.options[this.selectedIndex].value;\">");
for($i = 0; $i < count($allGroups); $i++)
{
print("<option value='groups.php?action=");
if($advancedPermissions)
{
if($modGroups)
{
print("edit");
}
else
{
print("view");
}
}
else
{
print("edit");
}
print("&group_id=");
print(str_replace(" ", "%20", $allGroups[$i][0])."'>");
print($allGroups[$i][0]);
if($allGroups[$i][2] != 'Y')
{
print(" - inactive");
}
}
print("</select></form>");
The relevant lines are the line with location = and the line just after the group_id parameter is added, where the str_replace() is done.
I do the str_replace() on just the value, not the display text, so it will show normally to the user, but contain the %20 character for when it is passed to the window location, but regardless, it either ignores it, or something else is happening I am not aware of.
This code is a whole mess of bad practices. First, separation of code (PHP) and presentation (HTML) is essential for making sense of things. You should be doing logic in a separate code block at the very least, if not a separate file. Definitely not in the middle of an HTML element. Exiting PHP and using alternative syntax and short echo tags make this separation much clearer.
You should be building HTTP query strings using the http_build_query() function, which will handle escaping issues like the one you're having, and you should always escape HTML for output using htmlspecialchars().
print is not commonly used, but note that it's a language construct and not a function. Parentheses are not needed, and rarely used.
Inline CSS and JavaScript declarations are very 20th century and should be avoided wherever possible.
Here's how I would start to rework this code...
<?php
// assuming $allGroups is created in a loop
// the following code could be incorporated into that loop
$options = [];
foreach ($allGroups as $group) {
$action = ($advancedPermissions && !$modGroups) ? "view" : "edit";
$group_id = $group[0];
$url = "groups.php?" . http_build_query(compact("action", "group_id"));
$options[$url] = $group[0] . ($group[4] !== "Y" ? " - inactive" : "");
}
?>
<!doctype html>
<html>
<head>
<style>
#location_select {
width: 200px; font-family: monospace; font-weight: bold; color: black;
}
</style>
</head>
<body>
<form name=sel1>
<select id="location_select" size="10">
<?php foreach ($options as $value => $option): ?>
<option value="<?= htmlspecialchars($value) ?>">
<?= htmlspecialchars($option) ?>
</option>
<?php endforeach ?>
</select>
</form>
<script>
document
.getElementById("location_selector")
.addEventListener("change", function() {
window.location = this.options[this.selectedIndex].value;
});
</script>
</body>
</html>
But if you are looking for the quick fix:
for($i = 0; $i < count($allGroups); $i++)
{
$action = ($advancedPermissions && !$modGroups) ? "view" : "edit";
$group_id = $allGroups[$i][0];
$url = "groups.php?" . http_build_query(compact("action", "group_id"));
print("<option value='$url'>");
print($allGroups[$i][0]);
if($allGroups[$i][2] != 'Y')
{
print(" - inactive");
}
print("</option>");
}
I'm using the following php code to create a select option box:
$TypeLU = mysqli_query($mysqli, "SELECT * FROM LookupList");
while($Row = mysqli_fetch_array($TypeLU)) {
$TypeOptions = $TypeOptions."<option>$Row[1] $Row[2]</option>";
}
In HTML it gets displayed as a list with 2 columns. If I select and item from the list the value would be the concat of both $Row[1] and $Row[2] which is fine for display purposes, but I want to be able to 'extract' for example only $Row[1] as being the 'bound' value which I can then use as refrence.
So in pure Javascript I want to be able to get the value of just $Row[1] for example:
var x = document.getElementById("selectbox").value;
// So x must be only $Row[1] and not the concat of $Row[1] $Row[2]
Thanks
Use:
$TypeOptions = $TypeOptions."<option value='$Row[1]'>$Row[2]</option>";
You may also want to consider escaping the variables in case they contain any < or " or other special HTML characters. See htmlspecialchars.
Full example with escaping:
$TypeLU = mysqli_query($mysqli, "SELECT * FROM LookupList");
while($Row = mysqli_fetch_array($TypeLU))
{
$Row[1] = htmlspecialchars($Row[1]);
$Row[2] = htmlspecialchars($Row[2]);
$TypeOptions = $TypeOptions."<option value='$Row[1]'>$Row[2]</option>";
}
I'm working on a very basic web page to facilitate data entry. I have it working with PHP talking to SQL Server to both enter and display data. At the simplest level, they'll select a store from a dropdown and enter some data, then hit submit.
I'm trying to dynamically display the last 7 days worth of data when their store is chosen from the form select input. How do I get the Select value to drive the SQL query? I found how to use onchange to fire a javascript function, which I can alert the value. Do I really need to then use jquery or AJAX to link that back to the PHP select query or is there a simpler way to approach this?
I'm trying to learn this all from scratch and am quite admittedly out of my element. Here are some snippets of what I've got:
...
<script>
function OnSelectChange(obj)
{
alert(obj.options[obj.selectedIndex].value);
}
</script>
...
<td align="right">Store</td><td width="125"><select style="width:100%" name="store" onchange="OnSelectChange(this)">
...
<?php
$tsql = "select * from test where DateStamp >= getdate()-7";
$stmt = sqlsrv_query($conn, $tsql);
//generate table view of data
echo "<table>";
echo "<tr><td>Store ID</td><td>Date</td><td>Data</td></tr>";
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC))
{
$StoreID = $row['StoreID'];
$DateStamp = $row['DateStamp'];
$Donations = $row['Data'];
echo "<tr><td>".$StoreID."</td><td>".$DateStamp."</td><td>".$Data."</td></tr>";
}
echo "</table>";
?>
I've found a lot of helpful information to get me this far, but am stuck now.
Thank you in advance.
Got it! For anyone else looking, here are relevant snippets of code:
<style>
.hideable {
visibility: collapse;
}
</style>
...
<script language="JavaScript">
function OnSelectChange(cl)
{
var els = document.getElementsByClassName('hideable');
for(var i=0; i<els.length; ++i){
var s = els[i].style;
s.visibility = 'collapse';
};
var els = document.getElementsByClassName(cl);
for(var i=0; i<els.length; ++i){
var s = els[i].style;
s.visibility = 'visible';
};
}
</script>
...
<select style="width:100%" name="store" onchange="OnSelectChange(this.value)">
...
echo "<tr class='hideable ".$StoreID."'><td>".$StoreID."</td><td>".$DateStamp."</td><td>".$Data."</td></tr>";
Leveraging dual classes upon the table (tr) creation and the collapse CSS style property was key.
I have an edit function where their is a function that has hide/show if i click edit. My problem is how can i remain the value of row if im going to hide it?
for example i have this dialog
and decided to edit sample 1(first row)
and then i decided i realize that i dont want to edit sample 1 then close it (by clicking edit again) then i want to edit sample 5 but i got this error
here is my script
//show and hide update button checker
function update_contain(){
var row = jQuery(".beneficiaries_rows input[type='text']:visible").length;
if(row > 0){
jQuery('.ui-dialog-buttonpane button:contains("Update")').button().show();
}else{
jQuery('.ui-dialog-buttonpane button:contains("Update")').button().hide();
}
}
//beneficiaries edit
jQuery(".edit_beneficiaries").click(function(){
var row = jQuery(this).closest(".beneficiaries_rows");
var show = row.find(".hide");
var hide = row.find(".show");
if(jQuery(show).is(":visible")){
jQuery(show).css({"display":"none"});
jQuery(hide).css({"display":"inline-block"});
}else{
jQuery(hide).css({"display":"none"});
jQuery(show).css({"display":"inline-block"});
}
update_contain();
});
HTML
<table style="border: 2px solid black;margin:auto;">
<tr>
<th style="width:145px;"><center>Name<center></th>
<th><center>Action</center></th>
</tr>
<?php
while($row1 = mysql_fetch_array($result1)){
echo "<tr class='beneficiaries_rows' id='".$row1['id']."' data-id='".$row1['ben_id']."'>";
echo "<td><input class='hide' type='text' name='bename_update' value='".$row1['name']."'></div>";
echo "<div class='show'>".$row1['name']."</td>";
echo "<td>";
echo "<center><button class='del_beneficiaries'>X</button><button class='edit_beneficiaries'>Edit</button></center>";
echo "</td>";
echo "</tr>";
}
?>
</table>
P.S im not good in english thats why im posting a picture to elaborate
my question
You'll want to set the text inside your label with something like this
jQuery("[selector for your label]").html(jQuery("[selector for input]").val());
I suggest doing this on click, just before you hide the input.
edit; since you're not really following:
jQuery(".edit_beneficiaries").click(function(){
var row_display = jQuery(this).parents("tr").find(".show");
var row_edit = jQuery(this).parents("tr").find(".hide");
jQuery(row_display).html(jQuery(row_edit).val());
});
On my site when comment text contains my company name, then I want this name to be highlighted. This comments are retrieved from my mysql database. So how can I change the color (highlight anyway) of my company name if it exists in a comment? I can't use <span> because comments are dynamic. So please help me.
input
<?php
$paragraph=$row['textColumn'];//from database
//now it is
$paragraph='This is my companyName To be highlighted.This is companyName To be highlighted.This is my companyName To be highlighted.This is companyName To be highlighted.';
echo '<p>'.$paragraph.'</p>';
?>
expected output
Use the search and replace method str_replace:
$paragraph = $row['textColumn'];//from database
//now it is
$paragraph = str_replace('companyName', '<span class="highlightClass">companyName</span>', $paragraph);
echo '<p>'.$paragraph.'</p>';
You can use spans via a simply search and replace. You could do this in php:
$paragraph = str_replace('companyName', '<span class="red">companyName</span>', $paragraph;
Or in javascript (jquery):
$('div.comments').each(function() {
$(this).text($(this).text().replace('companyName', '<span class="red">companyName</span>'));
});
The above presumes comments are wrapped in <div class="comments"></div>. You would need to adjust to match your actual markup
This can be done wih JQuery
var html = $('p').html();
$('p').html(html.replace(/world/gi, '<strong>$&</strong>'));
<?php
$paragraph=$row['textColumn'];//from database
//now it is
$paragraph='company name';
echo '<h1>'.$paragraph.'</h1>';
?>
after it
change h1 class style