What could be causing the Ajax error to occur in my .Net Data table?

While trying to load a table, I encountered an ajax error in the datatable (.net).

Below is the code for my data table:

<table id="productsTable" class="table table-striped table-bordered">
<thead>
    <tr>
        <th>Name</th>
        <th>Code</th>
        <th>Price</th>
        <th>No of Products</th>
    </tr>
</thead>
</table>

<link href="//cdn.datatables.net/1.10.20/css/jquery.dataTables.min.css" rel="stylesheet" />
<link href="https://cdn.datatables.net/1.10.20/css/dataTables.bootstrap.min.css" rel="stylesheet" />



@section scripts{
<script src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.20/js/dataTables.bootstrap.min.js"></script>

<script>
    $(document).ready(function () {
        $('#productsTable').DataTable({
            "ajax": {
                "url": "/Products/GetData",
                "type": "GET",
                "datatype": "json"
            },
            "columns": [
                { "data": "Name" },
                { "data": "Code" },
                { "data": "Price" },
                { "data": "Available" }
            ]

        });
    });
</script>
}

This is the controller code:

public ActionResult GetData()
    {
        using (DBModel db = new DBModel())
        {
            List<product> proList = db.products.ToList<product>();
            return Json(new { data = proList }, JsonRequestBehavior.AllowGet);
        }

    }

product represents the database table.

Here is the model structure:

public partial class product
{
    public int ProductId { get; set; }
    public string Name { get; set; }
    public string Code { get; set; }
    public decimal Price { get; set; }
    public Nullable<int> Available { get; set; }
    public byte[] is_deleted { get; set; }
}

Error message received:

DataTables warning: table id=productsTable - Ajax error. For more information about this error, please see http://datatables.net/tn/7

Answer №1

Check out this link: https://dotnetfiddle.net/S7KWOg

No errors were encountered with the following:

Review

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index4</title>
    @*added this css*@
    <style>
        body {
            padding-left: 50px;
            width: 80%;
        }
    </style>

    @*removed the bootstrap for better dataTable styling*@

    @*putting all your scripts in the head*@
    <link href="//cdn.datatables.net/1.10.20/css/jquery.dataTables.min.css" rel="stylesheet" />
    @*<link href="https://cdn.datatables.net/1.10.20/css/dataTables.bootstrap.min.css" rel="stylesheet" />*@

    @*added this script*@
    <link href="https://cdn.datatables.net/1.10.20/css/jquery.dataTables.min.css" rel="stylesheet" />

    @*need this jquery script*@
    <script src="https://code.jquery.com/jquery-1.12.4.min.js"
            integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ="
            crossorigin="anonymous"></script>

    <script src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js"></script>
    @*<script src="https://cdn.datatables.net/1.10.20/js/dataTables.bootstrap.min.js"></script>*@

    <script>
        $(document).ready(function () {
            $('#productsTable').DataTable({
                "ajax": {
                    //using home controller instead of products
                    "url": "/Home/GetData",
                    //"url": "/Products/GetData",
                    "type": "GET",
                    "datatype": "json"
                },
                "columns": [
                    { "data": "Name" },
                    { "data": "Code" },
                    { "data": "Price" },
                    { "data": "Available" }
                ]

            });
        });
    </script>
</head>
<body>
    <table id="productsTable" class="table table-striped table-bordered display">
        @*added display class*@
        <thead>
            <tr>
                <th>Name</th>
                <th>Code</th>
                <th>Price</th>
                <th>No of Products</th>
            </tr>
        </thead>
    </table>

    @section scripts{
        @*moved these scripts to the head*@
    }
</body>
</html>

Controller/Model

public class product
{
    public int ProductId { get; set; }
    public string Name { get; set; }
    public string Code { get; set; }
    public decimal Price { get; set; }
    public Nullable<int> Available { get; set; }
    public byte[] is_deleted { get; set; }
}
public class HomeController : Controller
{
    public ActionResult GetData()
    {
        //using (DBModel db = new DBModel())
        //{
        //    List<product> proList = db.products.ToList<product>();
        //    return Json(new { data = proList }, JsonRequestBehavior.AllowGet);
        //}

        List<product> proList = new List<product>{ new product { Available = 1, Code = "Code1", is_deleted = new byte[1],
                                                                     Name = "Name1", Price = 1.27M, ProductId = 1 },
                                                   new product { Available = 2, Code = "Code2", is_deleted = new byte[2],
                                                                     Name = "Name2", Price = 1.28M, ProductId = 2 },
                                                   new product { Available = 3, Code = "Code3", is_deleted = new byte[3],
                                                                     Name = "Name3", Price = 1.29M, ProductId = 3 } };

        return Json(new { data = proList }, JsonRequestBehavior.AllowGet);
    }

