locked
Having Problems with $.ajax Methods RRS feed

  • Question

  • User974500661 posted

    Hello, I found some great code to use cascade dropdown lists using JQuery and asp.net and it works well, however, when I edit it for my own use, I can't seem to use one of the Ajax methods successfully.

    All the data I want to populate in all 3 of my dropdowns is actually from the same table. I'm not using an integer ID value in the name value pairs of the dropdown lists and I'm just using the text values of the dropdown lists to pass in as parameters. Help appreciated.

    Here is the code I have so far for the first two dropdown lists. Country populates fine, but then once I select a Country, Region just stays greyed out and indicates "loading". Debug indicates that my call to web method PopulateRegion is never made. Not sure why....

    Imports System
    Imports System.Collections.Generic
    Imports System.Web
    Imports System.Web.UI
    Imports System.Web.UI.WebControls
    Imports System.Configuration
    Imports System.Data.SqlClient
    Imports System.Data
    
    Public Class RegionSearch
        Inherits System.Web.UI.Page
    
        Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
            If Not IsPostBack Then
                Me.PopulateCountry()
            End If
        End Sub
    
        Private Sub PopulateCountry()
            Dim strConnString As String = ConfigurationManager.ConnectionStrings("AdminConnectionString").ConnectionString
            Dim strQuery As String = "select Distinct Country from tblWines"
            Dim con As SqlConnection = New SqlConnection(strConnString)
            Dim cmd As SqlCommand = New SqlCommand
            cmd.CommandType = CommandType.Text
            cmd.CommandText = strQuery
            cmd.Connection = con
            con.Open()
            ddlCountry.DataSource = cmd.ExecuteReader
            ddlCountry.DataTextField = "Country"
            ddlCountry.DataValueField = "Country"
            ddlCountry.DataBind()
            con.Close()
        End Sub
    
        <System.Web.Services.WebMethod()> _
        Public Shared Function PopulateRegion(ByVal country As String) As ArrayList
            Dim list As ArrayList = New ArrayList
            Dim strConnString As String = ConfigurationManager.ConnectionStrings("AdminConnectionString").ConnectionString
            Dim strQuery As String = "select Distinct Region from tblWines where Country=@country"
            Dim con As SqlConnection = New SqlConnection(strConnString)
            Dim cmd As SqlCommand = New SqlCommand
            cmd.CommandType = CommandType.Text
            cmd.Parameters.AddWithValue("@country", country)
            cmd.CommandText = strQuery
            cmd.Connection = con
            con.Open()
            Dim sdr As SqlDataReader = cmd.ExecuteReader
            While sdr.Read
                list.Add(New ListItem(sdr("Region").ToString, sdr("Region").ToString))
            End While
            con.Close()
            Return list
        End Function
     Private Sub PopulateDropDownList(ByVal list As ArrayList, ByVal ddl As DropDownList)
            ddl.DataSource = list
            ddl.DataTextField = "Text"
            ddl.DataValueField = "Value"
            ddl.DataBind()
        End Sub

    The JavaScript in my .ASPX:

    <script src="Scripts/jquery-1.10.2.min.js" type="text/javascript"></script>
        <script type = "text/javascript">
            var pageUrl = '<%=ResolveUrl("~/RegionSearch.aspx")%>'
            function PopulateCountry() {
                $("#<%=ddlRegion.ClientID%>").attr("disabled", "disabled");
                $("#<%=ddlSubregion.ClientID%>").attr("disabled", "disabled");
                if ($('#<%=ddlCountry.ClientID%>').val() == "0")
                {
                           
                    $('#<%=ddlRegion.ClientID %>').empty().append('<option selected="selected" value="0">Please select</option>');
                    $('#<%=ddlSubregion.ClientID %>').empty().append('<option selected="selected" value="0">Please select</option>');
                }
                else {
                    $('#<%=ddlRegion.ClientID %>').empty().append('<option selected="selected" value="0">Loading...</option>');
                    $.ajax({
                        type: "POST",
                        url: pageUrl + '/PopulateRegion',
                        data: '{country: ' + $('#<%=ddlCountry.ClientID%>').val() + '}',
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        success: OnRegionPopulated,
                        failure: function(response) {
                            alert(response.d);
                            
                        }
                         
                    });
    
                  }
                
            }
     function OnRegionPopulated(response) {
                PopulateControl(response.d, $("#<%=ddlRegion.ClientID %>"));
               
            }
     function PopulateControl(list, control) {
                if (list.length > 0) {
                    control.removeAttr("disabled");
                    control.empty().append('<option selected="selected" value="0">Please select</option>');
                    $.each(list, function() {
                        control.append($("<option></option>").val(this['Value']).html(this['Text']));
                    });
                }
                else {
                    control.empty().append('<option selected="selected" value="0">Not available<option>');
                }
            }
    Country:<asp:DropDownList ID="ddlCountry" runat="server" AppendDataBoundItems="true"
                     onchange = "PopulateCountry();">
            <asp:ListItem Text = "Please select" Value = "0"></asp:ListItem>                 
        </asp:DropDownList>
        <br /><br />
        Region:<asp:DropDownList ID="ddlRegion" runat="server"
                     onchange = "PopulateSubregion();">
            <asp:ListItem Text = "Please select" Value = "0"></asp:ListItem>                 
        </asp:DropDownList>


    Thank you!

    Saturday, October 3, 2015 8:37 PM

