Transmitting a JSON string to my backend system to insert into my database, but unfortunately, no data is being added

I've been facing a challenging issue with my code

Currently, I am attempting to insert an object into my database using jQuery/AJAX. Despite not encountering any errors, the data is not getting added to my DB.

Here is the snippet of my JS/JQuery code:

var student = new Object();
student.Name = $("#txtNameAdd").val();
student.Age = $("#txtAgeAdd").val();
student.Email = $("#txtEmailAdd").val();

$.ajax({
    type: "POST",
    url: "Default.aspx/AddStudent",
    data: "{'studentJSONString':'" + JSON.stringify(student) + "'}",
    success: function (response) {
        $("#lblSuccessAdd").text("Success!");
        $("#lblSuccessAdd").css("display", "block");
    },
    error: function (response) {
        alert(response.responseJSON);
    }
});

The JS code above corresponds to the following code snippet in my Default.aspx page:

    [WebMethod]
    public static void AddStudent(string studentJSONString)
    {
        JavaScriptSerializer converter = new JavaScriptSerializer();
        Student a = converter.Deserialize<Student>(studentJSONString);
        WebMethods.AddStudent(a);
    }

This subsequently leads to the mentioned code in my WebMethods.cs class:

    [WebMethod]
    public static void AddStudent(Student student)
    {
        MasterStudent master = new MasterStudent();
        master.AddStudent(student);
    }

Finally, this process concludes with a method in the MasterStudent class located in my class library:

    public void AddStudent(Student student)
    {
        if (string.IsNullOrWhiteSpace(student.Name))
        {
            throw new Exception("There's no name");
        }
        if (string.IsNullOrWhiteSpace(student.Email))
        {
            throw new Exception("There's no email");
        }

        using (studentEntities model = new studentEntities())
        {
            model.student.Add(student);
            model.SaveChanges();
        }
    }

After executing the code, there are no apparent issues logged in the Console but the expected functionality is missing as well.

Previously, when running similar code on a Forms application, everything worked smoothly. This current setback has me puzzled. Can anyone offer insight into why this is failing?

Answer №1

Have you attempted connecting a debugger to it and confirming that the student object is not empty before running model.SaveChanges()?

Consider debugging to ensure that the student string is successfully converted into a valid Student object.

If so, then consider profiling the database to confirm any commands being executed.

Answer №2

After posting my question, I managed to find a solution. I modified my JQuery AJAX call as follows:

    $.ajax({
    type: "POST",
    url: "Default.aspx/AddStudent",
    data: "{'studentJSONString':'" + JSON.stringify(student) + "'}",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (response) {
        $("#lblSuccessAdd").text("Success!");
        $("#lblSuccessAdd").css("display", "block");
    },
    error: function (response) {
        $("#lblErrorAdd").text(response.responseJSON.Message);
        $("#lblErrorAdd").css("display", "block");
    }
});

Surprisingly, it now works! It seems that either the dataType or contentType were crucial for achieving what I intended

I appreciate everyone's input on this matter. Thank you!

Answer №3

let newStudent = {};
newStudent.name = $("#txtNameAdd").val();
newStudent.age = $("#txtAgeAdd").val();
newStudent.email = $("#txtEmailAdd").val();

$.ajax({
    type: "POST",
    url: "Default.aspx/AddStudent",
    data: newStudent,
    success: function (response) {
        $("#lblSuccessAdd").text("Submission Successful!");
        $("#lblSuccessAdd").css("display", "block");
    },
    error: function (response) {
        alert(response.responseJSON);
    }
});

Now you need to refer to the WebMethod below.

[WebMethod]
public static void AddStudent(Student student)
{
    MasterStudent master = new MasterStudent();
    master.AddStudent(student);
}

Give it a try and see how it goes!

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

Use jQuery to switch back and forth between two different sets of classes

I am attempting to switch between two different sets of classes using jQuery. My goal is to change from one custom icon to a font-awesome icon upon clicking an element. While I have been successful in changing a single class, I am facing challenges when tr ...

Attempting to develop a server component that will transmit a JSON result set from a MySQL database located on the local server. What is the best method to send the server object (RowDataPacket) to the

After successfully rendering server-side pages and creating forms with react hooks for database updates, I encountered a challenge in integrating Ag-Grid into my application. Despite being able to retrieve data from the database using the mysql2 module and ...

Issues with the functionality of AngularJS routing system

