Tips for generating cascading dropdown lists with AJAX

After using the code below, I encountered an issue with storing the value of the second dropdownlist in the database when clicking on the update button. An error occurred referring to a null value. In the form.aspx.cs file, I attempted to retrieve the value by using

cmd.Parameters.AddWithValue("@department", DropDownList2.SelectedItem.ToString());
, but it ended up taking a null value.

 <script type="text/javascript">
    $(function() {
    //$('#<%=DropDownList2.ClientID %>').attr('disabled', 'disabled');
    $('#<%=DropDownList2.ClientID %>').append('<option selected="selected" value="0">Select Post</option>');
    $('#<%=DropDownList1.ClientID %>').change(function() {
    var country = $('#<%=DropDownList1.ClientID%>').val()
    $('#<%=DropDownList2.ClientID %>').removeAttr("disabled");
    $.ajax({
    type: "POST",
    url: "http://localhost:50384/update_add_staff.aspx/BindPosts",
    data: "{'country':'" + country + "'}",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function(msg) {
    var j = jQuery.parseJSON(msg.d);
    var options;
    for (var i = 0; i < j.length; i++) {
    options += '<option value="' + j[i].optionValue + '">' + j[i].optionDisplay + '</option>'
    }
    $('#<%=DropDownList2.ClientID %>').html(options)
    },
    error: function(data) {
    alert('Something Went Wrong')
    }
    });
    });
    $('#<%=DropDownList2.ClientID %>').append('<option selected="selected" value="0">Select Post</option>');
    $("#DropDownList2").children("option").is("selected").text() 
    $('#<%=DropDownList2.ClientID %>').change(function() {
    var stateid = $('#<%=DropDownList2.ClientID%>').val()
      var myVar =('#DropDownList2').find(':selected').text();
    $.ajax({
    type: "POST",
    url: "http://localhost:50384/update_add_staff.aspx/BindPosts",
    data: "{'state':'" + post_id + "'}",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function(msg) {
    var j = jQuery.parseJSON(msg.d);
    var options;
    for (var i = 0; i < j.length; i++) {
    options += '<option value="' + j[i].optionValue + '">' + j[i].optionDisplay + '</option>'
    }
    $('#<%=DropDownList2.ClientID %>').html(options)
    $("option:selected", myVar).text()
    },
    error: function(data) {
    alert('Something Went Wrong')
    }
    });
    })
    })
    </script>

In regards to my C# code:

 private void Bindcategorydown()
        {
            String strQuery = "SELECT [dept_no],[department_name] FROM [first].[dbo].[dept_add]";
            using (SqlConnection con = new SqlConnection(strcon))
            {
                using (SqlCommand cmd = new SqlCommand())
                {
                    cmd.CommandType = CommandType.Text;
                    cmd.CommandText = strQuery;
                    cmd.Connection = con;
                    con.Open();
                    DropDownList1.DataSource = cmd.ExecuteReader();
                    DropDownList1.DataTextField = "department_name";
                    DropDownList1.DataValueField = "dept_no";
                    DropDownList1.DataBind();
                    DropDownList1.Items.Insert(0, new ListItem("Select Department", "0"));
                    con.Close();
                }
            }
        }
        [WebMethod]
        public static string BindPosts(string country)
        {
            StringWriter builder = new StringWriter();
            String strQuery = "SELECT [post_id],[post_name] FROM [first].[dbo].[add_post] where group_id=@dept_no";
            DataSet ds = new DataSet();
            using (SqlConnection con = new SqlConnection(strcon))
            {
                using (SqlCommand cmd = new SqlCommand())
                {
                    cmd.CommandType = CommandType.Text;
                    cmd.CommandText = strQuery;
                    cmd.Parameters.AddWithValue("@dept_no", country);
                    cmd.Connection = con;
                    con.Open();
                    SqlDataAdapter da = new SqlDataAdapter(cmd);
                    da.Fill(ds);
                    con.Close();
                }
            }
            DataTable dt = ds.Tables[0];
            builder.WriteLine("[");
            if (dt.Rows.Count > 0)
            {
                builder.WriteLine("{\"optionDisplay\":\"Select Post\",");
                builder.WriteLine("\"optionValue\":\"0\"},");
                for (int i = 0; i <= dt.Rows.Count - 1; i++)
                {
                    builder.WriteLine("{\"optionDisplay\":\"" + dt.Rows[i]["post_name"] + "\",");
                    builder.WriteLine("\"optionValue\":\"" + dt.Rows[i]["post_id"] + "\"},");
                }
            }
            else
            {
                builder.WriteLine("{\"optionDisplay\":\"Select Post\",");
                builder.WriteLine("\"optionValue\":\"0\"},");
            }
            string returnjson = builder.ToString().Substring(0, builder.ToString().Length - 3);
            returnjson = returnjson + "]";
            return returnjson.Replace("\r", "").Replace("\n", "");
        }

For the update button, I utilized the following code:

cmd.Parameters.AddWithValue("@department", DropDownList2.SelectedItem.ToString());

Answer №1

cmd.Parameters.AddWithValue("@department", DropDownList2.SelectedItem.Text);

In case the issue continues, kindly provide us with the error stack trace.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Sending form data using Ajax

My concern is quite straightforward - I am using jquery and ajax to submit a form. When the button is clicked, the data gets sent to the database. The question is - if the user clicks the submit button twice, there will be two entries in the database. Ho ...