Answers

  • User475983607 posted

    But on the code I'm trying to use for my needs, I don't get anything back for console.log(msg); and the network log looks like this:

    /RegionSearch.aspx/PopulateRegion HTTP POST 500 application/json

    and it looks like that response is an internal server error. 

    A 500 error is a server error.  A common cause of a 500 are invalid parameters.   Have you verified the POST parameters are what you expect and are formatted correctly?

    data: '{country: ' + $('#<%=ddlCountry.ClientID%>').val() + '}',

    Don' t you want this format?

    '{"country": ' + '"' + $('#<%=ddlCountry.ClientID%>').val() + '"}'

    Have you tried stepping through the web method?

    Maybe add try catches to the web methods as well.

    Troubleshooting is a big part of programming.  You need to learn how to systematically test code.  

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, October 6, 2015 6:33 AM

All replies

  • User475983607 posted

    Here is the code I have so far for the first two dropdown lists. Country populates fine, but then once I select a Country, Region just stays greyed out and indicates "loading". Debug indicates that my call to web method PopulateRegion is never made. Not sure why....

    Use the developer tools (F12) and console.log() to follow the logic flow, view the state of objects and HTTP requests, and see any run-time JavaScript errors.

    Since the ddl is displays Loading... We can assume the code makes it that far.  The next thing is the ajax call.  Do you see the HTTP request in the developer tool's network tab?  Are there any error in the console or network tab?

    Let's assume we get pst the AJAX request.  What's the result of the request?

    Place console.log() here...

    function OnRegionPopulated(response) {
      console.log(response);
       PopulateControl(response.d, $("#<%=ddlRegion.ClientID %>"));
    }

    Open the console tab.  Is the response what you expect?

    What about the PopulateControl method, is it working as expected?

    function PopulateControl(list, control) {
      console.log(list.length);
                if (list.length > 0) {
                    control.removeAttr("disabled");
    
       console.log(control);
    
                    control.empty().append('<option selected="selected" value="0">Please select</option>');
        console.log(control);
                    $.each(list, function() {
                        control.append($("<option></option>").val(this['Value']).html(this['Text']));
                    });
                }
                else {
                    control.empty().append('<option selected="selected" value="0">Not available<option>');
                }
        console.log(control);
            }

    Debugging is an art.  It's the process of elimination, testing each component, and verifying the state of objects during run-time. 

    Sunday, October 4, 2015 11:17 AM
  • User974500661 posted

    Thank you. I agree. Found some sample code on how to grab some values after the ajax call. I'm lucky to have a working example of the code, and then the version of the code I'm trying to use for my own needs. I performed the F12 and console.log() in each so I could evaluate. Here is what I found so far:

    right after the .ajax call, I called cosole.log() to evaluate what was going on by setting var request =

       var request = $.ajax({
                        type: "POST",
                        url: pageUrl + '/PopulateRegion',
                        data: '{country: ' + $('#<%=ddlCountry.ClientID%>').val() + '}',
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        success: OnRegionPopulated,
                        failure: function(response) {
                            alert(response.d);
                            
                        }
                         
                    });
                    request.done(function (msg) {
                        console.log(msg);
                    });

    On my example of the code that works, I get the following in the F12 console:

    [object Object]{d: Array[2]}

    and network summary info looks like this: /VB.aspx/PopulateCountries HTTP POST 200 application/json

    But on the code I'm trying to use for my needs, I don't get anything back for console.log(msg); and the network log looks like this:

    /RegionSearch.aspx/PopulateRegion HTTP POST 500 application/json

    and it looks like that response is an internal server error. 

    Any help/clues appreciated. Thank you.

    Monday, October 5, 2015 9:50 PM
  • User475983607 posted

    But on the code I'm trying to use for my needs, I don't get anything back for console.log(msg); and the network log looks like this:

    /RegionSearch.aspx/PopulateRegion HTTP POST 500 application/json

    and it looks like that response is an internal server error. 

    A 500 error is a server error.  A common cause of a 500 are invalid parameters.   Have you verified the POST parameters are what you expect and are formatted correctly?

    data: '{country: ' + $('#<%=ddlCountry.ClientID%>').val() + '}',

    Don' t you want this format?

    '{"country": ' + '"' + $('#<%=ddlCountry.ClientID%>').val() + '"}'

    Have you tried stepping through the web method?

    Maybe add try catches to the web methods as well.

    Troubleshooting is a big part of programming.  You need to learn how to systematically test code.  

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, October 6, 2015 6:33 AM
  • User974500661 posted

    Thank you very much. You are exactly right and I thank you for coaching me on the debug aspects. This exchange has been very helpful. I really like the capabilities of console.log() and the F12 tools.

    I placed a try catch in the PopulateCountries web method as you suggested, but it never made it to that point. Good catch on the syntax regarding the country parameter. The sample code passed an number ID as a parameter, but I am using text.

    That is exactly what the issue was and it is working now!

    Thanks again.

    Tuesday, October 6, 2015 9:29 AM