User ID dropdown

I ask this question because I do not know how to best solve my problem.

Problem: I have a pre-populated drop-down list of 1000 or so numbers. I need to limit which numbers appear in the drop-down list based on which user uses the drop-down list.

The solution I was thinking about:

  • Hide all numbers with jQuery
  • Use jQuery / AJAX to call the database, pass user id
  • DB returns a list of values ​​based on user ID
  • Show drop-down options with the same values ​​as the numbers returned from the database

Let's 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 the basic js / jQuery, and I am not very knowledgeable about the DB, so I welcome any suggestions that may help me fulfill my final goal.

EDIT / NOTE: How stupid it sounds ... Security is not great here. This will be used on the company's internal website, where if the user feels the need to hack and select a different number, it really does not matter. I also do not foresee any of the company employees who have a desire / need / desire to choose a different option than they are allowed.

In addition, the list must be pre-populated and then hidden. Its the way I use the platform is configured, so I need to use show / hide or something like that.

+8
javascript jquery database ajax
source share
8 answers

If this is an example of a database table and an example of a Select element. Then I think that 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 move on to coding. I will try to explain what I write and how I write; since you are new :-)

HTML code for you

HTML code for your work would be simple, like this

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

Getting UserId

Now, as soon as the user is logged in. Try to get UserId in any of the following ways.

JQuery

To use jQuery, you will need to use the value generated by the server, since jQuery cannot interfere with server requests and code. Thus, you can create a simple hidden input and assign it the value of the current registered user. Here is an example

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

Now, using jQuery, you can get the value for this input. There will be code for this

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

ASP.NET

To use ASP.NET, you are not doing anything. All you do is use the built-in ASP.NET method as

 WebSecurity.CurrentUserId; 

and it will give you an integer value. What will be the userId of the current user.

Using WebSecurity

WebSecurity, as indicated in the following link, is a data class. Which can be used in your application to reduce code and help you get user properties faster.

This class is used as a value for a variable or as a parameter. This method returns a specific property of the user. For example, you can get the User UserId, its UserName, your CreateDate, or you can use WebSecurity to log in to the user or log him out of the system.

Here is an example of using WebSecurity. Just 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 in your database query,

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

or, write it inside the document

 Response.Write(userId); 

Or do what you want to do. You can find out the syntax of the Class and other materials in the MSDN links. :-)

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

Submit Ajax Request

Now send your Ajax request. If you know, then great! If not, here is an example of an 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 } }); 

As soon as this is done. It will update the "Select Item" options. But wait, what would he add to this?

It's you who controls it. You are editing the server side code as follows.

Retrieving data from a database.

If you are new to Databases and ASP.NET, you need to learn a little first.

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

Well, you can find out about this a bit later. I’ll still explain to you all my code. :-)

So, for a database, you first need to create a database connection, and then you can search for 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 receiving all these values, all you have to do is create a response that will be sent to the client.

Hope you are using web page technology. Good! You are one step safer than others.

Just click “Down” and go 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 that will be added to the select element.

PS Another method (Actual method) for issuing a response uses the Actuall HttpResponse class and then gives it values. Like this

 Response.Write("Hello World!"); 

If you write the line above, it will add that line to your select statement ( albeit illegal ), but it will help you understand its use.

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

+2
source share

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

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

Just because you can easily add / remove / update values ​​in the future rather than parsing a comma-separated value.

I would not use jQuery to just “hide” because Javascript can be disabled by the user and he can end up passing any value he wants (visible or invisible). Never trust user input.

In conclusion, do the following:

  • Use jQuery / AJAX to call the database, pass user id
  • DB returns a list of values ​​based on user ID
  • Fill in the drop-down list with the values ​​returned from the database.
  • Validate the server-side form to ensure that the value represented is in the user_value table.
+5
source share

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

The list will be pre-populated by the client side (from a server that I cannot access / modify). Then call AJAX to another database (simple, two columns). THEN returns the values ​​to the 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 the server) so that you only make one AJAX call (from the client)?

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

This service will make calls to both databases to return a list of a valid parameter for a given user ID. This allows the server to do most of the heavy lifting and greatly reduces the amount of jQuery on the client.

Additional Information:

The url that jQuery uses to call AJAX.

The easiest way to do this:

  • Create a web page called http://mySite/MyService.aspx
  • Add the public GetOptionsForUser () method, which takes 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.
  • On an existing web page where you want to fill in your drop-down lists, you call AJAX at http://MySite/MyService.aspx/GetOptionsForUser and pass the ID to the User as an AJAX parameter.
+1
source share

I think a good way to do this would be to use JSON for all users. prepare a json array for users with parameters and create them based on users to fill in parameters. eg.

 var user1 = '["101","102","103"]'; 
+1
source share

This is an example that shows how jquery ajax and php work:

for example, when the button clicked on ajax, send an order to the server language (php) and execute a php-request for this order and it will show a suitable answer:

 $("#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 the php code called 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();'; } } ?> 
+1
source share

Simple task. I’ll try to answer what you thought.

0. Existing HTML

 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 invoke the database by passing the user ID and 3. DB returns a list of values ​​based on the user ID

 <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 parameters in quotation marks that have the same values ​​as the numbers returned from the database

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

Since you say that you have pre-filled entries, I would go with this approach -

  • First save all the elements of the JS array when loading the page

      var alloptions = $("select").find("option").get(); 
  • Then, for each user ID, after receiving the list of elements, display and hide them as shown below:

      //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]); } } } } }); 
+1
source share

If you only need to fill in once when loading the first page, this is the best option for 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 what you need for asp.net, so try converting this

+1
source share

All Articles