    public ActionResult Index4()
    {
        return View();
    }

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

Displaying images in Dash Python by utilizing external Javascript

Dear audience, I am looking to incorporate an image on a Python Dash webpage that is created by JavaScript code. For more details, you can refer to the documentation here: . To include this script in a static HTML page, one would typically add the followi ...

Switch between MMM dd yyy and dd/mm/yyyy date formats easily

I have implemented a native material-ui date picker which currently displays dates in the dd/mm/yyy format. However, I need to customize the display format to show dates like this: Jun 18 2012 12:00AM. This specific date format is essential for consistency ...

Remove any posts that have a date earlier than the current day

Currently, I am working on a website showcasing events organized by my friend's music label. However, I have run into an issue while attempting to implement an "archiving automation". The code I have tried below is not functioning as expected, as my " ...

Utilizing jQuery UI for Autocomplete Functionality with Objects

Currently, I am utilizing jQuery version 1.11.2 and attempting to implement the autocomplete widget to interpret a data array. The array consists of two individuals - Will Smith and Willem Dafoe. I anticipated that upon typing 'Wi' in the text fi ...

Activate $digest when a variable is modified by a node.js function

I am currently working on developing an application using node-webkit and AngularJS. Everything was going smoothly until I tried to make Angular watch over a "legacy variable" using the method outlined in this answer, which led to an Error: [$rootScope:inp ...

HTML - Retain placeholder text while user inputs

My input is structured like this: <input value="My text" placeholder="Placeholder"> Typing in the input causes the placeholder text to disappear, which is expected. However, I am looking to keep the placeholder text visible as a background behind ...

Tips for creating a dynamic variable for an object key in jQuery to streamline your code

Utilizing the TweenMax library, I am adding styles to a div while scrolling. However, I am facing a challenge where I need different styles based on varying page resolutions. To address this issue, I implemented an if condition. Is there a way I can use a ...

Looking for a way to execute MySQL queries using promises in Protractor?

Is there a way to query a MySQL database using promises in Protractor? I have multiple queries that I need to execute during test execution, but my `executeSelectQuery` function always runs at the beginning of the test. How can I ensure it executes at the ...

Avoiding memory leaks in Reactjs when canceling a subscription in an async promise

My React component features an async request that dispatches an action to the Redux store from within the useEffect hook: const fetchData = async () => { setIsLoading(true); try { await dispatch(dataActions.fetchData(use ...

When utilizing :id with Vue, HTML attributes become hidden from view

I am facing an issue where I need to make HTML elements visible, but they appear invisible upon rendering. Below is my HTML code: <div class="created-links-wrapper" v-for="item in createdUrls" :key="item._id"> <d ...

Example of Next.js Authentication - redirecting according to authentication status, encapsulating within other functionalities

I'm currently working on a project using next.js with authentication. The authentication is set up and working, but I'm having trouble displaying the data in my navbar. Originally, I was using firebase for authentication, but now I have it set u ...

What steps can I take to ensure my project can be executed on any operating system?

After creating my solution in Visual Studio 2008 using C# WPF, I have encountered an issue when trying to publish it. The application is based on a service-connected SQL database that was created and managed using Microsoft Visual Studio Server Explorer. ...

js/jquery Asynchronous Loading of Content Replaces Existing Page Content

I have encountered a problem that I am hoping someone can assist me with. Here is the issue: A partner of mine has given me a code to use on my website, which will display certain content that I am interested in. However, this content is only relevant to ...

Issues with pop-up windows on YII2 gridview

I am currently developing a web application using the Yii2 framework for my company to efficiently manage their storage. I have incorporated various plugins from kartik-v to enhance the functionality of the application. However, I am facing an issue with i ...

Is it possible to retrieve the index of a chosen v-select option within Vuetify?

Exploring Vuetify for the first time, I'm encountering an issue with obtaining the index of a selected option on the v-select component. My goal is to populate a text field based on the option that is clicked once I have the index. I am fetching an ...

jQuery menu animation not triggering until second click

I am currently working on implementing a menu that will slide in after clicking the hamburger button (located in the upper right corner). Instead of simply appearing, I wanted to use a jQuery function for a smoother sliding effect. However, I seem to be e ...

The JavaScript button's onClick event is not functioning properly, despite the method executing normally

I'm currently working on creating a button using JavaScript that, when clicked, will trigger an AJAX request to some PHP code. Interestingly, I have already set up three buttons with the same functionality and they are all functioning perfectly. Wha ...

The node module.exports in promise function may result in an undefined return value

When attempting to log the Promise in routes.js, it returns as undefined. However, if logged in queries.js, it works fine. What changes should be made to the promise in order to properly return a response to routes.js? In queries.js: const rsClient = req ...

Challenges arising with the express search feature

Currently, I am in the process of developing an API for a to-do application. I have successfully implemented the four basic functions required, but I am facing some challenges with integrating a search function. Initially, the search function worked as exp ...

What is the process for sending an image as input to a Django view using an Angular frontend?

I currently have a django web api with an angular frontend that allows users to upload and view images. My goal now is to expand this functionality: when the user clicks the "segment" button (see image), it should send the corresponding image to my python ...