Ways to restrict a function to a single DOM element using either its id or class

This script is responsible for dynamically loading pages on my website. It works fine, except that it currently iterates over all anchor tags a on the site, whereas I want it to iterate only through my navigation menu. Here is the navigation menu: <div ...

Tips for fixing the issue "Uncaught SyntaxError: Unexpected token S in JSON at position 0"

After referencing sols of SO, I am still unable to solve the error. I have a file dashboard.html which contains search conditions. When clicked, it calls loadtable.js. This loadtable.js file uses search.php to retrieve rows from a table. However, encount ...

Is it possible to use both the .load function and fadeIn in jQuery simultaneously?

Currently, I am utilizing the .load method to bring in another page using jQuery. Below is the code snippet: $('#page1').click(function(){ $("#content").load("page1.html"); }); While this code works well, I am inte ...

Discovering the Desired Key within a JSON Structure

For my c# project, I am utilizing the Json.net Library. Within this library, I have a lengthy JSON object with multiple subfields. Here is an example of the structure: { "count": 10, "Foo1": [ { "id": "1", "name": "Name1" }, { ...

Nested for loops are utilized in order to extract names from a JSON array

I am faced with a challenge involving a container that contains rows with 4 columns each. My goal is to retrieve the title of each column using ajax from a json array by utilizing a for loop. Initially, I successfully achieved this for one row using a sing ...

jQuery AJAX call failing to return to page

Currently, my form is set up to upload multiple text fields and a file to a PHP script for saving. The script successfully saves the file and text fields to an SQL database. At the end of the PHP script, I have the following code snippet: ('state&apo ...

Using jQuery and AJAX to prevent the default behavior of a link, initiate an AJAX request, and then navigate to the link afterwards

Attempting a seemingly 'simple' task has turned into quite the challenge for me. My goal is to have a user click a link, prevent the default action, execute an AJAX function, and then proceed to follow that link. So far, my attempts have only re ...

Utilizing Coded UI to Extract and Input Data from CSV Files

Looking for a way to enhance my codedui test that involves reading values from an .csv file? Currently, I have this code snippet: [DataSource("Microsoft.VisualStudio.TestTools.DataSource.CSV", "|DataDirectory|\\testdata.csv", "testdata#csv", Dat ...

React: State does not properly update following AJAX request

I'm currently facing a challenge in my React project where I need to make two AJAX calls and update the UI based on the data received. Below is the implementation of my render method: render() { if (this.state.examsLoaded) { return ( ...

Issues with sending an AJAX POST request to a PHP script

Hello, I am trying to send a variable from an AJAX JavaScript file to a PHP file. Here is what I have done so far: var request = createRequest(); var deletenode = node.id; window.alert("nodeid=" + deletenode); var vars = "deletenode ...

Getting data sent via Ajax and jQuery through window.location.href in a new controller in CodeIgniter

How to retrieve ajax jquery data passed through window.location.href in a new controller using CodeIgniter? $(".x").on("click","a.p",function(){ productId = $(this).attr("productId"); alert("product ID : " + product ...

Issue with jQuery fadeIn() and fadeOut() functions on IE versions 7 and 8

I have a project in Ruby on Rails that showcases illustrations. The top of the page features category links that fade out the current illustrations, replace them with new content, and then fade back in. Currently, I am utilizing jQuery version 1.6.2 for t ...

Using Sinonjs fakeserver to handle numerous ajax requests

I utilize QUnit in combination with sinon. Is there a way to make sinon's fakeserver respond to multiple chained ajax calls triggered from the same method? module('demo', { beforeEach: function(){ this.server = sinon.fakeServer. ...

Hide the menu when tapping outside on a tablet device

Currently working with HTML, CSS, and JS (specifically Angular) I have a Header menu that contains dropdown sub-menus and sub-sub-menus in desktop view. On a PC, the sub-menus appear on hover and clicking on an entry redirects you somewhere. Clicking o ...

Unlocking the Magic of JSONP: A Comprehensive Guide

Currently attempting to utilize JSONP in order to work around Cross Domain challenges. I referenced this solution: Basic example of using .ajax() with JSONP? $.getJSON("http://example.com/something.json?callback=?", function(result){ //response data a ...

Sending checkbox value with jquery.ajax in Bootstrap modal: a step-by-step guide

Currently I am facing a challenge with a form that includes a checkbox on a webpage pop-up modal using flask/bootstrap/jquery. My goal is to submit the form without refreshing the page, which is why I'm utilizing jquery.ajax for this task. Despite the ...

Transfer information from python-cgi to AJAX

Currently, I am in the process of creating a UI version of the find command found in Linux. In this implementation, I receive the location and filename parameters for the find command through a CGI form that has been built using Python. When the user submi ...

Utilizing Ajax: Sending Customized Data to a Modal

Having never worked with jquery before, I struggled to find a solution for my specific case. On the cockpit.php page, I have a form that retrieves content from a mysql database. Currently, I am able to display this content in a div on the same cockpit.php ...

What is the best way to update HTML content using JSF reRender or Ajax load, and then rebind the updated DOM with AngularJS?

Let's analyze the following piece of code: <div id="dest"> <p>Original Content</p> <p>Some data</p> <ul> <li ng-repeat="i in items">{{i.name}}</li> </ul> </div> Alternatively, u ...