"Encountered a problem while trying to insert data using JSON and Ajax

I've been struggling to figure out where the issue lies in my code. I've double-checked everything and it all seems correct, but I keep encountering errors.

Below is the code snippet:

Markup:

<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/jquery-ui.min.js"></script>

<script type="text/javascript">
    $(document).ready(function(){
        $("#Button1").click(function(){       
            var Name=document.getElementById('Text1').value
            var Class=document.getElementById('Text2').value
            var Data=JSON.stringify({Name:Name,Class:Class});
            alert(Data);       
            $.ajax({
                type: 'POST',
                contentType: "application/json; charset=utf-8",
                url: 'Default.aspx/InsertData',
                data:Data,
                async: false,
                success: function (response) {
                    $('#Text1').val('');
                    $('#Text2').val('');                 
                },
                error: function () { 
                    alert("Error") 
                }
            }); 
        });
    });
</script>

ASP.NET AJAX Page Method in code-behind:

[WebMethod]
public string InsertData(string Name, string Class)
{
    SqlCommand cmd = new SqlCommand("Insert into employee(EmployeeName,Class) values(@EmpName,@Classs)",con);
    cmd.Parameters.AddWithValue("@EmpName", Name);
    cmd.Parameters.AddWithValue("@Classs",Class);
    cmd.ExecuteNonQuery();
    con.Close();

    return "True";
}

Answer №1

Here is a helpful tip:

Remember, the method must be declared as static if it is located in an ASPX page's code behind file.

[WebMethod]
    public static string InsertData(string Name, string Class)
    {
        SqlCommand cmd = new SqlCommand("Insert into employee(EmployeeName,Class) values(@EmpName,@Classs)",con);
        cmd.Parameters.AddWithValue("@EmpName", Name);
        cmd.Parameters.AddWithValue("@Classs",Class);
        cmd.ExecuteNonQuery();
        con.Close();

        return "True";
    }

Answer №2

There is no need to convert it into a string format.

Simply pass without converting it to a string

"{'Name':'"+Name+"','Class':'"+Class+"'}"  

If you prefer passing the object in a stringified form, it should be done like this

 JSON.stringify({'Name':Name,'Class':Class});

Make sure to include the quotes as shown above.

