Adaptive Drop Down Menu with PHP functions Populating from a MySQL server - javascript

I have three drop down menus that I have been trying to make dependent on one another so that once a selection has been made in the first drop down, the options for the second one will change. Then once a selection has been made in the second drop down menu, the third dropdown menu will change. My HTML looks like this:
<select class = "homepageSelectors , hpSelectorMenu" id = "classSelector" name="classSelector" >
<option selected="selected">Select</option>
<option value= "geometry">Geometry</option>
<option value= "english1">English 1</option>
<option value= "algebra2">Algebra 2</option>
</select>
<select class = "homepageSelectors , hpSelectorMenu" id = "levelSelector" name="levelSelector">
</select>
<select class = "homepageSelectors , hpSelectorMenu" id = "teacherSelector" name="teacherSelector">
</select>
The first drop down is hard coded because the options will not change. Although, what I need to do is when the first one is changed, run a PHP function to query an SQL database and get the options for the second dropdown menu. I have the following jquery code in another file that runs a function when the first dropdown is changed.
$("#classSelector").change( function () {
//In here is where I need to run a PHP function
});
I realize that I can call an external PHP file from in that jquery function, although my problem is that once I query my SQL server from that external PHP file, I have no way of returning the results from the query to my HTML file so that the second drop down menu can be populated.
I have been looking at other forums trying to find a solution, although I was unable to find any posts similar to my scenario. I am not too familiar with ajax, but if you think that it is the way to do it, please do explain. THANKS FOR ALL THE HELP!!!

You need to use jQuery Ajax
Make a request the .php file in order to get the data you want. A way simple example to get you an idea:
Your javascript function file:
$("#classSelector").change( function () {
//In here is where I need to run a PHP function
var value = $(this).val();
// load data if value is different than 'selected'
if(value != 'selected') {
$.ajax({
url: 'your_file.php',
data: {classID: $(this).val()},
dataType: 'html',
type: "GET",
success: function(data) {
// drop the output in #levelSelector select
$('select#levelSelector').html(data);
}
});
}
});
This can be translate to something like your_file.php?classID=Geometry for example:
Your php file:
<?php
// This is an example your php script should output what you need
// and how you need even if loading data from SQL Server / MySQL etc...
$classID = (isset($_GET['classID'])) ? $_GET['classID'] : null;
switch($classID)
{
case 'Geometry':
echo "<option value='level1'>Level 1</option>";
break;
default:
break;
}
// Output
<option value='level1'>Level 1</option>
The output will be inside the '#levelSelector' select and like this:
<select class = "homepageSelectors , hpSelectorMenu" id = "levelSelector" name="levelSelector">
<option value='level1'>Level 1</option>
</select>

So, I think what you're really asking for here is: how do I use JavaScript and PHP to live-query a database?
There are two parts to this. The JavaScript script and the PHP script. JavaScript will make an AJAX call to the PHP script, which will then query the database and return the results of that query to the JavaScript that made the initial request.
It seems you are already using jQuery, so that's great, since jQuery has a really useful feature for making network calls: $.ajax()
Taking the code you already have and expanding it:
$("#classSelector").change( function () {
var selectedClass = $(this).find(":selected").text();
$.ajax({
url: '/path/to/class/select/php/script.php',
data: {selectedValue: selectedClass}, // Send this data to the PHP script
dataType: 'json', // Let's assume the PHP script will send us a JSON response
success: function(data) { // Gets called if the entire request is successful
console.log('Server returned level options for class ' + selectedClass, data);
// data now contains the array of options for levelSelector.
// I'm going to assume you know how to loop through them and populate levelSelector
}
});
});
We need the exact same code for levelSelector, just changing two little things:
$("#levelSelector").change( function () {
var selectedLevel = $(this).find(":selected").text();
$.ajax({
url: '/path/to/level/select/php/script.php',
data: {selectedValue: selectedLevel}, // Send this data to the PHP script
dataType: 'json', // Let's assume the PHP script will send us a JSON response
success: function(data) { // Gets called if the entire request is successful
console.log('Server returned teacher options for class ' + $("#classSelector").find(":selected").text() + 'and level ' + selectedLevel, data);
// data now contains the array of options for teacherSelector.
// I'm going to assume you know how to loop through them and populate teacherSelector
}
});
});
Cool. Now, let's get one of our PHP scripts setup. I'm going to assume you are using a MySQL database, and for this example I am not going to include any of the code you need to use to cleans and secure the script (you can find that all over other questions on SO). Most of the PHP script is a straight copy/paste from W3Schools.
<?php
header('Content-Type: application/json'); // We are going to send a JSON response
// Server connection info
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$selectedValue = $_REQUEST['selectedValue'];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM levels WHERE class = " . $selectedValue; // THIS IS AN EXAMPLE. IN PRODUCTION, ALWAYS CLEAN USER INPUT FIRST.
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
$results = array();
while($row = $result->fetch_assoc()) {
$results[] = $row;
}
echo json_encode($results);
} else {
echo json_encode("0 results");
}
$conn->close();

