locked
How do i fix the Ajax insert error on insert on modal? RRS feed

  • Question

  • User-2074858223 posted

    Tried to figure out why the insert shows error " undefined " the Ajax supposed to insert username, postid and icon selected into database, the modal popup is working but cant insert.

    see codes

    <div>
        <asp:DataList ID="Getpost" runat="server" DataKeyName="Id" Font-Bold="True" Width="100%">
            <ItemTemplate>
                <div class="well col-lg-6">
                    <asp:Label ID="Label1" Text='<%# Eval("UserName") %>' runat="server" />
                    <div class="" style="margin-top: 0; margin-left: 9px; margin-bottom: 8px">
                        <asp:Label ID="lblpost" runat="server" Text='<%# Eval("ContentPost").ToString().Length >180 ? Eval("ContentPost").ToString().Substring(0,180)+"...(Read More)" : Eval("ContentPost").ToString()%>'
                            Font-Bold="False" Font-Strikeout="False" ForeColor="#333333" CssClass="" Font-Names="Arial"
                            Font-Size="" />
                    </div>
                    <asp:Label ID="lbCOMlId" Text='<%#Eval("ID") %>' CssClass="" runat="server" Font-Size="0px"
                        Visible="False" />
                    <asp:Label ID="lbCOMlId2" Text='<%#Eval("ID") %>' CssClass="" runat="server" />
                    <div class="clearfix">
                    </div>
                    <asp:LinkButton ID="btnPick" Text="" runat="server">
                        <asp:Label ID="lblpickdefaultshow" runat="server" Text="" CssClass=" fa fa-shopping-cart"></asp:Label>
                        <asp:Label ID="Label6" runat="server" Text="Pick"></asp:Label>
                    </asp:LinkButton>
                </div>
            </ItemTemplate>
        </asp:DataList>
        <asp:HiddenField ID="hfUserName" runat="server" />
        <asp:HiddenField ID="hfPostId" runat="server" />
        <br />
        <div class="modal fade" id="pickermodal" tabindex="-1" role="dialog" aria-labelledby="pickerModalLabel"
            aria-hidden="true">
            <div class="">
                <div class="modal-dialog">
                    <div class="modal-content">
                        <div class="modal-header">
                            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                <span aria-hidden="true">×</span></button>
                            <h4 class="modal-title">
                                Pick Item Icons</h4>
                        </div>
                        <div class="modal-body">
                            ....... <span style="margin-right: 29px">
                                <asp:LinkButton ID="btnpickbook" Text="" runat="server">
                                    <asp:Label ID="Label59" runat="server" Text="" Font-Size="42px" CssClass="fa fa-book"></asp:Label>
                                </asp:LinkButton>
                                <a href="#" id=""></a></span><span style="margin-right: 29px"><a href="#" id="btnpickcup">
                                    <asp:Label ID="Label7" runat="server" Text="" Font-Size="42px" CssClass="fa fa-coffee"
                                        ForeColor="Red"></asp:Label>
                                </a></span><span style="margin-right: 29px"><a href="#" id="btnpen">
                                    <asp:Label ID="Label8" runat="server" Text="" Font-Size="42px" CssClass="fa fa-pencil"></asp:Label>
                                </a></span>
                        </div>
                        <div class="modal-footer">
                        </div>
                    </div>
                    <!-- /.modal-content -->
                </div>
                <!-- /.modal-dialog -->
            </div>
            <!-- /.modal -->
        </div>
    </div>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <script type="text/javascript" src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>
    <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" />
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" />
    <script type='text/javascript'>
        $(function () {
            var lblPick;
            $('[id*=btnPick]').on('click', function () {
                lblPick = $(this).closest('tr').find('[id*=lblpickdefaultshow]');
                var username = $(this).closest('tr').find('[id*=Label1]').text();
                var postId = "106";
                $('[id*=hfUserName]').val(username);
                $('[id*=hfPostId]').val(postId);
                $('[id*=pickermodal]').modal('show');
                return false;
            });
     
            $('[id*=pickermodal] a').click(function () {
                var icon = '';
                var userName = $('[id*=hfUserName]').val();
                var postId = $('[id*=hfPostId]').val();
                if ($(this).find('[id*=Label59]').length > 0) {
                    icon = 'fa fa-book';
                }
                else if ($(this).find('[id*=Label7]').length > 0) {
                    icon = 'fa fa-coffee';
                }
                else if ($(this).find('[id*=Label8]').length > 0) {
                    icon = 'fa fa-pencil';
                }
                $.ajax({
                    type: "POST",
                    url: "CS.aspx/INSERTUSERSTATUS",
                    data: '{icon:"' + icon + '",userName:"' + userName + '",postId:"' + postId + '"}',
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (response) {
                        $('#pickermodal').modal('hide');
                        $('[id*=hfUserName]').val('');
                        $('[id*=hfPostId]').val('');
                        $(lblPick).attr('class', icon)
                    },
                    failure: function (response) {
                        alert(response.d);
                    },
                    error: function (response) {
                        alert(response.d);
                    }
                });
                return false;
            });
        });
    </script>
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            DataTable dt = new DataTable();
            dt.Columns.AddRange(new DataColumn[] { new DataColumn("Id"), new DataColumn("UserName"), new DataColumn("ContentPost") });
            dt.Rows.Add(1, "mic44", "Post 1");
            dt.Rows.Add(2, "may88", "Post 2");
            dt.Rows.Add(3, "Stak55", "Post 3");
            dt.Rows.Add(4, "ston55", "Post 4");
            Getpost.DataSource = dt;
            Getpost.DataBind();
        }
    }
     
    [WebMethod]
    public static string INSERTUSERSTATUS(string userName, string icon, string postId)
    {
        string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
        using (SqlConnection con = new SqlConnection(constr))
        {
            using (SqlCommand cmd = new SqlCommand("INSERT INTO [UserPICKS](UserName,statuscount,Iconbook,IconCup,IconPen,PostId) VALUES(@UserName,@statuscount,@Iconbook,@IconCup,@IconPen,@PostId)"))
            {
                cmd.Connection = con;
                cmd.CommandType = CommandType.Text;
                cmd.Parameters.AddWithValue("@UserName", userName);
                cmd.Parameters.AddWithValue("@statuscount", "1");
                if (icon.ToLower() == "fa fa-book")
                {
                    cmd.Parameters.AddWithValue("@Iconbook", "book");
                }
                if (icon.ToLower() == "fa fa-coffee")
                {
                    cmd.Parameters.AddWithValue("@IconCup", "cup");
                }
                if (icon.ToLower() == "fa fa-pencil")
                {
                    cmd.Parameters.AddWithValue("@IconPen", "pen");
                }
                cmd.Parameters.AddWithValue("@PostId", postId);
                con.Open();
                cmd.ExecuteNonQuery();
                con.Close();
            }
        }
        return "posted";
    }

    Monday, March 5, 2018 5:39 PM