var Data=JSON.stringify({'Name':Name,'Class':Class});
        alert(Data);       
        $.ajax({
        type: 'POST',
        contentType: "application/json; charset=utf-8",
        url: 'Default.aspx/InsertData',
        data:Data,
        async: false,
         success: function (response) {
                             $('#Text1').val('');
                             $('#Text2').val('');

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

In the backend code of the page

    [WebMethod]
        public string InsertData(myobj getdat)
        {
            SqlCommand cmd = new SqlCommand("Insert into employee(EmployeeName,Class) values(@EmpName,@Classs)",con);
            cmd.Parameters.AddWithValue("@EmpName", getdat.Name);
            cmd.Parameters.AddWithValue("@Classs",getdat.Class);
            cmd.ExecuteNonQuery();
            con.Close();

            return "True";
        }
public class myobj
{
public string Name {get;set;}
public string Class{get;set;}
}

Answer №3

To ensure proper functioning, ASP.NET AJAX Page Methods should be declared as static. Revise your code with the following changes:

[WebMethod]
public static string InsertData(string Name, string Class)
{
    SqlCommand cmd = new SqlCommand("Insert into employee(EmployeeName,Class) values(@EmpName,@Classs)",con);
    cmd.Parameters.AddWithValue("@EmpName", Name);
    cmd.Parameters.AddWithValue("@Classs",Class);
    cmd.ExecuteNonQuery();
    con.Close();

    return "True";
}

Want to know why ASP.NET AJAX page methods have to be static? Check out this article: Why do ASP.NET AJAX page methods have to be static?.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

"Optimizing Long Polling for Maximum Efficiency: Tips for utilizing php, Jquery

Hey everyone, I'm looking to implement real-time flash message notifications for users when they receive a new private message in their inbox. What is the most effective way to achieve this using technologies like PHP 5.3, jQuery, and JSON? I prefer ...

Access JSON data from the data[] object in PHP and handle it

I have a task where I need to extract specific data from Facebook using the following code snippet: $tagData = file_get_contents('https://graph.facebook.com/123456789/friends?access_token='.$access_token); echo $tagData; When this runs, it gen ...

Issues arise when jQuery functions do not execute as expected within an "if" statement following

Recently, I delved into the realm of AJAX and embarked on a journey to learn its intricacies. Prior to seeking assistance here, I diligently scoured through past queries, such as this, but to no avail. Here is an excerpt from my code: $('.del'). ...

"Utilize PHP and AJAX to dynamically filter records based on selected values from a

I am looking to utilize AJAX to dynamically display a list of examinees based on the selected exam date from a dropdown list. I'm new to PHP and AJAX, so any guidance would be appreciated. <?php include 'configuration.php'; $queryselect ...

Avoid writing any duplicate values to a CSV file

I need help with converting a JSON file into a CSV file while avoiding duplicate values in the output. I want to include four columns in my CSV file without repeating any data. My approach involves storing variables in an array and writing them to a CSV f ...

The File API functions properly with cURL, but encounters issues when used with AJAX and Postman

I currently have gotenberg running as my chosen document to PDF conversion API and it is successfully functioning with the use of cURL. The command I utilize with cURL is structured like this: curl --request POST --url http://example.com --header ' ...

Generating examples of two models that are interdependent

In my Javascript form, I have implemented an AJAX POST request that successfully creates a new instance of a model called Component. Now, my goal is to allow users to input keywords for the Component model through the same form. To achieve this, I have al ...

Steps to fix the issue: Unhandled Type Error: t.addLayer is not a recognized function

I've encountered a bit of difficulty with an error that I can't seem to figure out. I'm currently working on adding a geoJSON layer to my Leaflet Map, specifically a multi-polygon representing country borders. To achieve this, I'm using ...

Easy jQuery Mobile and AJAX login solution

My current project involves creating a mobile app with user login capabilities using PhoneGap, jQuery Mobile, AJAX, and PHP. I am starting with a basic HTML and PHP structure as I am not an experienced programmer, but even my simple user login form is not ...

Retrieving specific information from the Model and returning it as a JSON response using annotations

I am interested in receiving a JSON response with additional annotations. Currently, my JSON response looks like: { "id": 1, "startDate": [ 1993, 12, 12 ], "endDate": [ 2018, 11, 22 ], "totalDistance": 255, "totalPrice": 211 } How ...

"Multiple instances of JavaScript files seem to be present when using Ajax navigation

Having some difficulties with AJAX navigation. The issue is that the JavaScript files loaded remain in the browser even after the new content is loaded, even when they are no longer in the DOM. These files appear as VM files in the browser console and cont ...

Challenge encountered in Ajax with data processing

Help needed with making an ajax request to update the "status" parameter of my "task" object. The script is set up to retrieve the task ID and the new status, but I'm encountering errors in either the routes.rb file, the update_status function within ...

Retrieving distinctive keys from deeply nested JSON data using jq

I am seeking to create an all_keys function that can extract all keys from a nested JSON blob, navigating through arrays and objects as necessary. The goal is to generate an array of keys without any duplicates. For example, consider the following input: ...

Only one class is allowed to access the API value

Recently, I created some classes (JsonData which consists of getters and setters for the Json value retrieved from an API): GetSetJsonData: class GetSetJsonData { HttpClient client; #region SuccesLogin JsonData.SuccesLogin.RootObject succesL ...

Organize JSON data based on the timestamp

What is the most effective method for sorting them by timestamp using jquery or plain JavaScript? [{"userName":"sdfs","conversation":"jlkdsjflsf","timestamp":"2013-10-29T15:30:14.840Z"},{"userName":"sdfs","conversation":"\ndslfkjdslkfds","timestamp" ...

Remove data from a database using Ajax in ASP.NET MVC without utilizing DataTables

I'm encountering a slight issue with my code. I am attempting to delete a row from the database without using DataTables in ASP.NET MVC, but it seems to be not working as expected. I have displayed all items from the database on a page within div elem ...

A guide on customizing column names in MUI Datatables through object keys

I'm currently facing an issue where I need to set the name of a column in MUI Datatables using an object key. Specifically, I want to set one of the column names with the first element of children.childName so that it displays a list of child names, b ...

Is it possible to modify the value of just one element within a Nested JSON in Kotlin?

Let's assume we have a JSON as shown below... {"cars": [ { "id": 1, "brand": "Honda", "milesDriven": "100,000"}, { "id": 2, "brand": "Toyota", "milesDriven ...

Why won't XML load with jquery GET, but does load with a direct link and PHP?

When it comes to pulling in an xml feed, I've been experimenting with using php and simpleXML to load it. Interestingly, I can access the direct link without any issues. However, when attempting to utilize jquery and GET method, the request times out ...

How can the background color of a DIV be altered based on the values of an array's minimum

Basically, I am fetching values from an array using AJAX. The background color will change from green to red based on the "aht_value". Currently, the colors are displaying correctly because I hardcoded the values in the calculation below. However, I want t ...