How to call php function from html select option onChange? - javascript

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);
}
});
});

Related

Sending Ajax Request to PHP not working

I am trying to make an ajax request to my PHP file.
The ajax request occurs when my "Country" select option menu changes. The result is suppose to be a new select option menu titled "State Province" and the options would be based off the choice made in the "Country" select option menu.
This is what I want it to look like:
The problem I'm having is when the ajax is making a request to the PHP, the PHP seems to be returning an empty array:
Does anyone know what might be wrong?
Thank you!
HTML for the select option:
<select name="Country" class="form-control input-sm" id="Country">
</select>
Ajax code with the onchange function:
$("#Country").on("change",function(){
var val = $('#Country').val();
performAJAX(val,'Country','StateProvince');
});
function performAJAX(choice,prevSelect,newSelect){
$.ajax({
type: "post",
url: "select-creation.php",
data: {choice: choice, prevSelect: prevSelect,newSelect: newSelect},
dataType: "json",
success: function(data){
var obj = $.parseJSON(data);
console.log("meow meow");
}
});
}
PHP code:
<?php session_start();
try{
$choice = $_POST['choice'];
$prevAttri = $_POST['prevSelect'];
$nxtAttri = $_POST['newSelect'];
$data = array();
$sql = 'SELECT '.$nxtAttri.' FROM agents WHERE '.$prevAttri.' = :userChoice';
include_once $_SERVER['DOCUMENT_ROOT'].'/inc/Database.class.php';
$db = new Database();
$conn = $db->getConnection();
$query = $conn->prepare($sql);
$query->bindValue(':userChoice',$choice,PDO::PARAM_STR);
if($query->execute()){
$data = $query->fetchAll(PDO::FETCH_ASSOC);
}//stmt
return json_encode($data);
}catch(PDOException $e){
echo $e->getMessage();
}
?>
Your code return json_encode($data); seems to be nothing or invalid because your code doesn't use a function.
Just use echo json_encode($data);
In the ajax side, you don't need to use $.parseJSON(data); because you already specify the dataType to json it will immediately convert the data response by PHP to an object type.

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

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

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();

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.

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