locked
Error Submitting data. RRS feed

  • Question

  • User1216627406 posted

    Hello experts,

    I can't seem to figure out what I am doing wrong.

    I am using json object and an ajax call to submit data to the database.

    When I try to submit the data, I got an error that there is an error submitting to the database.

    Any ideas what I could be doing wrong?

    Thanks in advance

        <script type="text/javascript">
            $(document).ready(function () {
                $(document).on("click", "#btnAdd", function () { //
                    var rowCount = $('.data-contact-person').length + 1;
                    var contactdiv = '<tr class="data-contact-person">' +
                        '<td><input type="text" name="sourcename' + rowCount + '" class="form-control sourcename01" /></td>' +
                        '<td><input type="text" name="sourceaddress' + rowCount + '" class="form-control sourceaddress01" /></td>' +
                        '<td><input type="text" name="sourceincome' + rowCount + '" class="form-control sourceincome01" /></td>' +
                        '<td><button type="button" id="btnAdd" class="btn btn-xs btn-primary classAdd">Add More</button>' +
                        '<button type="button" id="btnDelete1" class="deleteContact btn btn btn-danger btn-xs">Remove</button></td>' +
                        '</tr>';
                    $('#maintable').append(contactdiv); // Adding these controls to Main table class
                });
    
                $(document).on("click", "#btnAdd2", function () { //
                    var rowCount = $('.data-contact-person2').length + 1;
                    var contactdiv = '<tr class="data-contact-person2">' +
                        '<td><input type="text" name="spousename' + rowCount + '" class="form-control spousename01" /></td>' +
                        '<td><input type="text" name="spouseaddress' + rowCount + '" class="form-control spouseaddress01" /></td>' +
                        '<td><input type="text" name="spouseincome' + rowCount + '" class="form-control spouseincome01" /></td>' +
                        '<td><button type="button" id="btnAdd2" class="btn btn-xs btn-primary classAdd">Add More</button>' +
                        '<button type="button" id="btnDelete2" class="deleteContact btn btn btn-danger btn-xs">Add More</button></td>' +
                        '</tr>';
                    $('#maintable2').append(contactdiv); // Adding these controls to Main table class
                });
    
            $(document).on("click", ".deleteContact", function () {
                $(this).closest("tr").remove(); // closest used to remove the respective 'tr' in which I have my controls 
            });
    
            function getAllEmpData() {
                var data = [];
                $('tr.data-contact-person').each(function () {
                    var sname = $(this).find('.sourcename01').val();
                    var saddress = $(this).find('.sourceaddress01').val();
                    var sincome = $(this).find('.sourceincome01').val();
                    var spname = $(this).find('.spousename01').val();
                    var spaddress = $(this).find('.spouseaddress01').val();
                    var spincome = $(this).find('.spouseincome01').val();
                    var alldata = {
                        'mySource': sname,
                        'mySAddress': saddress,
                        'mySIncome': sincome,
                        'mySpouse': spname,
                        'mySPAddress': spaddress,
                        'mySPIncome': spincome
                    }
                    data.push(alldata);
                });
                console.log(data);
                return data;
            }
    
            $("#btnSubmit").click(function () {
                var data = JSON.stringify(getAllEmpData());
                //console.log(data);
                $.ajax({
                    url: 'closures.aspx/SaveData',
                    type: 'POST',
                    dataType: 'json',
                    contentType: 'application/json; charset=utf-8',
                    data: JSON.stringify({ 'empdata': data }),
                    success: function () {
                        alert("Data Added Successfully");
                    },
                    error: function () {
                        alert("Error while inserting data");
                    }
                });
            });
        });
    </script>
    
    
        <WebMethod()> _
        Public Shared Function SaveData(empdata As String) As String
            Dim serializedData = JsonConvert.DeserializeObject(Of List(Of Employee))(empdata)
            Using con = New SqlConnection(Constr)
                If con.State = ConnectionState.Closed Then
                    con.Open()
                End If
                For Each data As Employee In serializedData
                    Using cmd = New SqlCommand("INSERT INTO SourceDetails(sourcename, sourceaddress, sourceincome, createDate) VALUES(@sname, @saddress,@sincome,@CreatedDate)")
    
                        cmd.CommandType = CommandType.Text
                        cmd.Parameters.AddWithValue("@sname", data.mySpouse)
                        cmd.Parameters.AddWithValue("@saddress", data.mySAddress)
                        cmd.Parameters.AddWithValue("@sincome", data.mySIncome)
                        cmd.Parameters.AddWithValue("@CreatedDate", DateTime.Now)
                        cmd.Connection = con
                        cmd.ExecuteNonQuery()
                    End Using
                Next
                con.Close()
            End Using
            Return Nothing
        End Function

    Monday, March 6, 2017 3:04 AM

