I am working on a very basic administrator functionality of a social network and I came across this issue of not being able to remove an option from select dropdown list that I previously generated using jquery. The dropdown list contains all users of the social network. Administrator upon clicking on "Delete account" deletes the corresponding record from the database.
Now the question being - when I click on "delete account" it works perfectly fine but the option with a username is still there in a dropdown list and is possible to be picked - when picked it obviously returns dozens of PHP warnings and errors because the record is not in a database anymore. How can I remove this option straight away? I tried something like the following, but it doesn't work.
admin_panel.php (only relevant stuff)
<select name='users' id='users'>
<option value="" disabled selected>Select user</option>
<?php
$sql = mysql_query("SELECT * FROM users WHERE id <>'".$_SESSION['user_id']."'ORDER BY username DESC") or die(mysql_error());
$userList = [];
while($row=mysql_fetch_assoc($sql)){
$username = $row['username'];
$userID = $row['id'];
$userList .= '<option name="userID" value='.$userID.'>'.$username.'</option>';
}
echo $userList;
?>
</select></br></br></div>
<div id="user_info">
<!-- generated user info table-->
</div>
<script type="text/javascript">
"$('#user_info').on('click', '#deleteAccount', function(e){
data.command = 'deleteAccount'
data.userID = $('#users').val()
$.post(theURL, data, function(result){
//Do what you want with the response.
$('#delete_account_success').html(result);
})
$("#users option[value='data.userID']").remove();
$('#delete_account_success').show();
$('#delete_account_success').fadeOut(5000);
})
</script>
processUser.php (part of a switch statement)
if(isset($_POST['command'])){
$cmd = $_POST['command'];
$userID = $_POST['userID'];
$sql=mysql_query("SELECT * FROM users WHERE id='".$userID."'");
$userData = [];
while($row = mysql_fetch_assoc($sql)){
$userData['userid'] = $row['id'];
$userData['username'] = $row['username'];
$userData['name'] = $row['name'];
$userData['date'] = $row['date'];
$userData['email'] = $row['email'];
$userData['avatar'] = $row['avatar'];
$userData['about'] = $row['about'];
$userData['admin'] = $row['admin'];
}
switch($cmd){
case 'deleteAccount':
$sql= "DELETE FROM users WHERE id =".$userID;
$result=mysql_query($sql);
echo "<img src='pics/ok.png' class='admin_updated_ok'>";
break;
}
On this line
$("#users option[value='data.userID']").remove();
You're removing any option items from #users where the value is equal to the string literal data.userID
Try changing it to
$("#users option[value='" + data.userID + "']").remove();
Related
I'm trying to dynamically generate radio buttons with data in front of them. The data that is to be displayed in front of the radio button is based on a drop down selection, which also displays some data in a text box using javascript.
I tried taking the selected option in a string and use it in the next query, but I know I am doing it wrong.
Database Connection
$db = pg_connect("");
$query = "select account_name,account_code,address1,address2,address3 FROM
customers";
$result = pg_query($db,$query);
//NEW QUERY
$sql1= "select name from conferences";
$result1= pg_query($db, $sql1);
//END
//New Code
<select class="form-control" id="conference" name="conference">
<option value="">Select Conference...</option>
<?php while($rows1 = pg_fetch_assoc($result1)) { ?>
<option value="<?= $rows1['code']; ?>"><?= $rows1['name']; ?></option>
<?php } ?>
</select>
<br>
// END OF NEW CODE
Dropdown to select the data.
<select onchange="ChooseContact(this)" class="form-control"
id="account_name" name="account_name" >
<?php
while($rows= pg_fetch_assoc($result)){
echo '<option value=" '.$rows['address1'].' '.$rows['address2'].'
'.$rows['address3'].''.$rows['account_code'].'">'.$rows['account_name'].'
'.$_POST[$rows['account_code']].'
</option>';
}?>
</select>
Displaying data in the text area based on the selcted value using javascript. (The code works fine till here)
<textarea readonly class="form-control" style="background-color: #F5F5F5;"
id="comment" rows="5" style="width:700px;"value=""placeholder="Address...">
</textarea>
<script>
function ChooseContact(data) {
document.getElementById ("comment").value = data.value;
}
</script>
Displaying data in front of the radio buttons based on the selected option(This code works if I use some random value in the query, but not if I use the selected value 'account_code' from the previous query. I'm using POST GET method to carry the selected value)
<?php
//NEW CODE
$sql = "select order_number, order_date from orders where
customer_account_code = '3000614' and conference_code='DS19-'"; <-Data
gets displayed when put random value like this.
$code = $_GET[$rows['account_code']];
$conf = $_GET[$rows1['conference_code']];
$sql = "select order_number, order_date from orders where
customer_account_code = '$code' and conference_code= '$conf']"; <- But I
want to display the data against the selected value, i.e, the 'account_code'
in the variable $code from the dropdown select
//END
$res = pg_query($db,$sql);
while($value = pg_fetch_assoc($res) ){
echo "<input type='radio' name='answer'
value='".$value['order_number']." ".$value['order_date']."'>"
.$value['order_number'].$value['order_date']." </input><br />";
}
?>
I need to help to find a way to put the selected 'account_code' in a variable and use it in the $sql query.
Please try with this code : (It's work for me)
1- Add this line to your HTML <head>:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js" type="text/javascript"></script>
2- Edit your CODE to this:
Dropdown to select the data:
<select class="form-control" id="account_name" name="account_name">
<option value=""></option>
<?php while($rows = pg_fetch_assoc($result)) { ?>
<option value="<?= $rows['address1'].' '.$rows['address2'].' '.$rows['address3'].'-'.$rows['account_code']; ?>"><?= $rows['account_name']; ?></option>
<? } ?>
</select>
Displaying data in the text area based on the selected value using jQuery:
<textarea readonly class="form-control" style="background-color: #F5F5F5;"
id="comment" rows="5" style="width:700px;" value="" placeholder="Address..."></textarea>
jQuery Code:
<script type="text/javascript">
$('#comment').val($('#account_name').val()); // MAKE A DEFAULT VALUE
(function($) {
$('#account_name').change(function() {
$('#results').html(''); // REMOVE THE OLD RESULTS
var option = $(this).val();
$('#comment').val(option);
// EDIT RADIO WITH AJAX
$.ajax({
type: "POST",
url: "path/test.php",
dataType:'JSON',
data: $('#account_name').serialize()
}).done(function(data) {
for (var i = 0; i < data.length; i++) {
// ADD RADIO TO DIV RESULTS
$('#results').append('<input type="radio" name="answer" value="'+data[i].order_number+'">'+data[i].order_date+'</input><br>');
}
});
});
})(jQuery);
</script>
after that, add this HTML to your page, to show RESULTS FROM AJAX DATA
<!-- RADIOs -->
<div id="results"></div>
3- Create a new file like path/test.php
in this file, use this CODE to return values with JSON :)
<?php
header('Content-type: application/json');
// CONNECT (JUST USE YOUR CUSTOM CONNECTION METHOD & REQUIRE CONFIG FILE IF YOU WANT)
$db = pg_connect("");
$value = explode('-', $_POST['account_name']);
// EXPLODE AND GET LAST NUMBER AFTER < - >
$code = (int) end($value);
$sql = "select order_number, order_date from orders where customer_account_code = '$code'";
$res = pg_query($db, $sql);
// CREATE JSON RESULTS
$is = '';
while($data = pg_fetch_assoc($res)) {
$is .= json_encode($data).', ';
}
// AND GET ALL
echo '['.substr($is, 0, -2).']';
?>
I have run into a problem and Im not sure where to start... So my problem is- I need to use a dropdown which is automatically populated by a query concatenating two fields to make a single full-name. Then based off the name of the person selected change the value of the text input to be the dob, then also update every change when a new name selected. I have tried using the onchange event for select but just cant work out the right combination.
<?php
$conn = new mysqli('localhost', 'username', 'password', 'database') or die ('Cannot connect to db');
$result = $conn->query("SELECT id, dob, CONCAT(`space`,`firstname`,`lastname`) AS `whole_name` FROM `table`");
echo "<select name='id'>";
while ($row = $result->fetch_assoc()) {
$data = $id
unset($id, $name);
$id = $row['id'];
$name = $row['whole_name'];
echo '<option value="'.$id.'">'.$name.'</option>';
}
echo "</select>";
?>
<input type="text" id="text" value="<?php echo "$data" ?>"/>
Things to note - due to the concatenate needing a separator 'space' has been added to a field. at this time the sql query works exactly as intended. When loading the page in the current state the text field comes up with the correct value for the first name, but does not update when changing value of select.
Im new with PHP and mySQL - self learning as I go. Any help appreciated.
Ajax not needed here. You can just put the dob value as special attribute for each options, and then change the text input with javascript when the select value change.
Here the new select with dob in attribute :
while ($row = $result->fetch_assoc()) {
$data = $id
unset($id, $name);
$id = $row['id'];
$dob = $row['dob'];
$name = $row['whole_name'];
echo '<option dob="'.$dob.'" value="'.$id.'">'.$name.'</option>';
}
and then update the input when the select change, here an example with jquery :
$("select[name=id]").change(function(event) {
//get the dob attribute
var dob = $('option:selected', this).attr('dob');
// update the text input
$("input#text").val(dob);
});
I have a form where user selects the category while adding the product.
When user want to edit the product, i am displaying all the previously populated values but could not able to figure out how to display the category he selected.
addproduct.php (displaying the categories from the database)- this code is working fine and can see all the categories in dropdown
<?php
require'dbconn.php';
$subject = mysql_query("select * from categories", $link);;
while($subjectData = mysql_fetch_array($subject)){
echo $subjectData['value'];?>
<option value="<?php echo $subjectData['name'];?>"><?php echo
$subjectData['name'];?>
</option>
In the edit product i want to display all the categories like above, but want to display the selected category in the form which i could not able to do.
editproduct.php (rough draft code) -- not working
<?php
require'dbconn.php';
$subject = mysql_query("select * from categories", $link);;
while($subjectData = mysql_fetch_array($subject)){
echo $subjectData['value'];?>
<option select="<?php echo $cat;?>"value="<?php echo $subjectData['name'];?>"><?php echo
$subjectData['name'];?>
</option>
$cat - category value(previously selected) pulled from database
require'dbconn.php';
$subject = mysql_query("select * from categories", $link);;
<option value="<?php echo $cat;?>"><?php echo $cat;?></option>
while($subjectData = mysql_fetch_array($subject)){
echo $subjectData['value'];?>
<?php if($cat!=$subjectData['name']){?> <option value="<?
php echo $subjectData['name'];?>"><?php echo
$subjectData['name'];?>
</option>
<?php } ?>
Try using this code and please use mysqli as mysql is deprecated. previously selected category should be before while loop. Hope it helps
Two issues with your code:
You are using mysql functions, which are depreciated and don't even exist in the current version of PHP. Use mysqli or PDO functions.
The html you are generating is invalid syntax.
I'll leave the first issue to you to correct.
For the 2nd issue, all of the non-selected options in your dropdown will not have the selected attribute.
Only the selected item will have that attribute. The code below assumes that the variable $cat has the previously selected value, and each row has a
column named 'cat'. When $cat matches the value in the column 'cat', it will add selected='selected' to the option.
<?php
require 'dbconn.php';
$subject = mysql_query("select * from categories", $link);;
while($subjectData = mysql_fetch_array($subject)){
echo $subjectData['value'];
$selected = "";
if($cat == $subjectData['cat']) {
$selected = "selected='selected' ";
}
echo "<option ".$selected."value=".$subjectData['name'].">";
echo $subjectData['name'];
echo "</option>\n";
}
?>
Currently working on user management page where there are name , username , email and level fields . All fields except for level are obtained from AD. I managed to make the values saved into database. However , the name field takes both username and email field instead. The dropdown would display the name but it saves username and email.
<th align="right" scope="row">Select User</th>
<td><script type="text/javascript">
var $ = function(e){ return document.getElementById(e); }
var swap = function(val){
var arr = val.split("|");
document.getElementsByName('username')[0].value = arr[0];
document.getElementsByName('email')[0].value = arr[1];
}
</script>
<select name="name" id="name" class="reginput" onchange="swap(this.value)" />
<option value="">Select User</option>
<?php
// Create connection
$con=mysqli_connect("localhost","root","","dbname");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL:" . mysqli_connect_error();
}
//$result = mysqli_query($con, "SELECT name,Id FROM users");
$result = $this->Users_model->queryAD();
$options=$test;
//while ($row=mysqli_fetch_array($result)) {
for ($i=0; $i<$result["count"]; $i++) {
//$options .= '<option value="'.$row["name"].'">'.$row["name"].' '.'</option>';
$options .= '<option value="'.$result[$i]["samaccountname"] [0].'|'.$result[$i]["mail"][0].'">'.$result[$i]["displayname"][0].' '.'</option>';
}
$options .= '</select>';
echo $options;
For example :
Select User : Jane Doe
Username : Jane
Email : janed#yahoo.com
Level : Admin
User would be displayed as Jane | janed#yahoo.com instead of Jane Doe but other fields are fine.
This is the page for inserting users , the display is fine but Full Name wont be saved properly into DB
It takes the username and email instead of Full name because the value of the option you are giving is $result[$i]["samaccountname"][0].'|'.$result[$i]["mail"][0]
Change the value of the option to
$options .= '<option value="'.$result[$i]["displayname"][0].'">'.$result[$i]["displayname"][0].' '.'</option>';
EDIT
To display username and email to user, and saving Fullname to DB, use this:
$options .= '<option value="'.$result[$i]["displayname"][0].'">"'.$result[$i]["samaccountname"] [0].'|'.$result[$i]["mail"][0].'"</option>';
in my code i'm showing drop down select field list base on user school choice. for example -
if user choose 'School of Economics' from drop down list, i'm showing in another drop down list just the relevant lanes (based on a mysql query).
to do this i have 5 div's, on for etch school:
<div id='a'>
<span><label>Lane</label></span>
<?php
$sql = "SELECT lane_name FROM lane WHERE `lane_school_id` = 1 ORDER BY `lane_name` ASC";
$result = mysql_query($sql);
echo "<select name='lane_name'>";
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['lane_name'] ."'>" . $row['lane_name'] ."</option>";
}
echo "</select>";
?>
</div>
<div id='b'>
<span><label>Lane</label></span>
<?php
$sql = "SELECT lane_name FROM lane WHERE `lane_school_id` = 2 ORDER BY `lane_name` ASC";
$result = mysql_query($sql);
echo "<select name='lane_name'>";
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['lane_name'] ."'>" . $row['lane_name'] ."</option>";
}
echo "</select>";
?>
</div>
i have a listener to show just the right 'lane' div when user chooses school and hide all other 'lane' div's:
$(document).bind('pageinit', '#indexPage', function(){
$("#a").show();
$("#b").hide();
$("#c").hide();
$("#d").hide();
$("#e").hide();
//this will call our toggleFields function every time the selection value of School field changes
$("#school").change(function () {
toggleFieldsA();
toggleFieldsB();
toggleFieldsC();
toggleFieldsD();
toggleFieldsE();
});
});
function toggleFieldsA() {
if ($("#school").val() == 'School of Economics'){
$("#a").show();
}
else
$("#a").hide();
}
function toggleFieldsB() {
if ($("#school").val() == 'School of Computer Science')
$("#b").show();
else
$("#b").hide();
}
the problem: when user submit the form, i get the wrong 'lane_name' from POST array. i'm getting the last school selected lane value (that is hidden from the user) and not the user selected lane name , plz help
You need to give each <select> element a unique name, otherwise the last element with a particular name will be the only one you can access. PHP has no way of determining which of the 5 lane_name you are referring to.
To figure out what option set was selected you could make the first option blank: <option value=""></option>. You can add some logic to reset to the blank option when you hide/show the DIVs so only one of the lane_names will have any data in it.
The mysql_* is depreciated as of PHP 5.5.0. You should consider switching to mysqli.