angular.module('Stations', ['ngRoute']) .config(function ($routeProvider) { $routeProvider .when('/documents/:stationId', { templateUrl: '/Scripts/Modules/checklist/views/index.html', ...

What is the correct way to extract results from an Array of Objects in Typescript after parsing a JSON string into a JSON object? I need help troubleshooting my code

Here is my code for extracting data from an array of objects after converting it from a JSON string to a JSON object. export class FourColumnResults { constructor(private column1: string, private column2: string, private column3: string, priv ...

converting web job json data into a pandas dataframe

Currently, I am endeavoring to retrieve JSON data for logs from Azure WebJobs services using the REST API. While I have managed to extract the data into a dataframe with various columns, my goal is to format the "lastrun" column in a tabular layout, where ...

Populate Vue.js component with data prior to rendering

I'm new to using Vue.js and I've been struggling to create a simple component that includes a select list. I've been attempting to populate the options data by simulating an Ajax request, here is my code: HTML <div id="app"> < ...

The ckeditor vanishes upon refreshing the div element

I have created two pages named openclosediv.php and content.php. The openclosediv.php page contains a list of records and a button that can show/hide the div, bringing in the content from content.php. However, I am facing an issue where the CKEditor in the ...

Starting a new React project

prtScn I'm encountering an issue while trying to initiate a new react app in Visual Studio Code. I have been following the given instructions as follows: in the visual code terminal : create-react-app sali (sali is the name) npm install node node_m ...

How to extract the id instead of the value in ReactJs when using Material UI Autocomplete

I am utilizing Material UI Autocomplete to retrieve a list of countries, and my objective is to capture the selected country ID in order to send it back to the database. <Autocomplete options={this.state.countries.map(option => option.name_en + ` ...

Discovering the specific element that was clicked from a collection of elements

I'm dealing with a scenario where multiple divs share the same class. There is a dropdown that alters the background color of one of these divs when a certain option is selected (for example, option 2 changes div #2's background color). My dile ...

Checking the conditional styling implemented with Material UI makeStyles: a step-by-step guide

For the past few weeks, I've been working on a React app where I heavily rely on Material UI components. One particular component changes its style based on the values of its props. To achieve this, I used the following approach: const useStyles = ...

Basic Node.js messaging application excluding the use of socket.io

Recently, I've delved into learning Node.js and embarked on creating a basic chat application. It appears that socket.io is the go-to option for most developers, but I'm keen on grasping the concept from a more foundational standpoint using GET a ...

Issue with req.user being Undefined in Node, Express, Passport, and Mongoose

I've encountered an issue where req.user is defined when logging in, but undefined on other paths. I'm starting to feel stuck and out of ideas at this point. Another thing is that deserialization is never being called. server.js: var LocalStra ...

A guide on navigating through JSON data in PHP

I've been researching this subject extensively, but I'm struggling to interpret this JSON string in PHP. I need to extract "summary, description, start, end" for each event. { "pages": { "current": 1, "total": 1 }, "events": [ ...

Is there a way to restrict the number of line breaks in a multiline asp:TextBox control?

Is it possible to restrict a multiline asp:TextBox to only display content on 3 lines using either javascript or C#? ...

Tips for showcasing JavaScript variables on a webpage

I am working with various JavaScript variables that involve displaying values inside div elements. goalDiv = "<div class=goal-parent id=goal-parent"+Id+">"+ "<div class=goal>"+ "<div class=top-layer>"+ "<div class=compone ...

Is there a way to determine the size of a file using either C++ or Visual C++/.NET, or possibly C#?

Similar Question: How to Determine File Size Using C#? Is there a way to calculate the size of different file types using either C++ or Visual C++/.NET or C#? I'm specifically looking for methods to determine the size of .exe, .txt, .doc, and ot ...

Create a dynamic process that automatically generates a variety of div elements by using attributes from JSON data

Is there a way to organize the fixtures from this data into separate divs based on the matchday attribute? I've tried using Underscore's groupBy function but I'm unsure how to dynamically distribute the data into individual divs for each re ...

Searching for the nearest BBCode using JavaScript regex

After checking the suggested SO questions, none of them seem to address my issue. I have a small form textarea that allows for BBCODE formatting. For example: [url=http://www.derp.com/]link[/url] [url=http://www.derp.com/435]link[/url] When a link is hi ...

Disable JavaScript when making an AJAX request

There is an issue that has surfaced for the first time, and I'm not sure why. Allow me to elaborate on it. I work with PHP in WordPress. I have an ajax request. The response of this ajax request will display an object, but my respon ...