Answers

  • User-1838255255 posted

    Hi simflex,

    According to this error message, that's mean this request is failed. About how to find this error code, please try the following steps:

    1. Debugger your Ajax code, please check the parameters that you passed. Or other errors in JS.  

    2. Please add a break point in your webmethod, check it how to execute, which line code caused this error or else error show up.

    3. Please try the following code to get response message.

    error: function(xhr, status, error) {
        alert(xhr.responseText);
     }

    Best Regards,

    Eric Du

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, March 7, 2017 7:07 AM
  • User753101303 posted

    Hi,

    As reported earlier change the code to get more details.You could also use try/catch server side to log details. I suspect the issue is that as parameters are part of the loop you are adding them again and again cuasing an error (they should be added outside of the loop and just the value for thiose parameters should be defined in the loop).

    Perhaps not an issue but you should never have to explicitely deserialize or serialize data, ASP.NET does this for you as part of the ASP.NET infrastructure.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, March 7, 2017 7:55 AM

All replies

  • User527778624 posted

    Hi,

    Try updating your code like below:

    $("#btnSubmit").click(function () {
                var data = getAllEmpData();  //JSON.stringify(getAllEmpData());
                $.ajax({
                    url: 'closures.aspx/SaveData',
                    type: 'POST',
                    dataType: 'json',
                    //contentType: 'application/json; charset=utf-8',
                    data: JSON.stringify(data),
                    success: function () {
                        alert("Data Added Successfully");
                    },
                    error: function () {
                        alert("Error while inserting data");
                    }
                });
            });

    Monday, March 6, 2017 8:19 AM
  • User1216627406 posted

    Thank you for your response Raju.

    Still getting same error message though - "Error while inserting data"

    Monday, March 6, 2017 2:32 PM
  • User-1838255255 posted

    Hi simflex,

    According to this error message, that's mean this request is failed. About how to find this error code, please try the following steps:

    1. Debugger your Ajax code, please check the parameters that you passed. Or other errors in JS.  

    2. Please add a break point in your webmethod, check it how to execute, which line code caused this error or else error show up.

    3. Please try the following code to get response message.

    error: function(xhr, status, error) {
        alert(xhr.responseText);
     }

    Best Regards,

    Eric Du

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, March 7, 2017 7:07 AM
  • User753101303 posted

    Hi,

    As reported earlier change the code to get more details.You could also use try/catch server side to log details. I suspect the issue is that as parameters are part of the loop you are adding them again and again cuasing an error (they should be added outside of the loop and just the value for thiose parameters should be defined in the loop).

    Perhaps not an issue but you should never have to explicitely deserialize or serialize data, ASP.NET does this for you as part of the ASP.NET infrastructure.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, March 7, 2017 7:55 AM
  • User1216627406 posted

    Hi Eric and Patrice,

    This is weird.


    When I added the script debugger from Eric,

    I got the following error:

    "The parametized query \u0027(@sname nvarchar(4000), @saddress nvarchar(4000), @sincome nvarcha\u0027 expects parameter \u0027@sname\u0027, which was not supplied.

    Can someone please help make some sense of this for me please?

    Tuesday, March 7, 2017 3:42 PM
  • User1216627406 posted

    Thanks to both of you. it is working now.

    many, many thanks

    Tuesday, March 7, 2017 4:36 PM