Answers

  • User-1838255255 posted

    Hi micah2012,

    According to your description and code, i checked your code, i guess the icon.ToLower value equal to "fa fa-book", so it doesn't enter the second 'if conditional', the IconCup value is null, so caused this issue. I suggest you could try this: 

     if (icon.ToLower() == "fa fa-book")
                {
                    cmd.Parameters.AddWithValue("@Iconbook", "book");
                    cmd.Parameters.AddWithValue("@IconCup", "");
                    cmd.Parameters.AddWithValue("@IconPen", "");
    
                }
                if (icon.ToLower() == "fa fa-coffee")
                {
                    cmd.Parameters.AddWithValue("@Iconbook", "");
                    cmd.Parameters.AddWithValue("@IconCup", "cup");
                    cmd.Parameters.AddWithValue("@IconPen", "");
                }
                if (icon.ToLower() == "fa fa-pencil")
                {
                    cmd.Parameters.AddWithValue("@Iconbook", "");
                    cmd.Parameters.AddWithValue("@IconCup", "");
                    cmd.Parameters.AddWithValue("@IconPen", "pen");
                }

    Best Regards,

    Eric Du 

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, March 6, 2018 2:53 AM

All replies

  • User475983607 posted

    The code base is far too sloppy to make a guess.  undefined is a JavaScript type that means a variable has not been assigned a value.  Generally you can click the undefined error in dev tools to see the line of code that caused the error.  I suggest that you set a breakpoint in dev tools and single-step through the JavaScript to find the bugs.  Also make use of dev tools to investigate the DOM elements and make sure the jQuery selectors are correct.

    Once you get the JavaScript working, you'll might need to fix the Web Method as there are more script parameters then populated parameters.  Unless you are allowing null.

    Monday, March 5, 2018 7:18 PM
  • User-2074858223 posted

    i debugged it and got this error message

    {"Must declare the scalar variable \"@IconCup\"."}
     
    
    
    System.Data.SqlClient.SqlException was unhandled by user code
      HResult=-2146232060
      Message=Must declare the scalar variable "@IconCup".
      Source=.Net SqlClient Data Provider
      ErrorCode=-2146232060
      Class=15
      LineNumber=1
      Number=137
      Procedure=""
      Server=.
      State=2
      StackTrace:
           at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
           at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
           at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
           at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
           at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)
           at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, SqlDataReader ds)
           at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite)
           at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite)
           at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
           at CS.INSERTUSERSTATUS(String userName, String icon, String postId) in c:\Documents\ PROJ\CS.aspx.cs:line 74
      InnerException:

    Tuesday, March 6, 2018 12:35 AM
  • User409696431 posted

    Debug to see if this "if" condition is entered.  If not, @IconCup won't be declared.

     if (icon.ToLower() == "fa fa-coffee")
                {
                    cmd.Parameters.AddWithValue("@IconCup", "cup");
                }
    

    Tuesday, March 6, 2018 2:19 AM
  • User-1838255255 posted

    Hi micah2012,

    According to your description and code, i checked your code, i guess the icon.ToLower value equal to "fa fa-book", so it doesn't enter the second 'if conditional', the IconCup value is null, so caused this issue. I suggest you could try this: 

     if (icon.ToLower() == "fa fa-book")
                {
                    cmd.Parameters.AddWithValue("@Iconbook", "book");
                    cmd.Parameters.AddWithValue("@IconCup", "");
                    cmd.Parameters.AddWithValue("@IconPen", "");
    
                }
                if (icon.ToLower() == "fa fa-coffee")
                {
                    cmd.Parameters.AddWithValue("@Iconbook", "");
                    cmd.Parameters.AddWithValue("@IconCup", "cup");
                    cmd.Parameters.AddWithValue("@IconPen", "");
                }
                if (icon.ToLower() == "fa fa-pencil")
                {
                    cmd.Parameters.AddWithValue("@Iconbook", "");
                    cmd.Parameters.AddWithValue("@IconCup", "");
                    cmd.Parameters.AddWithValue("@IconPen", "pen");
                }

    Best Regards,

    Eric Du 

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, March 6, 2018 2:53 AM