Dynamically created checkboxes using ajax from sql result set - html

I am looking to use ajax to dynamically create checkboxes each time you change your selection from a <select> tag, see the below screenshot for a section of the form that is relevant:
NOTE: The checkboxes under "Queues" should be dynamic.
At the moment, when you change the value for Team it grabs the team name (in this case "Test"), then using ajax (POST) it returns the Manager name for that team.
What I want it to do is look up another table that has a list of the "queues" associated with each team; I am going to add an "onchange" attribute in the tags for the "Manager Name" field.
Below is the code I'm currently using to accomplish the Team => Manager Name dynamic filling:
<script>
window.onload = function() {
getManager($("#team").val());
}
function getManager(team) {
$.ajax({
type: "POST",
url: "getManager.php",
data: {team:team}
}).done(function( manager ) {
$("#manager_name").val(manager);
});
}
</script>
And here is the getManager.php file that it uses:
<?php
require("../../database/db.php");
$mysqli = new db("nab_reporting");
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
$team=$mysqli->real_escape_string($_POST['team']);
$result = $mysqli->query("SELECT manager_name FROM team WHERE teamname = '".$team."'");
$row = $result->fetch_assoc();
echo $row['manager_name'];
mysqli_close($mysqli);
?>
Keeping in mind that the above works; I now need a way to use the onchange attribute of the Manager Name field that will use ajax (similar to above), passing another php page the value that is currently in the field (in this case Kane Charles) and will return a result set (array or JSON maybe?) containing a list of all queues in the database that match up with that Team name.
Below is the html code for each of the different bits:
TEAM
<select name="team" id="team" required="required" onchange="getManager(this.value)">
<?php
include(__DIR__ . "/../../database/db.php");
$db = new db("nab_reporting");
$result = $db->query("SELECT teamname FROM team");
while ($row = $result->fetch_assoc()) {
echo "
<option value=\"" . $row['teamname'] . "\">" . $row['teamname'] . "</option>
";
}
$db->close();
?>
</select>
MANAGER NAME
<input type="text" name="manager_name" id="manager_name" required="required" onchange="getQueues(this.value)">
QUEUES
<label>
Queues
</label>
<div id="queue_options">
<!-- queues dynamically created here -->
</div>
I need the contents of queue-options to be erased and reset to only the queues associated with the current team; I haven't done a great deal with ajax, hence why I'm posting on here.

This revision should match what you are asking about
PHP
// make an array to hold the queues
$data = Array();
// Fetch the rows of all the queues
$res = $mysqli->query("SELECT * FROM the_queue_table WHERE manager='" . $_GET["manager"] . "'");
// loop through all the rows and push the queues into the data array
while(($row = mysql_fetch_object($res)) !== false)
{
array_push($data, $row->queue);
}
// return the data array as a json object
echo json_encode($data);
JavaScript
// get the page and send the manager name to filter with
$.get("file.php?manager=" + managerName, function(page)
{
// parse the json into an object
var data = $.parseJSON(page);
// remove existing checkboxes
$("#queue_options").children().remove();
// add checkboxes to the div
for (var item in data){
$("#queue_options").append("<input type=\"checkbox\" value=\"" + item + "\" />" + item + "<br />");
}
});

Related

how to retrieve selected data from database based on selected checkbox in proper JSON format for highcharts

sorry for disturbing...I got json format to build column highcharts that will accept data from user multiple selected via checkbox and retrieve the data result from database based on what they check at checkbox and display by highcharts in form of column chart..
The problem is,I think my json format for column highcharts is not correct can anyone see my code and tell me what wrong with this....below this is the json output and the code..:- Thank u very much for your time..
Let say if I checked 2 checkbox from the checkboxes list (BAT123 & BIO22), this json will displayed like this:
[{"name":"Subject","data":["BAT123"]},{"name":"Result","data":[3.03]}]
[{"name":"Subject","data":["BAT123","BIO222"]},{"name":"Result","data":[3.03,1.05]}]
I know that json format is wrong, I tried to fixed it but still failed..I am a newbie..hope u can try to fix my code below.
Here is the json code:
<?php
if(isset($_GET['iddoc'])) //iddoc is the value from selected checkbox
{
$category = array();
$category['name'] = 'Subject';
$series1 = array();
$series1['name'] = 'Result';
foreach ($_GET['iddoc'] as $iddoc)
{
$query="select * from compareresult where iddocument=$iddoc";
$sql_query = mysql_query($query) or die('Error 3 :'.mysql_error());
while($r = mysql_fetch_assoc($sql_query))
{
$category['data'][] = $r['subject'];
$series1['data'][] = $r['result'];
}
$result = array();
array_push($result,$category);
array_push($result,$series1);
$jsonTable = json_encode($result, JSON_NUMERIC_CHECK);
echo $jsonTable;
}
}
?>

