Can someone please tell me why I am getting "error while inserting data" error message

Hi mates,

I have written an app built around JSON object and ajax though with PHP.

This one is using WebMethod() with asp.net and I am running into "error while inserting data"

Though that is my custom error message, it tells me there is an issue with sanitizing data.

I am also receiving [object Object] which tells me that a certain form field is not getting stringrified.

Can someone please help?

    <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" style="width:200px;" name="sourcename' + rowCount + '" class="form-control sourcename01" /></td>' +
                    '<td><input type="text" style="width:200px;" name="sourceaddress' + rowCount + '" class="form-control sourceaddress01" /></td>' +
                    '<td><input type="text" style="width:200px;" name="sourceincome' + rowCount + '" class="form-control sourceincome01" /></td>' +
                    '<td style="width:200px;"><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", ".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 alldata = {
                        'mySource': sname,
                        'mySAddress': saddress,
                        'mySIncome': sincome
                    }
                    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>
</head>
<body>  
    <form id="form1" runat="server">  
        <div class="container">  
            <h2>Forms</h2>  
            <table class="table" id="maintable">  
                <thead>  
                    <tr>  
                        <th>Name</th>  
                        <th>Address</th>  
                        <th>Income</th>  
                    </tr>  
                </thead>  
                <tbody>  
                    <tr class="data-contact-person">  
                        <td>  
                            <input type="text" style="width:200px;" name="sourcename" class="form-control sourcename01" /></td>  
                        <td>  
                            <input type="text" style="width:200px;" name="sourceaddress" class="form-control sourceaddress01" /></td>  
                        <td>  
                            <input type="text" style="width:200px;" name="sourceincome" class="form-control sourceincome01" /></td>  
                        <td style="width:200px;">  
                            <button type="button" id="btnAdd" class="btn btn-xs btn-primary classAdd">Add More</button>  
                        </td>  
                    </tr>  
                </tbody>  
            </table> 
            <button type="button" id="btnSubmit" class="btn btn-primary btn-md pull-right btn-sm">Submit</button>  
        </div>  
    </form>  
</body>  
</html>

Open in new window

LVL 29
sammySeltzerAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Nitin SontakkeDeveloperCommented:
If possible, you are better off debugging the code in 'closures.aspx/SaveData' method and post the exception here. Because that's where the error is coming. No point in looking at client side code. Furthermore, you will also see the values being posted.
0
sammySeltzerAuthor Commented:
Hi, Thanks a lot for the prompt response.

I doubt that it is coming from codebehind. I can't even get to it. If I could I would have debugged it and found the issue by now.

I could be wrong but I am well versed with this part of the code.

Please have a look.

Imports System.Collections.Generic
Imports System.Configuration
Imports System.Data
Imports System.Data.SqlClient
Imports System.Linq
Imports System.Web
Imports System.Web.Services
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports Newtonsoft.Json

Partial Public Class disclosures
    Inherits System.Web.UI.Page
    Public Shared Constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString

    Protected Sub Page_Load(sender As Object, e As EventArgs)

    End Sub

    <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
End Class

Public Class Employee
    Public Property mySpouse() As String
        Get
            Return m_mySpouse
        End Get
        Set(value As String)
            m_mySpouse = value
        End Set
    End Property
    Private m_mySpouse As String
    Public Property mySAddress() As String
        Get
            Return m_mySAddress
        End Get
        Set(value As String)
            m_mySAddress = value
        End Set
    End Property
    Private m_mySAddress As String
    Public Property mySIncome() As String
        Get
            Return m_mySIncome
        End Get
        Set(value As String)
            m_mySIncome = value
        End Set
    End Property
    Private m_mySIncome As String
    Public Property CreatedDate() As DateTime
        Get
            Return m_CreatedDate
        End Get
        Set(value As DateTime)
            m_CreatedDate = Value
        End Set
    End Property
    Private m_CreatedDate As DateTime

End Class

Open in new window

0
Nitin SontakkeDeveloperCommented:
Got it. You suspect that the request is not being posted at all!

If such is the case why not try an exhaustive form for error function as shown below:

    error: function (jqXHR, exception) {
        var msg = '';
        if (jqXHR.status === 0) {
            msg = 'Not connect.\n Verify Network.';
        } else if (jqXHR.status == 404) {
            msg = 'Requested page not found. [404]';
        } else if (jqXHR.status == 500) {
            msg = 'Internal Server Error [500].';
        } else if (exception === 'parsererror') {
            msg = 'Requested JSON parse failed.';
        } else if (exception === 'timeout') {
            msg = 'Time out error.';
        } else if (exception === 'abort') {
            msg = 'Ajax request aborted.';
        } else {
            msg = 'Uncaught Error.\n' + jqXHR.responseText;
        }
    },

