locked
How to show Alert message based on SP return val in $.ajax (post method RRS feed

  • Question

  • User-582711651 posted
    Hi, 
     
    I want to show the Alert message based on the Return value from Codebehind after the execution of SP,
    Please ref my code
    
        <script type="text/javascript" src="http://cdn.jsdelivr.net/json2/0.1/json2.js"></script>
        <script type="text/javascript">
                     function db_post() {
                     var f_db = {};
                     var recidx =  $('#<%=lbl_rowid.ClientID%>').text();
                     f_db.recid =  $.trim(recidx);
                     var trkidx =  $('#<%=lbl_trckingid.ClientID%>').text();
                     f_db.trkid =  $.trim(trkidx);
                     f_db.recvdt = $('#<%=txt_PostCouriReceivedOn.ClientID%>').val();
                     f_db.recvby = $('#<%=txt_DocReceivedByName.ClientID%>').val().toUpperCase();
                     f_db.recvph = $('#<%=txt_ReceivedPersonMobPH.ClientID%>').val();
                     f_db.remarks = $('#<%=txt_GeneralRemarks.ClientID%>').val().toUpperCase();
                     f_db.usrid = '<%= Session("ICT_Em_Code") %>';
                     f_db.ipadr = '<%= Session("ICT_IPADDR") %>';
                $.ajax({
                    type: "POST",
                    url: "DocAck.aspx/Doc_ackwd",
                    data: '{f_db: ' + JSON.stringify(f_db) + '}',
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (response) {
                      // Here I want to show the Alert message 
                        if (response.d) ==1 {
                        alert("Data updated successfully!");
                       }
                      else if (response.d)==2 {
                        alert("Sorry, data already updated !");
                      }
    
                    },
                    error: function (data, ex) {
                        alert("Sorry there is err. " + data + " Ex: " + ex);
                       
                    }
                    
                });
             }
        </script>
    My VB Code
    
          <WebMethod()>
        <ScriptMethod()>
        Public Shared Function Doc_ackwd(f_db As f_db) As f_db
            Dim DCStr As String = ConfigurationManager.ConnectionStrings("ConStr").ConnectionString
            Dim selectSQL As String
            Dim sCon As New SqlConnection(DCStr)
            Dim sCmd As New SqlCommand(selectSQL, sCon)
            Dim param As SqlParameter
            Dim dtadp As New SqlDataAdapter(sCmd)
            Dim dtset As New DataSet
            Try
                sCon.Open()
                sCmd.CommandType = CommandType.StoredProcedure
                sCmd.CommandText = "USP_AckwdByHO_Txn"
                sCmd.Parameters.Clear()
                sCmd.Parameters.Add(New SqlParameter("@i_SP_AttributeId", SqlDbType.Int)).Value = 1
                sCmd.Parameters.Add(New SqlParameter("@i_LoginUserECode", SqlDbType.VarChar)).Value = f_db.usrid
                sCmd.Parameters.Add(New SqlParameter("@i_ParentRecordID", SqlDbType.Int)).Value = f_db.recid
                sCmd.Parameters.Add(New SqlParameter("@i_TrackingId", SqlDbType.VarChar)).Value = f_db.trkid
                sCmd.Parameters.Add(New SqlParameter("@i_PostCourierDate", SqlDbType.Date)).Value = CDate(f_db.recvdt)
                sCmd.Parameters.Add(New SqlParameter("@i_PostCourierReceiverName", SqlDbType.VarChar)).Value = f_db.recvby
                sCmd.Parameters.Add(New SqlParameter("@i_PostCourierReceiverMobNo", SqlDbType.VarChar)).Value = f_db.recvph
                sCmd.Parameters.Add(New SqlParameter("@i_Remarks", SqlDbType.VarChar)).Value = f_db.remarks
                sCmd.Parameters.Add(New SqlParameter("@i_RecordUpdtUser_IPMACAddr", SqlDbType.VarChar)).Value = f_db.ipadr
                param = New SqlParameter("@o_ErrorStatus", SqlDbType.Int) With {
                    .Direction = ParameterDirection.Output
                }
                sCmd.Parameters.Add(param)
                dtadp.Fill(dtset)
                If sCmd.Parameters("@o_ErrorStatus").Value = 1 Then
               ' Data Saved 
                else If sCmd.Parameters("@o_ErrorStatus").Value = 2 Then
               ' Data already updated
                else sCmd.Parameters("@o_ErrorStatus").Value = 9 Then
               ' Data transport err.
                End If
    
            Catch ex As Exception
                else sCmd.Parameters("@o_ErrorStatus").Value = 9 Then
               ' Data transport err.
            Finally
                sCon.Close()
            End Try
            Return f_db
        End Function
    Thanks in advance. 

    Tuesday, October 20, 2020 3:12 PM

All replies

  • User475983607 posted

    The problem is very obvious. 

    The Web Method returns an f_db type but the AJAX success handler expects a scalar value.  It looks like you might be changing the design but did not complete the work?  

    Tuesday, October 20, 2020 3:33 PM
  • User-582711651 posted

    @ mgebhard

    Hi, Im very beginner on this Ajax data post, I already completed data updating well, now I gonna improve little for example if data already exists want to show message, this is my requirment, with examples

    Thanks in advance. 

    Tuesday, October 20, 2020 3:52 PM
  • User475983607 posted

    ayyappan.CNN

    Hi, Im very beginner on this Ajax data post, I already completed data updating well, now I gonna improve little for example if data already exists want to show message, this is my requirment, with examples

    Thanks in advance. 

    For the second time.  The Web Method returns an f_db type not an integer the AJAX success handler expects.  The community has no idea how your code is intended to work.  However, the problem does not appear to be with the AJAX.  It seems as though you do not understand ADO.NET or there might be a problem with the stored procedure.

    Can you explain how your design is supposed to work?  Do you want to return an integer from the Web Method?  Have you verified the stored procedure works as expected?  Is there some reason why you are unable to perform basic debugging? 

    Tuesday, October 20, 2020 4:27 PM
  • User-474980206 posted

    once you make the web method and ajax call agree on the response data, you still need to fix the post data. your post data is invalid json, so the ajax call should just error. 

                   data: '{f_db: ' + JSON.stringify(f_db) + '}',

    should be:

                   data: '{"f_db": ' + JSON.stringify(f_db) + '}',
    

    or the much more readable:

                   data: JSON.stringify({f_db: f_db}),

    Tuesday, October 20, 2020 5:45 PM
  • User-582711651 posted

    HI, 

    01. Can you explain how your design is supposed to work? 

    ref my code: https://drive.google.com/drive/u/4/folders/1UlnK55cgpidmcV7OKGuw9jtOVaqH2TVb

    02. Do you want to return an integer from the Web Method?

    No, not compulsory, the string can be passed.

    03. Have you verified the stored procedure works as expected?

    Yes, I tried and it works, ref my above link

    04. Is there some reason why you are unable to perform basic debugging? 

    I'm new to this Ajax data post, I don't have much knowledge on this. but using Vb code I have done a lot successfully. 

    Thanks,

    Tuesday, October 20, 2020 6:15 PM
  • User475983607 posted

    ayyappan.CNN

    01. Can you explain how your design is supposed to work? 

    ref my code: https://drive.google.com/drive/u/4/folders/1UlnK55cgpidmcV7OKGuw9jtOVaqH2TVb

    You did not answer the question.  You have to understand your code is incomplete.  I have no idea how the code is intended to work.  

    ayyappan.CNN

    02. Do you want to return an integer from the Web Method?

    No, not compulsory, the string can be passed.

    Then why are you still returning the type f_db after being notified of this bug?  The first step is setting the return value to the expected type.  

    Public Shared Function Doc_ackwd(f_db As f_db) As Integer

    or 

    Public Shared Function Doc_ackwd(f_db As f_db) As string

    This will cause a compiler error that you need to fix.  The next step is fixing the body of the Web Method to return the expected Integer or string.  For the time being, you can hard code an Integer or a string to verify the AJAX success handler.  But you have a lot of design work to do in the VB.NET code.

    ayyappan.CNN

    03. Have you verified the stored procedure works as expected?

    Yes, I tried and it works, ref my above link

    The stored procedure is bad.  You pass a parameter, @i_SP_AttributeId, that determines if the INSERT is performed.  Why call the procedure if you know the value is 1?   Makes no sense.  There a return parameter, @o_ErrorStatus, which can be 0,1, or 9 but your code is looking for a 2.  Where does the magic 2 come form?  The proc starts a transaction but there is no reason to have a transaction.  There's only one INSERT.  Why is the transaction needed?   

    I would fail the procedure in a code review, suggest a basic INSERT, and remove all the unnecessary code.

    CREATE PROCEDURE [dbo].[Dbusp_docu] (
        @i_RecId                    INT = 0, 
        @i_PostCourierDate          VARCHAR(15) = NULL, 
        @i_PostCourierReceiverName  VARCHAR(100) = NULL, 
        @i_PostCourierReceiverMobNo VARCHAR(15) = NULL, 
        @i_Remarks                  VARCHAR(100) = NULL) 
    AS 
    
    BEGIN 
    
        INSERT INTO [dbo].[emptrans] 
                    ([trid], 
                     [postcourierdate], 
                     [postcourierreceivername], 
                     [postcourierreceivermobno], 
                     [remarks], 
                     [createdon], 
                     [isactive]) 
        VALUES      (@i_RecId, 
                     @i_PostCourierDate, 
                     @i_PostCourierReceiverName, 
                     @i_PostCourierReceiverMobNo, 
                     @i_Remarks, 
                     Getdate(), 
                     1) 
    
    END 
    
    go 

    ayyappan.CNN

    04. Is there some reason why you are unable to perform basic debugging? 

    I'm new to this Ajax data post, I don't have much knowledge on this. but using Vb code I have done a lot successfully. 

    As far as I can tell, you are having trouble with basic VB.NET, ADO.NET, and T-SQL.  The ADO.NET fills a dataset but the procedure does not return a dataset.  You should execute an ExecuteNonQuery() which returns the number of records affected.  That will tell you if the INSERT succeeded or not. Read the docs...

    From my perspective your code is not ready for posting on the forum or a code review.   The design is clearly unfinished and there are problems with the return values.   If this were a code review I would recommend paying better attention to details and take some time to review the code.

    Tuesday, October 20, 2020 7:39 PM
  • User-582711651 posted

    Hi mgebhard

    Sorry for the delayed reply, I shared my similar code, due to urgent I missed out some stuff, once again I say sorry.

    After the great struggle, I have solved my problem, it works well. 

    ref my Code VB code: 

      Public Shared Function dack(f_db As f_db) As String
            Dim DCStr As String = ConfigurationManager.ConnectionStrings("CS").ConnectionString
            Dim selectSQL As String
            Dim sCon As New SqlConnection(DCStr)
            Dim sCmd As New SqlCommand(selectSQL, sCon)
            Dim param As SqlParameter
            Dim dtadp As New SqlDataAdapter(sCmd)
            Dim dtset As New DataSet
            Dim f_retval As String = ""
            Try
                sCon.Open()
                sCmd.CommandType = CommandType.StoredProcedure
                sCmd.CommandText = "USP_DocAck"
                sCmd.Parameters.Clear()
                sCmd.Parameters.Add(New SqlParameter("@i_SP_AttributeId", SqlDbType.Int)).Value = 1
                sCmd.Parameters.Add(New SqlParameter("@i_LoginUserECode", SqlDbType.VarChar)).Value = f_db.usrid
                sCmd.Parameters.Add(New SqlParameter("@i_ParentRecordID", SqlDbType.Int)).Value = f_db.recid
                sCmd.Parameters.Add(New SqlParameter("@i_TrackingId", SqlDbType.VarChar)).Value = f_db.trkid
                sCmd.Parameters.Add(New SqlParameter("@i_PostCourierDate", SqlDbType.Date)).Value = CDate(f_db.recvdt)
                sCmd.Parameters.Add(New SqlParameter("@i_PostCourierReceiverName", SqlDbType.VarChar)).Value = f_db.recvby
                sCmd.Parameters.Add(New SqlParameter("@i_PostCourierReceiverMobNo", SqlDbType.VarChar)).Value = f_db.recvph
                sCmd.Parameters.Add(New SqlParameter("@i_Remarks", SqlDbType.VarChar)).Value = f_db.remarks
                sCmd.Parameters.Add(New SqlParameter("@i_RecordUpdtUser_IPMACAddr", SqlDbType.VarChar)).Value = f_db.ipadr
                param = New SqlParameter("@o_ErrorStatus", SqlDbType.Int) With {
                    .Direction = ParameterDirection.Output
                }
                sCmd.Parameters.Add(param)
                dtadp.Fill(dtset)
                If sCmd.Parameters("@o_ErrorStatus").Value = 1 Then
                    f_retval = "1"
                ElseIf sCmd.Parameters("@o_ErrorStatus").Value = 2 Then
                    f_retval = "2"
                End If
            Catch ex As Exception
                f_retval = "9"
            Finally
                sCon.Close()
            End Try
            Return f_retval
        End Function

    This is my Jq script

     <script type="text/javascript" src="http://cdn.jsdelivr.net/json2/0.1/json2.js"></script>
        <script type="text/javascript">
                     function db_post() {
                     var f_db = {};
                     var recidx =  $('#<%=lbl_rowid.ClientID%>').text();
                     f_db.recid =  $.trim(recidx);
                     var trkidx =  $('#<%=lbl_trckingid.ClientID%>').text();
                     f_db.trkid =  $.trim(trkidx);
                     f_db.recvdt = $('#<%=txt_PostCouriReceivedOn.ClientID%>').val();
                     f_db.recvby = $('#<%=txt_DocReceivedByName.ClientID%>').val().toUpperCase();
                     f_db.recvph = $('#<%=txt_ReceivedPersonMobPH.ClientID%>').val();
                     f_db.remarks = $('#<%=txt_GeneralRemarks.ClientID%>').val().toUpperCase();
                     f_db.usrid = '<%= Session("ICT_Em_Code") %>';
                     f_db.ipadr = '<%= Session("ICT_IPADDR") %>';
                $.ajax({
                    type: "POST",
                    url: "Ack.aspx/dack",
                    data: '{f_db: ' + JSON.stringify(f_db) + '}',
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (response) {
                       var result = response.d;
                       if (result == '1') {
                        alert("The document acknowledgement information has been updated successfully!");
                        $("#<%=txt_GeneralRemarks.ClientID %>").val("");
                        $(".modal-backdrop").remove();
                        $("#Popu_HOApproval").modal('hide');
                        disbl_rbt();
                        }
                        else if (result == '2') {
                        alert("Sorry, This transaction already exists, due to this unable to save your data!");
                        }
                        else{
                        alert("Sorry! There is a Data Transmission erro, please contact IT Admin!");
                        }
                    },
                    error: function (data, ex) {
                        alert("Sorry there is err. " + data + " Ex: " + ex);
                        $(".modal-backdrop").remove();
                        $("#Popu_HOApproval").modal('show');
                    }
                    
                });

    Kindly check my code and share your views, changes if required. 

    Wednesday, October 21, 2020 7:26 PM