Check if entry is available in database

I have generated a 10 digit number, added it to a database after purchase.
Now I want to make a php page to give users an input box, ask them to enter the 10 digit number, and click submit. After you click submit it should return if the pin is used or has not been used it. (Used if its not available - Not used if its in the table)
I got the following code:
<?php
require_once 'db.php';
function validated_pin($pin)
{
$pin = mysql_real_escape_string($pin); // SECURITY!
$result = mysql_query("SELECT pins FROM pins WHERE pin='$pin' LIMIT 1");
if (mysql_fetch_row($result)) {
return 'This pin has already been used';
} else {
return 'This pin is available for use';
}
}
echo '<html><center>
<form action="' . $_SERVER['SCRIPT_NAME'] . '" method="post">
<table style="border:0px solid black;">
<tr>
<td>PIN*:</td><td><input type="text" name="pin" value="" class="bginput"/></td>
</tr>
<tr>
<td></td><td><input type="submit" id ="submit" name="submit1" value="Check Pin>>" class="button"></td>
</tr>
</table>';
echo validated_pin($pin);
echo '</center></html>';
?>
And PHPmyAdmin looks like this:
http://gyazo.com/67c3df7171c83c677cb221c04d644ed7.png
It's located in _donation and in table name pins
I don't know whats going on tried looking everywhere
The current code will return this error
Warning: mysql_fetch_row() expects parameter 1 to be resource, boolean given in /home/website/public_html/directory/example.php on line 8
Your query is failing to fetch data, resulting in false returned.
Firstly - you should catch this false value and not assume $result has data.
Secondly - var_dump() the query you are running, run that in PhpMyAdmin
Your query is-
$result = mysql_query("SELECT pins FROM pins WHERE pin='$pin' LIMIT 1");
shouldn't it be
$result = mysql_query("SELECT pin FROM pins WHERE pin='$pin' LIMIT 1");
pin is the column name right? not pins
if (mysql_fetch_row($result)) {
if(mysql_num_rows($result)>0)
return 'This pin has already been used';
else
return 'This pin is available for use';
}
This seemed to have solved it:
$pin = $_POST["pin"];
function validated_pin($pin)
{
$pin = mysql_real_escape_string($pin); // SECURITY!
$result = mysql_query("SELECT pin FROM pins WHERE pin='$pin' LIMIT 1");
if(mysql_num_rows($result) == 0) {
return 'This pin has already been used';
} else {
return 'This pin is available for use';
}
}
Still facing the issue of it saying "Already been used" before I execute any code.

Adjusting SQL line to include a collection