Open in new window


The above code is being copied from here.
0
Become a Microsoft Certified Solutions Expert

This course teaches how to install and configure Windows Server 2012 R2.  It is the first step on your path to becoming a Microsoft Certified Solutions Expert (MCSE).

Nitin SontakkeDeveloperCommented:
If (appropriate / possible) you could also post the value of 'data' as well, please.
0
sammySeltzerAuthor Commented:
You said:

Got it. You suspect that the request is not being posted at all!


Exactly my point.

I am about to remote in to add your code bit and let you know asap.

Thanks again
0
sammySeltzerAuthor Commented:
So, how / where exactly should I place this code in relation to the markup I posted?
0
Nitin SontakkeDeveloperCommented:
It goes at line 48-50 of your client-side code posted above.

But wait a minute. Do you not think there is a case of a missing , (comma) after the error function on line 50?

Have a close look. Please also refer to the link I posted to compare the typical ajax call code.
0
sammySeltzerAuthor Commented:
Do you mean there should be a comma after this line
                   'mySIncome': sincome?

No
0
Nitin SontakkeDeveloperCommented:
No. Line 50 in your client-side code.

                    error: function () {
                        alert("Error while inserting data");
                    },

Open in new window

0
sammySeltzerAuthor Commented:
sorry, that may have been inadvertently inserted when I was  copying it to post here.
0
Nitin SontakkeDeveloperCommented:
The comma is NOT there. I think it should be there. Also have you tried seeing client-side error log, which will typically be available under the 'console' table after you press F12 in browser window.
0
Peos JohnPHPCommented:
This is due to data not sent exact json format.

