最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Limiting dropdown options based on userID - Stack Overflow

programmeradmin0浏览0评论

I am asking this question because I'm unsure of the best way to solve my problem.

Problem: I have a pre-populated drop down list of 1,000 or so numbers. I need to limit which numbers appear in the drop down based on which user is using the drop down.

Solution I thought of:

  1. Hide all numbers with jQuery
  2. Use jQuery / AJAX to call a database, passing a userID
  3. DB returns a list of values based on the userID
  4. Show options in drop down that have same values as numbers returned from the DB

Lets say this is my HTML:

<select>
<option>Please Select..</option>
<option value="101"> CC 101 </option>
<option value="102"> CC 102 </option>
<option value="103"> CC 103 </option>
<option value="104"> CC 104 </option>
<option value="105"> CC 105 </option>
<option value="106"> CC 106 </option>
</select> 

And this is my DB table:

=======================
|   User1    |  101   |
|   User2    |  101   |
|   User2    |  102   |
|   User2    |  103   |
|   User3    |  103   |
=======================

I need to figure out, for example, how to pass user2 and then return 101,102,103.

I only know basic js/jQuery, and I am not very experienced with DBs, so I am welcome to any suggestions that can help me accomplish my end goal.

EDIT/NOTE: As dumb as this sounds.... Security is not a huge deal here. This will be used on an internal company website, where if a user felt the need to hack around and select a different number, it really wouldn't matter that much. I also don't foresee any of the employees of the company having the desire/need/want to select a different option than they are allowed.

Also, the list must be pre-populated then numbers hidden. Its the way the platform I am using is set up, so I have to use show/hide, or something similar.

I am asking this question because I'm unsure of the best way to solve my problem.

Problem: I have a pre-populated drop down list of 1,000 or so numbers. I need to limit which numbers appear in the drop down based on which user is using the drop down.

Solution I thought of:

  1. Hide all numbers with jQuery
  2. Use jQuery / AJAX to call a database, passing a userID
  3. DB returns a list of values based on the userID
  4. Show options in drop down that have same values as numbers returned from the DB

Lets say this is my HTML:

<select>
<option>Please Select..</option>
<option value="101"> CC 101 </option>
<option value="102"> CC 102 </option>
<option value="103"> CC 103 </option>
<option value="104"> CC 104 </option>
<option value="105"> CC 105 </option>
<option value="106"> CC 106 </option>
</select> 

And this is my DB table:

=======================
|   User1    |  101   |
|   User2    |  101   |
|   User2    |  102   |
|   User2    |  103   |
|   User3    |  103   |
=======================

I need to figure out, for example, how to pass user2 and then return 101,102,103.

I only know basic js/jQuery, and I am not very experienced with DBs, so I am welcome to any suggestions that can help me accomplish my end goal.

EDIT/NOTE: As dumb as this sounds.... Security is not a huge deal here. This will be used on an internal company website, where if a user felt the need to hack around and select a different number, it really wouldn't matter that much. I also don't foresee any of the employees of the company having the desire/need/want to select a different option than they are allowed.

Also, the list must be pre-populated then numbers hidden. Its the way the platform I am using is set up, so I have to use show/hide, or something similar.

Share Improve this question edited Apr 29, 2014 at 15:02 Brett asked Apr 23, 2014 at 19:34 BrettBrett 3911 gold badge6 silver badges22 bronze badges 5
  • 3 No matter what route you go, consider that you need to verify on the server side that the user selected an appropriate option. Otherwise any user can use their browser's debugging tools to select an invalid option, which could be a security risk. – mason Commented Apr 23, 2014 at 19:43
  • @mason thanks for the heads up. I will keep that in mind when I (hopefully) get to that point! – Brett Commented Apr 23, 2014 at 19:45
  • 1 How are you rendering this list from the server side? Your best bet is going to be populating this list on the server side since you should know what permissions each user has; this will keep you from having to worry about any smart user trying to abuse an Ajax call. – code4coffee Commented Apr 23, 2014 at 19:46
  • 1 So it must be pre-populated with all the numbers on the server, and then certain numbers hidden client-side? Please clarify what is allowed to happen where. – mr_plum Commented Apr 29, 2014 at 15:30
  • @nunzabar That's correct. The list will be pre-populated client-side (from a server I can't access/modify) THEN the AJAX call to a different DB (simple, two columns) THEN return values to original AJAX call, where THEN JS hides the values not returned (or shows the returned values, if they are initially hidden.) That's the way I see it having to happen, but it could go differently if there is a different solution. Hope that helps, let me know if that didn't clarify. – Brett Commented Apr 29, 2014 at 16:16
Add a comment  | 

8 Answers 8

Reset to default 5

I would go only with steps 2-3 of your approach; however, I would not store the numbers in the way you showed. A better approach would be to store them in a table called user_value -or something like that-:

user_id  |  value
---------+-------
user1    |  101
user1    |  102
user2    |  101

Just because you can then easily add/remove/update values in the future as opposed to having to parse the comma-delimited value.

I would avoid using jQuery to simply "hide" things because Javascript can be disabled by the user and he may end up submitting whatever value he wants (visible or invisible) - Never trust user input.

In conclusion do this:

  1. Use jQuery / AJAX to call a database, passing a userID
  2. DB returns a list of values based on the userID
  3. populate the dropdownlist with the values returned from the database.
  4. Validate the form on the server side to make sure that the value submitted is present in the user_value table.

If that's the example Database Table and an example of a Select element. Then I think the best method would be to not write anything on your own and just let the Database choose what to share and where to share.

Here we go with the coding. I will try to explain what I am writing and how I am writing; since you're a newbie :-)

HTML code for you

The HTML code for your job, would be simple as this

<select name="someName">
  <!-- No options please! -->
</select>

Getting the UserId

Now, once the user has logged in. Try to get the UserId by any one of the following method.

jQuery

To use jQuery you will need to be using the Server's generated value, because jQuery cannot interfere the Server Requests and code. So, you can create a simple hidden input and give it the value of the current logged in user. Here is the example

<input type="hidden" id="userId" value="@WebSecurity.CurrentUserId" />

Now, using jQuery you can get the value for this input. Here would be the code for that

var userId = $('#userId').val();

ASP.NET

To use ASP.NET, you don't do anything. All you do is you use the Built-in method of the ASP.NET as

WebSecurity.CurrentUserId;

and it would give you an integer value. Which would be the userId of the currently logged in user.

Usage of WebSecurity

The WebSecurity as the following link states, is a Class of data. Which can be used in your application, to lessen down the code and to help you get the User's properties at a better rate.

This class is used as a value for the variable, or as a parameter. This method would return a particular user's property. For example, you can get User's UserId, his UserName, his CreateDate, or you can use WebSecurity to Login a user, or Log him out.

Here would be an example of using WebSecurity. Just the way you create a variable in jQuery and get its value. You use this method and get the value.

jQuery Method

var userId = $('someElement').val(); 
/* get the value of some element as userId */

WebSecurity.CurrentUserId Method

var userId = WebSecurity.CurrentUserId;

Then you can use it inside the Database query,

db.Query("SELECT * FROM UserProfile WHERE UserId =@0", userId);

or, write it inside the document

Response.Write(userId);

Or do what ever you want to do. You can learn the syntax of the Class and other stuff in the links of MSDN. :-)

http://msdn.microsoft.com/en-us/library/webmatrix.webdata.websecurity(v=vs.111).aspx

Sending the Ajax request

Now send the Ajax request. If you know, then wonderfull! If not, then here is the example of the Ajax request to be sent

$.ajax({
  url: 'page_url',
  data: 'userId=' + userId, // userId that you got from input
  success: function (data) { // note the data parameter
    /* write in the select statement */
    $('select').html(data); // usage of data parameter
  }
});

Once it is done. It would update the Select element's options. But wait, what would it add to it?

It you, who control it too. You edit the server-side code to the following.

Getting the Data from Database.

If you're a newbie to the Databases and ASP.NET you need to first learn a bit.

http://www.asp.net/web-pages/tutorials/data/5-working-with-data

Ok, you can learn that a bit later too. I will still explain all my code to you. :-)

So, for Database you first need to create a Connection to the database and then you can search its tables and other content. Here is the code

var db = Database.Open("databaseName"); // Open a connection
var userId = Request.QueryString["userId"]; // get userid from ?userId=int
var selectQuery = "SELECT * FROM table_name WHERE UserId =@0"; // Query
var results = db.Query(selectQuery, userId); // Get data in a variable

After getting all these values, all that you need to do is to create a Response, to be sent to the client.

I hope, you're using Web Pages technology. Good! You're one step safer than others here.

Just press Page Down and move down to the last few lines and create a new Div element

<div>
  <!--empty div element -->
</div>

Now, write an if else statement in it and create a Response which would be added to the select element.

P.S Other method (Actual method) of giving out a Response, is using the Actuall HttpResponse class and then giving the values to it. Like this

Response.Write("Hello World!");

If you write the above line, it would add this string to your select statement (although illegal) but that would make you understand its usage.

http://msdn.microsoft.com/en-us/library/system.web.httpresponse.aspx

I'm still a little confused about your constraints, but based on your comment:

The list will be pre-populated client-side (from a server I can't access/modify) THEN the AJAX call to a different DB (simple, two columns) THEN return values to original AJAX call, where THEN JS hides the values not returned (or shows the returned values, if they are initially hidden.)

Why not create a "unifying" service (on a server) so that you only make one AJAX call (from the client)?

http://MySite/MyService.aspx/GetOptionsForUser(101)

This service would make calls to both databases an return a list of the allowable option for the given user ID. This lets the server do most of the heavy lifting and greatly reduces the amount of jQuery on the client.

More Info:

The URL is what jQuery uses to make the AJAX call.

The simplest thing to do is:

  1. Create a webpage called http://mySite/MyService.aspx
  2. Add a public method called GetOptionsForUser() that accepts an integer and returns a list of numbers. This is the "unifying" logic that queries both databases. Make the method AJAX-callable by adding the WebMethod attribute.
  3. In the existing web page where you want to populate your dropdowns, you make an AJAX call to http://MySite/MyService.aspx/GetOptionsForUser and pass the User ID as the AJAX parameter.

i think a good way to do it would be using JSON for all users. prepare a json array for users with options and render it based on users to populate options. eg.

var user1 = '["101","102","103"]';

This is an Example that shows how jquery ajax and php works to gather:

for example when a button clicked a ajax send an order to server side language (php), and php proccess that order and shows a suitable response:

$("#button").click(function(){
 $.ajax({
            type:"POST",
            url:"ajax/alertMe.php",
            data:({alert:"yes"}),
       // The alert  ^^  is the name of $_POST variable in php
            success:function(data){
                //this data can be some javascript and HTML codes or a text and ...
               evel(data);
            }
        });

})

and here is php code with name alertMe.php:

<?php
if(isset($_POST['alert']) && $_POST['alert']!=""){
if($_POST['alert']=="yes"){
  echo 'alert("the condition says I should alert!");';
}else{
   echo '$(this).fadeOut();';
}
}

?>

Since you are saying that - You have pre-populated entries I would have gone with this approach -

  1. First save all the items in a JS array at page load-

             var alloptions = $("select").find("option").get();
    
  2. Then for each user ID after getting the list of items, show and hide them as following -

            //getting the id of the user and passing to AJAX call
            $.ajax({
                url: '',
                dataType: 'json',
                type: 'GET',
                success:function(data){
                    // other codes
                    var userItemList = []; //list of items for this user [102,103, etc]
                    $("select").empty();
                    $("select").append(alloptions[0]) //the first one since it is the null one
                    for(var i = 0; i < userItemList.length; i++){
                        for(var j = 0; j < alloptions.length; j++){
                            if (parseInt($(alloptions[j]).val()) == userItemList[i]){
                                $("select").append(alloptions[j]);
                            }
                        }
                    }
    
                }
            });
    

If you only need to populate once at the first page loads this is the best option by me

Example:

HTML:
<select id="auto-populated">
    <?php
        //Next three lines you need if you dont have the user_id stored before in your code
        require('db.php');
        session_start();
        $user_id = $_SESSION['user_id'];

        //Selecting only the needed options to put here
        $sql = "SELECT dropdown_value, dropdown_option FROM tbl_dropdown WHERE dropdown_number='your-filter-kriteria-here'";
        $result = mysql_query($sql, $db) or die(mysql_error().': '.$sql);

        //After you got the filtered results from database, print them in the <select>
        echo "<option value=' '>Please select one...</option>";
        while ($item = mysql_fetch_assoc($result)) {
            echo "<option value='".$item['dropdown_value']."'>".$item['dropdown_option']."</option>";
        }
    ?>
</select>

EDIT: I see that you need for asp.net so try converting this

Straightforward problem. I will try to answer in your own way you thought of.

0. Your existing HTML code

Choose your Value:
<select id="dropDown">
    <option>Please Select..</option>
    <option value="101"> CC 101 </option>
    <option value="102"> CC 102 </option>
    <option value="103"> CC 103 </option>
    <option value="104"> CC 104 </option>
    <option value="105"> CC 105 </option>
    <option value="106"> CC 106 </option>
</select>

1. Hide all numbers with jQuery

<script>
    $("#dropDown").html("<option>Please Select..</option>");
</script>

2. Use jQuery / AJAX to call a database, passing a userID & 3. DB returns a list of values based on the userID

<script>
    $(function()
    {
        var userId = 1; <!--  Read & store the userId here  -->
        $.ajax({
            type: 'POST',
            url: 'server.php', <!--server.pl, server.js, server.asp, server.py whatever-->
            dataType: "json",
            data: {'userId': userId},
            success: function (returnData) //Returns "[101, 102, 103]"
            {          

4. Show options in drops down that have same values as numbers returned from the DB

                for (var i=0; i<returnData.length; i++)
                {
                    $("#dropDown").append("<option value='"+returnData[i]+"'> CC "+returnData[i]+" </option>");
                }
            }
        });
    });
</script>
发布评论

评论列表(0)

  1. 暂无评论