I have a function call resource of the day which I have duplicated and changed to be called Editors Picks. The function looks in the DB and grabs a ramdom image based on value and todays date.
Here is the SQL Line:
sql_value(
"select resource value
from resource_data
where resource > 5 and
resource_type_field=$rotd_field and
value like '" . date("Y-m-d") . "%' limit 1;"
,0);
I would like to try and adapt this line to pull in a collection instead, this is the SQL line that pulls in a collection image:
sql_query("select collection.ref,
collection.home_page_publish,
collection.home_page_text,
collection.home_page_image,
resource.thumb_height,
resource.thumb_width
from collection
left outer join resource on collection.home_page_image=resource.ref
where collection.public=1 and
collection.home_page_publish=1"
.$filterClause.
" order by collection.ref desc");
Does anyone know how to adapt the top SQL line to pull in the collection information instead, eg can I change date function to so something else?
This is the 2 pages that power the Code:
home.php
<?php
function HookEditorsPickHomeReplaceslideshow ()
{
include_once dirname(__FILE__)."/../inc/rotd_functions.php";
global $baseurl, $view_title_field;
$rotd=get_editors_pick();
if ($rotd===false) {return false;} # No ROTD, return false to disable hook and display standard slide show.
# Get preview width
$sizes = get_image_sizes($rotd, true);
foreach ($sizes as $size)
{
if ($size["id"]=="pre")
{
$width = $size["width"];
break;
}
}
# Fetch title
$title = sql_value("select value from resource_data where resource='$rotd' and resource_type_field=$view_title_field","");
# Fetch caption
$caption=sql_value("select value from resource_data where resource='$rotd' and resource_type_field=18","");
# Show resource!
$pre=get_resource_path($rotd,false,"pre",false,"jpg");
?>
<div class="HomePicturePanel" style="width: <?php echo $width ?>px; background-color:#f1f1f1; height: 409px;">
<a onClick="return CentralSpaceLoad(this,true);" href="<?php echo $baseurl?>/pages/view.php?ref=<?php echo $rotd ?>"><img class="ImageBorder" style="margin-bottom: 0px; margin-top: 0px; border:#CCC; solid: 0px;" src="<?php echo $pre ?>" /></a>
<br />
<div class="ResourceOfTheDayHead">Our Resource of the day</div>
<div class="ResourceOfTheDayText"><?php echo i18n_get_translated(htmlspecialchars($title)) ?></div>
<div class="ResourceOfTheDayCaption"><?php echo $caption ?></div>
</div>
<?php
return true;
}
?>
And this is: rotd.functions.php
<?php
function get_editors_pick()
{
global $rotd_field;
# Search for today's resource of the day.
$rotd = sql_value("select resource value from resource_data where resource>5 and resource_type_field=$rotd_field and value like '" . date("Y-m-d") . "%' limit 1;",0);
if ($rotd!=0) {return $rotd;} # A resource was found?
# No resource of the day fields are set. Return to default slideshow functionality.
return false;
}
?>
I am not fluent with php, but this pseudo-code may be useful.
string whereClause = "WHERE ";
for each (item in collection)
{
whereClause = whereClause + " " + item;
}
string sqlQuery = "SELECT stuff, otherStuff FROM myTable " + whereClause + " ORDER BY thing2";
The SQL injection can come if the items in the where clause are not sanitized. There are many examples on the web of how to prevent this, but the best way is to use parameters instead of dynamic SQL like I am showing above.

How can I write and read bool values into/from cookies?

I want to save the state of checkboxes in an html form on submit to cookies, and then enable/disable other parts of my site based on those cookie values.
I've started out with code like this:
HTML:
<form method="POST">
<fieldset>
<legend>(Not really) Opt In or Out</legend>
<input type="checkbox" id="selectTwitter" name="selectTwitter" >I'm Twitterpated!</input><br />
. . .
Razor:
#{
var twitterSelected = false;
. . .
if (IsPost)
{
twitterSelected = Request["selectTwitter"].AsBool();
Response.Cookies["TwitterSelected"].Value = twitterSelected.ToString(); // Doesn't seem to accept saving boolean vals - saved as "false" or "true"?
Response.Cookies["TwitterSelected"].Expires = DateTime.Now.AddYears(1);
. . .
...but am stuck on how to check or uncheck the checkboxes based on possibly existing cookie vals:
if (Request.Cookies["selectTwitter"] != null)
{
// what now?
}
Cookies are strings. You'll need to convert the cookie value to the type you want. The boolean values are being saved as true or false because that's the string representation of a boolean.
var selectTwitterCookie = Request.Cookies["selectTwitter"];
bool selectTwitter = false;
if(selectTwitterCookie != null)
{
bool.TryParse(selectTwitterCookie, out selectTwitter);
}
Alternatively, you could use Convert.ToBoolean(selectTwitterCookie).

html listbox to show additonal txt in extra field outside of listbox

I have the following db-retrieve which results in the Listbox I like to have.
But I need $desc2 to be shown under the listbox in a separate field and it must change its content when the user clicks on an other item in the list:
Here is the retrieve which works:
echo "<form action=\"admin.php\" method=\"post\">";
echo "Industry:<SELECT name=\"industry\" size=\"10\">";
$result=sql_query("SELECT cat, title, desc, parentid
FROM industries
WHERE language='english'");
while(list($cid2, $ctitle2, $desc2, $parentid2) = sql_fetch_row($result)) {
if ($cid2==$userindustry) {
$sel = "selected";
} else {
$sel = "";
}
if ($parentid2!=0) $ctitle2=getparentindustry($parentid2,$ctitle2);
echo "<option value=\"$cid2\" $sel>$ctitle2</option>";
}
echo "</SELECT>
<br>$desc2<br> # place to show description of list item
<input type=\"hidden\" name=\"op\" value=\"save\">
<input type=\"submit\" value=\"Go\"></form><br>";
As I'm now searchin for some time, but didn't found something, hopefully someone here could help me.
The code for the side is in php.
Thanks in advance.
You would have to store $desc2 to a temporary variable in the loop, and use the temporary variable after the select to show the temporary variable.
I would however, point out that in general, this is probably the wrong way of going about this code, and that your problem is deeper in your implementation :)