Related

PHP - When a checkbox gets checked send a request to run a query on the database

So I've been working on this code for awhile now and I've done a lot of debugging but can't figure this out. What I want to do is: if a checkbox is checked send a request to run a query on the mySQL database FROM items WHERE .class(of the checkbox) '<' this.value(of the checkbox again) then get the filtered results and then use my javascript to format it:
index.php:
<form>
<label><input type="checkbox" class="calories "name="calories" value="300">Less than 300</label><br>
<label><input type="checkbox" class="calories" name="calories" value="500">Less than 500</label><br>
</form>
<script>
$("input.calories:checkbox").on("change",function(){
if(this.checked){
var column = $(this).attr('class'); //The class determines which column of the table is called
var value = $(this).attr('value'); //Takes the numeric value from the selected box
console.log(column);
//$.post('showItems.php', {type: column});
//$.post('showItems.php', {value: value});
//Can we call the php code above to run a query using variables column and value?
//make a php function above and call it
// function below will run showItemss.php?c=column?v=value
$.ajax({
type: "POST",
url: "showItems.php" ,
data: { c: column,
v: value},
error: function(){console.log("error")},
success: function(data) {
console.log("success");
console.log(test);
console.log(filteredList);
</script>
Here is the PHP file showItems.php I'm calling (the relevant part):
//This array holds items from database.
$itemList = array();
//Connect and Select
$con = makeConnection($dbhost, $dbuser, $dbpass, $dbname);
//Get the value and type from the javascript below
//If the type is null display the whole table
$c = $_POST['c'];
//echo $c;
//$v = mysqli_real_escape_string($con,$v);
//$type = $_POST['value'];
if($c==null){
$query = "SELECT * FROM items";
}
else{
$v = $_POST['v'];
$query = "SELECT * FROM items WHERE ".$c."< ".$v."";
}
$result = mysqli_query($con, $query);
//Collect data from all items
while($row = $result->fetch_assoc())
{
$tempItem = new Item($row['itemID'], $row['itemName'], $row['price'], $row['description'], $row['calories'], $row['protein'], $row['choles'], $row['sodi'], $row['picLink']);
$itemList[] = $tempItem;
}
echo json_encode($query);
?>
<script>
var test = <?php echo json_encode($query); ?>;
var filteredList = <?php echo json_encode($itemList); ?>;
</script>
So I want this code to be run every time I click a checkbox in my Index.php file so I can get the updated filtered items, $itemList, but I cannot figure out how to do this. Something I've done to test this is store my php values as javascript variables, Include showItems.php then console.log the variables from ShowItems.php in Index.php, and the query isn't being updated upon click which makes sense I guess. In the AJAX success function 'data' contains the entire HTML source with an updated query, but I can't figure out how use only the specific code I need in the success function. Any ideas at all would be helpful.
Try doing this:
Go from on("change",...) to on("click",...)
Also try using instead of this.checked, $(this).prop("checked") which will return you true or false depending on wether the checkbox is checked or not.
You might want to change either your selector or your checkbox classes because both are the same, and can give you undesired functionality in order to get your values when you click on a checkbox, since the selector finds you both checkboxes.
Hope this ideas can get you closer where you want to be.
Cheers

Trying to print onto an html page via PHP

I'm making a custom WYSIWYG editor with a save function, and through the save function I have run some code to get everything within a certain div, save it into a data table or overwrite it. But right now, I'm trying to load the page back.
The process is as follows: you press the save button, and it runs a PHP script called save.php, which is seen below.
My issue is that I want it to load or echo the contents within a certain div on the original html page. How would I go about doing that? I need it to work like Javascript's innerHTML function, basically.
Below are the files I use, at least the relevant parts.
test.html:
<form method="post" name="blog-post" id="blog-post">
<input type="hidden" name="postID" value="1"><!--Get the post's id-->
<div class="blog-editor-bar">
<a href="#" data-command='save'
onclick="submitForm('save.php');">
<i class='fa fa-save'></i>
</a>
</div>
<div id="blog-textarea" contenteditable>
</div>
<textarea style="display:none;" id="blog-post-cont" name="post-content"></textarea>
</form>
test.js:
function submitForm(action){
var theForm = document.getElementById("blog-post");
theForm.elements("post-content").value = document.getElementById("blog-textarea").innerHTML;
theForm.action = action;
theForm.submit();
}
save.php:
$conn = mysqli_connect('localhost', 'root', '', '');
if (mysqli_connect_errno()){
echo "<p>Connection Failed:".mysqli_connect_error()."</p>\n";
}
//store stuff in database
//Get Variables
$postid = $_POST['postID'] ? $_POST['postID'] : null;
$post = $_POST['post-content'] ? $_POST['post-content'] : null;
//if exists, overwrite
if($postid != null || $postid != ""){
$sqlSave = "SELECT * FROM wysiwyg.post WHERE idpost = $postid";
$rSave = mysqli_query($conn, $sqlSave) or die(mysqli_error($conn));
if(mysqli_num_rows($rSave)){
$sqlOverwrite = "INSERT INTO wysiwyg.post(post) VALUES(?) WHERE idpost = ?";
$stmt = mysqli_prepare($conn, $sqlOverwrite);
mysqli_stmt_bind_param($stmt, "sd", $post, $postid);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
mysqli_close($conn);
} else {
newSave();
}
loadSave();
}
function newSave(){
$sqlNewSave = "INSERT INTO wysiwyg.post(post) VALUES(?)";
$stmt = mysqli_prepare($conn, $sqlNewSave);
mysqli_stmt_bind_param($stmt, "s", $post);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
mysqli_close($conn);
}
function loadSave(){
$sqlLoad = "SELECT * FROM wysiwyg.post WHERE idpost = $postid";
$rLoad = mysqli_query($conn, $sqlLoad) or die(mysqli_error($conn));
//This is the part I'm stuck on
}
Thank you all in advance for helping me out! I've been stuck on it for at least a few hours!
EDIT: Before people comment on SQL Injections, I have taken it into consideration. This is me getting the code working on my localhost before I run it through a ton of anti-sql injection methods that I have already done in the past. The code i provide is only important to the functionality at this point.
EDIT #2: The anti-injection code already exists. I guess i seem to have forgotten to provide that information. I repeat, the code I have provided here is only code relating to functionality. I have escaped the strings, trimmed, etc. and more, but that code is not necessary to provide for people to get an understanding of what it is i am trying to do.
You can use an AJAX request to communicate with the server, send data and receive a response. There are many good tutorials out there, but since I first learned it in W3Schools website I am going to refer you there.
JavaScript tutorial.
jQuery tutorial.
You can use an AJAX request which is written like this:
<script>
$(document).ready(function(){
$.ajax({ //start an AJAX call
type: 'GET', //Action: GET or POST
data: {VariableName: 'GETvalue'}, //Separate each line with a comma
url: 'Destination.php', //save.php in your case
success: function(data)){ //if values send do this
//do whatever
}
}); //end ajax request
});
</script>
This allows you to send information to your php page without refreshing
So in my example you can do this on the PHP side
<?php
echo $_GET['VariableName'];
?>
Will echo out "GETvalue as specified in the data section of the Ajax call"
EDIT************
In the AJAX call you can add dataType if you want json
$.ajax({
type: 'GET',
data: {VariableName: 'GETvalue'},
dataType: 'json' // Allows Json values or you can change it to whatever you want
url: 'Destination.php',

Getting a variable from my form to my parser file via ajax

I'm a total AJAX noob, so please forgive me, but this is what I'm trying to do...
I have a php form that submits the information via ajax to a parser file. I need to get a few ids from that form to the parser file so I can use them in my sql update. I'll try to keep my code simple but give enough info so someone can answer.
My form is being generated via a foreach loop that iterates through a list of teams and grabs their various characteristics. For simplicity, let's say the main thing I need to get to the parser file is that team_id.
I'm not sure if I need to add
<input type="hidden" name="team_id" value="<?=$team->id ?>">
or
<tr data-teamid="<?=$team->id; ?>">
or something like that to my form....but either way, it gets passed through this AJAX file...
<script type="text/javascript">
function updateNames() {
jQuery('#form-message, #form-errors').html("");
var post_data = jQuery('form[name="update_names"]').serialize();
$.ajax({
url: 'parsers/update_names.php',
method: 'POST',
data : post_data,
success: function(resp) {
if(resp == 'success'){
jQuery('#form-message').html("Names and Scores have been Updated!");
}else{
jQuery('#form-errors').html(resp);
}
}
});
return false; // <--- important, prevents the link's href (hash in this example) from executing.
}
jQuery(document).ready(function() {
$(".linkToClick").click(updateNames);
});
</script>
And is making it to my parser file, which looks like this...
require_once '../core/init.php';
$db = DB::getInstance();
$errors = [];
// $camp_id = Input::get('camp_id');
$camp_id = 18;
//Find the Teams that Belong to the Camp
$sql = "SELECT * FROM teams WHERE camp_id = $camp_id";
$teamsQ = $db->query($sql);
$all_teams = $teamsQ->results();
//validation and sanitization removed for simplicity.
if(empty($errors)){
$fields = [];
foreach($_POST as $k => $v){
if($k != 'camp_id'){
$fields[$k] = Input::get($k);
}
}
$db->update('teams',$all_teams->id,$fields);
echo 'success';
}else{
echo display_errors($errors);
}
SO. The main question I have is how do I get that camp_id and team_id into the parser file so I can use them to update my database?
A secondary question is this...is the fact that the form is being generated by a foreach loop going to make it difficult for the ajax to know which field to update?
So, how would I get that camp_id to
$sql = "SELECT * FROM teams WHERE camp_id = $camp_id";
And the team_id to
$db->update('teams',$all_teams->id,$fields);
I tried to break this down to the simplest form and it's still not getting to the function. This code...
<form name="update_names" method="post">
<input type="hidden" name="team_id" value="<?=$teams->id ?>">
<button onclick="updateNames();return false;" class="btn btn-large btn-primary pull-right">test</button>
<script type="text/javascript">
function updateNames() {
alert('test');
}
</script>
Gives me... Uncaught ReferenceError: updateNames is not defined
The jQuery .serialize() method uses the name attribute of an element to assign a variable name. It ignores the element's id, any classes and any other attribute. So, this is the correct format if using .serialize():
<input type="hidden" name="team_id" value="<?=$team->id ?>">
Looking at your ajax code, your parser file would be called parsers/update_names.php.
To verify that the desired field is getting to your parser file, add this to the top for a temporary test:
<?php
$tid = $_POST['team_id'];
echo 'Returning: ' .$tid;
die();
and temporarily modify the ajax code block to:
$.ajax({
url: 'parsers/update_names.php',
method: 'POST',
data : post_data,
success: function(resp) {
alert(resp);
{
});
return false;
If the ajax processor file (your "parser") receives the team_id data, then you will get that data returned to you in an alert box.
Thus, you can now determine:
1. That you are receiving the team_id information;
2. That the ajax back-and-forth communications are working
Note that you also can install FirePHP and echo text to the browser's console from the php processor file.

How to call php function from html select option onChange?

So Ive been struggling with this problem all day and can't seem to get around it.
I need to call a php query whenever an option from a dropdown menu is selected.
<select class="selectpicker" id="headSelector">
<?php
$cname = $_GET['cname'];
$linkID = mysql_connect("localhost","USER","PASS");
mysql_select_db("USR", $linkID);
$SQLCurr = "SELECT `AName` FROM `Char-Armor` WHERE `CName` = '$cname' AND `AType`= 'Head'";
$currHeadValues = mysql_query($SQLCurr, $linkID);
$currRow = mysql_fetch_row($currHeadValues);
$curr = $currRow[0];
if($curr == '' || $curr == NULL){
$curr = 'None';
}
$SQLHead = "SELECT AName FROM `Armor` WHERE AType = 'Head'";
$allHeadValues = mysql_query($SQLHead, $linkID);
echo "<option>".$curr."</option>";
while($row = mysql_fetch_assoc($allHeadValues)){
echo "
<option>".$row['AName']."</option>
";
}
?>
</select>
The php part needs to take the 'AName' from the option and use it to insert into a table.
I have done a lot of reading about AJAX but I do not quite understand how it is supposed to work. I think it is like html -> js -> Ajax -> php
I need it to stay on the same page when an option is selected.
Any explanation would be great, thanks!
Here's what you can do.
1). As soon as an option is selected, run a jquery onchange event and get the value of the selected option.
2). Now, run an ajax request with the value of the selected value and post this data to a backend php file.
3). Now on this backend php file, receive data and process (run the query).
Code Sample.
Change your option line in this way.
<option value="$row['AName']">".$row['AName']."</option>
jQuery-Ajax
$("#headSelector").change(function(e){
//get the value of the selected index.
value = $(this).val();
//make an ajax request now
$.ajax({
url: 'yourPhpBackendScript.php',
type: 'POST',
data: {value: value},
success:function(response)
{
alert(response);
}
})
})
yourPhpBackendScript.php
//You can now receive the selected value as $_POST['value'];
//get the value now
$value = $_POST['value'];
//you can apply validations if you want.
//Now, run the query and send a response. Response can be a simple message like data submitted etc. So
runQueryHere
echo "inserted"; //response returned to ajax rquest
First of all, return the string like this:
$options_arr = '';
while($row = mysql_fetch_assoc($allHeadValues)){
$options_arr .= "<option>".$row['AName']."</option>
";
}
echo $options_arr;
Use the change event like this:
$("#headSelector").change(function(){
$.ajax({
data: '',
url: 'your_url',
type: 'POST',//Or get
success: function(options_array){
$("#headSelector").empty().append(options_str);
}
});
});

Jquery/AJAX populated HTML form when dropdown selected

I am trying to populate a form on my page. The information required to populate the form is pulled from a MySQL database using the ID of the drop down option as the ID in the SQL statement. I was thinking that I can store the information in $_SESSION['formBookings'] and on a refresh this will populate the form (this is already happening as I am using the session variable to populate the form after a submit.
I can not have a submit button attached to the form as I already have one and the boss doesn't want another. I would like the form to eventually automatically refresh the page on the selection of an option. If the data from the SQL statement has been stored in the session array then the form will be populated.
Here is what I have so far:
The JQuery:
<script>
$(document).ready(function(){
$('select[name=recall]').on('change', function() {var recall = $(this).val()
//$(function ()
//{
//-----------------------------------------------------------------------
// 2) Send a http request with AJAX http://api.jquery.com/jQuery.ajax/
//-----------------------------------------------------------------------
$.ajax({
url: 'recall.php', //the script to call to get data
data: "recall: recall", //you can insert url argumnets here to pass to api.php
//for example "id=5&parent=6"
dataType: 'json', //data format
success: function(data) //on recieve of reply
{
var id = data[0]; //get id
var vname = data[1]; //get name
//--------------------------------------------------------------------
// 3) Update html content
//--------------------------------------------------------------------
$('div#box1').load('DFBristol.html');//html("<b>id: </b>"+id+"<b> name: </b>"+vname); //Set output element html
//recommend reading up on jquery selectors they are awesome
// http://api.jquery.com/category/selectors/
//}
});
});
});
});
</script>
The HTML:
<select name='recall' id='recall'>
<option selected></option>
<?php
session_start();
$user = 'root';
$pass = '';
$DBH = new PDO('mysql:host=localhost;dbname=nightlineDB;', $user, $pass);
$DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$DBH->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$recall = $DBH->prepare('SELECT * FROM bookings WHERE dateInputted >= now() - INTERVAL 2 DAY');
$recall->execute();
$recallResult = $recall->fetchALL(PDO::FETCH_ASSOC);
foreach ($recallResult as $key) {
echo '<option id='.$key["ID"].'>'.$key['ID'].' - '.$key['branch'].' - '.$key['title'].' '.$key['firstName'].' '.$key['lastName'].'</option>';
}
?>
</select><br />
The SQL file (recall.php):
<?php
$user = 'root';
$pass = '';
$DBH = new PDO('mysql:host=localhost;dbname=nightlineDB;', $user, $pass);
$DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$DBH->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$recall = $DBH->prepare("SELECT * FROM bookings WHERE ID = '%$recall%'");
$recall->execute();
$recallFormResult = $recall->fetchALL(PDO::FETCH_ASSOC);
echo json_encode($recallFormResult);
?>
I have tried to pass the variable 'recall' from the jquery into the SQL statement using the data argument but nothing happens.
Could someone please help me understand what I am doing wrong and how I can resolve it.
On a quick glance there seems to be two issues with the code you've posted so far:
The AJAX request
Even though $.ajax() defaults to a request type of GET by default, it's good to specify it. There is also a syntax error in your request — you have closed the success callback with a }); where it should be a } only:
$.ajax({
url: "recall.php",
data: {
recall: recall
},
type: "GET", // Declare type of request (we use GET, the default)
dataType: "json",
success: function(data)
{
var id = data[0];
var vname = data[1];
$('div#box1').load('DFBristol.html');
} // The problematic closure
});
Even better: instead of using the deprecated jqXHR.success() function, use the .done() promise object instead, i.e.:
$.ajax({
url: "recall.php",
data: {
recall: recall
},
type: "GET", // Declare type of request (we use GET, the default)
dataType: "json"
}).done(function() {
// Success
var id = data[0],
vname = data[1];
$('div#box1').load('DFBristol.html');
});
Fixing the file recall.php
When you make an AJAX GET request to recall.php, the file needs to know what variables you intend to pass, which you have not defined. You can do that using $_GET[] (see doc), i.e.:
<?php
// Assign the variable $recall with the value of the recall query string from AJAX get request
// I recommend doing a check to see if $_GET['recall'] is defined, e.g.
// if($_GET['recall']) { $recall = $_GET['recall']; }
$recall = $_GET['recall'];
// The rest of your script, unmodified
$user = 'root';
$pass = '';
$DBH = new PDO('mysql:host=localhost;dbname=nightlineDB;', $user, $pass);
$DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$DBH->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$recall = $DBH->prepare("SELECT * FROM bookings WHERE ID = '%$recall%'");
$recall->execute();
$recallFormResult = $recall->fetchALL(PDO::FETCH_ASSOC);
echo json_encode($recallFormResult);
?>
Note: However, if you choose to make a POST request, then you should use $_POST[] (see doc) instead :)

Categories