Can you try just removing dataTyp:json line ? It works without this line, I have used    url: 'closures.php', for testing you can change to your page.

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

       <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" style="width:200px;" name="sourcename' + rowCount + '" class="form-control sourcename01" /></td>' +
                    '<td><input type="text" style="width:200px;" name="sourceaddress' + rowCount + '" class="form-control sourceaddress01" /></td>' +
                    '<td><input type="text" style="width:200px;" name="sourceincome' + rowCount + '" class="form-control sourceincome01" /></td>' +
                    '<td style="width:200px;"><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", ".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 alldata = {
                        'mySource': sname,
                        'mySAddress': saddress,
                        'mySIncome': sincome
                    }
                    data.push(alldata);
                });
                console.log(data);
                return data;
            }

            $("#btnSubmit").click(function () {
                var data = JSON.stringify(getAllEmpData());
                //console.log(data);
                $.ajax({
                    url: 'closures.php',
                    type: 'POST',
                     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>
</head>
<body>  
    <form id="form1" runat="server">  
        <div class="container">  
            <h2>Forms</h2>  
            <table class="table" id="maintable">  
                <thead>  
                    <tr>  
                        <th>Name</th>  
                        <th>Address</th>  
                        <th>Income</th>  
                    </tr>  
                </thead>  
                <tbody>  
                    <tr class="data-contact-person">  
                        <td>  
                            <input type="text" style="width:200px;" name="sourcename" class="form-control sourcename01" /></td>  
                        <td>  
                            <input type="text" style="width:200px;" name="sourceaddress" class="form-control sourceaddress01" /></td>  
                        <td>  
                            <input type="text" style="width:200px;" name="sourceincome" class="form-control sourceincome01" /></td>  
                        <td style="width:200px;">  
                            <button type="button" id="btnAdd" class="btn btn-xs btn-primary classAdd">Add More</button>  
                        </td>  
                    </tr>  
                </tbody>  
            </table> 
            <button type="button" id="btnSubmit" class="btn btn-primary btn-md pull-right btn-sm">Submit</button>  
        </div>  
    </form>  
</body>  
</html>

Open in new window


Here is the reference link I got this idea from.

http://stackoverflow.com/questions/19976627/posting-json-with-jquery-ajax-to-php
0
Julian HansenCommented:
Any reason you are not using serializeArray() to get your form data
            $("#btnSubmit").click(function () {

                // USE jQuery serializeArray TO GATHER ALL FORM DATA
                var formData = (this.form).serializeArray();

                var data = JSON.stringify(formData);
                //console.log(data);
                $.ajax({
                    url: 'closures.php',
                    type: 'POST',
                     contentType: 'application/json; charset=utf-8',
                    data: JSON.stringify({ 'empdata': data }),
                    success: function () {
                        alert("Data Added Successfully");
                    },
                    error: function () {
                        alert("Error while inserting data");
                    }
                });
            });

Open in new window

0
Julian HansenCommented:
Note
dataType:'JSON'

Is for return data only - it tells jQuery to treat the response as a JSON response which jQuery then automatically parses into a JavaScript object.

As your function is not returning any data you do not need it and it has no bearing on the sending of the data - that is what the ContentType Request Header is for.
0
sammySeltzerAuthor Commented:
Thank you guys very much. YOU all have been awesome.

I will test various parts of your code as soon as I get to work this morning and report back.

I really appreciate the great responses.
0
sammySeltzerAuthor Commented:
A couple of thoughts and then one question.

First, when I tried your solution Julian, I am getting the following error:

Error: Object doesn't support property or method 'serializeArray'


When I tried yours ( actually I tried yours first) but when I tried it, it said "Data added successfully"

Infact, no data was added to the database. It turns out that the reason it said data was added successfully was because SaveData webmethod was removed from the script, from both of your solutions as a matter of fact.

That leads to my question, any reason it was removed?

it is in there because of the INSERT statement.

Thanks again for your help.
0
Julian HansenCommented:
That leads to my question, any reason it was removed?
No that was a typo - to do a test here I had to change that to point to one of my own scripts when I pasted it back I did not copy the url in correctly. Should be
            $("#btnSubmit").click(function () {

                // USE jQuery serializeArray TO GATHER ALL FORM DATA
                var formData = (this.form).serializeArray();

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

Open in new window

First, when I tried your solution Julian, I am getting the following error:
You need to show us the code where you tried to do this. serializeArray is a valid jQuery function and will serialize your form variables into an array that can then be stringified into JSON
0
sammySeltzerAuthor Commented:
Here it is as I just used it:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Forms</title>
   <meta name="viewport" content="width=device-width, initial-scale=1" />  
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" />  
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>  
    <script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
    <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" style="width:200px;" name="sourcename' + rowCount + '" placeholder="Name of income source..." class="form-control sourcename01" /></td>' +
                    '<td><input type="text" style="width:200px;" name="sourceaddress' + rowCount + '" placeholder="Address of income source..." class="form-control sourceaddress01" /></td>' +
                    '<td><input type="text" style="width:200px;" name="sourceincome' + rowCount + '" placeholder="Income..." class="form-control sourceincome01" /></td>' +
                    '<td style="width:200px;"><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", ".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 alldata = {
                        'mySource': sname,
                        'mySAddress': saddress,
                        'mySIncome': sincome
                    }
                    data.push(alldata);
                });
                console.log(data);
                return data;
            }

            $("#btnSubmit").click(function () {

                // USE jQuery serializeArray TO GATHER ALL FORM DATA
                var formData = (this.form).serializeArray();

                var data = JSON.stringify(formData);
                //console.log(data);
                $.ajax({
                    url: 'closures.aspx/SaveData',
                    type: 'POST',
                    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>
<style type="text/css">
    .bs-example{
    	margin-left: 250px;
    	margin-top: 30px;
    }
</style>
</head>
<body> 
   <div class="bs-example"> 
    <form id="form1" runat="server">  
        <div class="container">  
            <h2>Forms</h2>  
            <table id="maintable">  
                <thead>  
                    <tr>  
                        <th>Name</th>  
                        <th>Address</th>  
                        <th>Income</th>  
                    </tr>  
                </thead>  
                <tbody>  
                    <tr class="data-contact-person">  
                        <td>  
                            <input type="text" style="width:200px;" name="sourcename" class="form-control sourcename01" placeholder="Name of income source..." /></td>  
                        <td>  
                            <input type="text" style="width:200px;" name="sourceaddress" class="form-control sourceaddress01" placeholder="Address of income source..." /></td>  
                        <td>  
                            <input type="text" style="width:200px;" name="sourceincome" class="form-control sourceincome01" placeholder="Income..." /></td>  
                        <td style="width:200px;">  
                            <button type="button" id="btnAdd" class="btn btn-xs btn-primary classAdd">Add More</button>  
                        </td>  
                    </tr>  
                </tbody>  
            </table><br />

            <button type="button" id="btnSubmit" class="btn btn-primary btn-md pull-center btn-sm">Submit</button> 
        </div>  
    </form>  
  </div>
</body>  
</html>

Open in new window

0
Julian HansenCommented:
You are stringifying your data twice.
0
sammySeltzerAuthor Commented:
That's your code I copied boss.

Can you please post the correct code if you don't mind, just the script not entire thing.

Thanks for all your help.

I have been stuck on this now for almost two days.
0
sammySeltzerAuthor Commented:
I added a script debugger:

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

Open in new window

and got the following error messages:

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


This doesn't make sense.
0
Nitin SontakkeDeveloperCommented:
Please refer to your original post of the question and line 26 in it and please see the line below from your server side code:

    cmd.Parameters.AddWithValue("@sname", data.mySpouse)

Open in new window


Should it not be 'mySource'?
1
Julian HansenCommented:
That's your code I copied boss.
Which I got from your opening post.


I am also receiving [object Object] which tells me that a certain form field is not getting stringrified.
Breaking your code down
You have the first step which is to get the data - let's use your approach for now - we can look at serializeArray down the road
var data = JSON.stringify(getAllEmpData());

Open in new window

data now contains a JSON string
In your AJAX call you have this
data: JSON.stringify({ 'empdata': data }),

Open in new window

So now you have a sringified object that has one property empdata that contains a string that is another stringified JavaScript object.

Let us take a step back - what are you expecting to see on the server, I doubt it is an object that has a property pointing to more data that needs to be decoded.

If I look at your server side code I am seeing this
Dim serializedData = JsonConvert.DeserializeObject(Of List(Of Employee))(empdata)

Open in new window

So it appears that it is expecting empdata to be a normal POST
Therefore I would make the following change to your original code
            $("#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',
                    // ***** DON'T STRINGIFY THE data PROPERTY *****
                    data: { 'empdata': data },
                    success: function () {
                        alert("Data Added Successfully");
                    },
                    error: function () {
                        alert("Error while inserting data");
                    }
                });

Open in new window

0
sammySeltzerAuthor Commented:
Man, this is so complicated.

It turns out that the code works as is as long as there is just one class.

For instance, If I use just one class called data-contact-person, it works and data is successfully inserted into the database.

If however, I add another class as shown below:

        $(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" style="width:200px;" name="sourcename' + rowCount + '" placeholder="Name of income source..." class="form-control sourcename01" /></td>' +
                    '<td><input type="text" style="width:200px;" name="sourceaddress' + rowCount + '" placeholder="Address of income source..." class="form-control sourceaddress01" /></td>' +
                    '<td><input type="text" style="width:200px;" name="sourceincome' + rowCount + '" placeholder="Income..." class="form-control sourceincome01" /></td>' +
                    '<td style="width:200px;"><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" style="width:200px;" name="spousename' + rowCount + '" placeholder="Name of income source of spouse..." class="form-control spousename01" /></td>' +
                    '<td><input type="text" style="width:200px;" name="spouseaddress' + rowCount + '" placeholder="Address of income source of spouse..." class="form-control spouseaddress01" /></td>' +
                    '<td><input type="text" style="width:200px;" name="spouseincome' + rowCount + '" placeholder="Income..." 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
            });

Open in new window


and attempt to have multiple INSERT statements using same saveData webmethod, it doesn't work.

Hence the error and only I was able to pinpoint the issue was using the debug script I posted earlier.

There is got to be a better way.
0
Julian HansenCommented:
With the following code I was able to connect to a VB Web Service and have the data come through as expected
$("#btnSubmit").click(function () {
  var data = JSON.stringify(getAllEmpData());
  $.ajax({
    url: 'http://localhost:60154/Service1.asmx/SaveData',
    type: 'POST',
    dataType: 'json',
    data: { 'empdata': data },
    success: function () {
      alert("Data Added Successfully");
    },
    error: function () {
      alert("Error while inserting data");
    }
  });
});

Open in new window

Note removal of the contentType property.

On the server side this code
Public Function SaveData(empdata As String) As String
        Return "Hello World"
    End Function

Open in new window

Receives the data as empdata equal to the following string
"[{"mySource":"Fred Smith","mySAddress":"12 Apple Way","mySIncome":"100"},{"mySource":"Jane Doe","mySAddress":"1 Spring Drive","mySIncome":"200"}]"

Open in new window

If you decode that JSON string you will end up with an array of 2 objects with the data you want.
Dim serializedData = JsonConvert.DeserializeObject(Of List(Of Employee))(empdata)

Open in new window

However if you look at the next bit of code
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) ' HERE *****
    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

Open in new window

As Nitin Sontakke pointed out here you are accessing the field as mySpouse - which won't work because we are sending it as mySource - so you need to change mySpouse to mySource.

That's about as far as was able to go with time I had.
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
sammySeltzerAuthor Commented:
Thank you guys for your help and time.

I will post the final product when I arrive there.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
ASP.NET

From novice to tech pro — start learning today.