Displaying records up to the year 1427 only

I am facing an issue while trying to populate data from a database into an HTML table using JSON and C#.NET. The problem I am encountering is that only up to 1427 records are being displayed, and I keep getting the error message "Unexpected token <". Despite searching online for a solution, I haven't been able to resolve this issue.

Any help would be greatly appreciated.

This is what I have attempted:

//JSON

$(document).ready(function () {
      bindData();
});

function bindData() {
$.ajax({
    type: "POST",
    url: "MyTestForm.aspx/getData",
    data: "{}",
    contentType: "application/json;charset=utf-8",
    datatype: "jsondata",
    async: "true",
    success: function (response) {

        var msg = eval('(' + response.d + ')');

        if ($('#tblResult').length != 0) {
            $("#tblResult").remove();
        }

        var table = "<table class='tblResult' id='tblResult'><thead><tr><th>Name</th><th>Address</th><th>Age</th><th>Action</th></tr></thead> <tbody>";

        for (var i = 0; i <= (msg.length - 1) ; i++) {
            var row = "<tr>";
            row += '<td>' + msg[i].Name + '</td>';
            row += '<td>' + msg[i].Address + '</td>';
            row += '<td>' + msg[i].Age + '</td>';
            row += '<td><img src="edit.png" title="Edit Record." onclick="bindRecordToEdit(' + msg[i].Id + ')" /> ';
            row += '    <img src="delete.png" title="Delete Record." onclick="deleteRecord(' + msg[i].Id + ')" /></td>';
            row += '</tr>';
            table += row;

        }

        table += "</tbody></table>";
        $('#divData').html(table);
        $('#divData').slideDown("slow");

    },
    error: function (response) {
        alert(response.status + ' ' + response.statusText);
    }
});

}

//C#

[WebMethod]
public static string bindRecordtoEdit(int id)
{
    string data = string.Empty;
    try
    {
        using (MyTestDatabaseEntities context = new MyTestDatabaseEntities())
        {
            var obj = (from r in context.MstNewTests select r).ToList();
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            data = serializer.Serialize(obj);
        }
        return data;
    }
    catch (Exception)
    {
        return data;
    }
}

Answer №1

Consider using the jquery template plugin for streamlining repetitive code.

<script id="trTemplate" type="text/x-jquery-tmpl">
            <tr>
                {{each $data}}
                    <td>${Col}</td>
                {{/each}}
            </tr>
</script>


<table id="containerTable">
</table>

Upon successful AJAX response, utilize this line to replace your data:

$('#trTemplate').tmpl(data).appendTo('#containerTable');

Answer №2

If you want to extract information from your JSON data, utilize the native JSON object.

var jsonData = JSON.parse(input);

Here is a sample demonstrating how to construct a table using various methods like table, createTHead, insertRow(), insertCell and textContent.

function createTable(info) {
  "use strict";

  var table, thead, tbody, tr, data, cell, img, i, len;

  table = document.createElement('table');
  table.class = 'resultTable';
  table.id = 'resultTable';

  thead = table.createTHead();

  tr = thead.insertRow();

  tr.insertCell().textContent = 'Name';
  tr.insertCell().textContent = 'Address';
  tr.insertCell().textContent = 'Age';
  tr.insertCell().textContent = 'Action';

  tbody = table.createTBody();


  len = info.length;
 for (i = 0; i < len ; i++) {
    data = info[i];

    tr = tbody.insertRow();

    tr.insertCell().textContent = data.Name;
    tr.insertCell().textContent = data.Address;
    tr.insertCell().textContent = data.Age;

    cell = tr.insertCell();

    img = new Image();
    img.src = 'edit.png';
    img.dataset.name = 'edit';
    img.dataset.value = data.id;
    img.title = 'Edit Record';
    cell.appendChild(img);


    img = new Image();
    img.src = 'delete.png';
    img.dataset.name = 'edit';
    img.dataset.value = data.id;
    img.title = 'Delete Record';
    cell.appendChild(img);

  }

  table.addEventListener(
    'click',
    function (event) {
      var target = event.target;

      if (target.nodeName != 'IMG') return;

      switch(target.dataset.name) {
        case 'edit':
         editAction(target.dataset.value);
         break;
        case 'delete':
         deleteAction(target.dataset.value);
         break;
      }
    }
  );
  return table;
};

These are placeholder functions. You should implement your own logic in them, tailored to match your requirements.

function editAction(id) {
  console.log('Editing record with ID: ', id)
};

function deleteAction(id) {
  console.log('Deleting record with ID: ', id)
};

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

What is the proper way to access a URL such as www.gmail.com using code?

Is there a way to dynamically open a URL in a new tab when a user clicks on a button? I am looking to retrieve the link from a database and have it automatically open in a new tab. For example, opening an address like gmail.com. ...

Showing the True/False data in Material-UI Table using React

I am currently working on a Material Table event log implementation. This event log is designed to receive data in the form of 'string' and 'boolean' values. While I am able to display the string values without any issue, I am facing di ...

ListCollectionView does not automatically update the current selected item on a TreeView control in WPF

I've encountered an issue with a simple example involving a Window with a TreeView and a Button. The expected behavior is that when you click the button, the selected item should be displayed. However, the CurrentItem property does not update when the ...

What is the best way to manage a 301 redirect from a current page to a new page within my index.js script?

Hello everyone, hope you're having a great Friday! I'm looking for advice on the best approach to handle a 301 redirect in node.js from an existing file to another file. Let's say I currently have a file called /contact router.get('/con ...

Is it a design choice or an error in List<T>.InsertRange()?

While examining the code for List<T>.InsertRange() in the .NET 4.0 framework, I stumbled upon an interesting quirk. Take a look at the code snippet below: public void InsertRange(int index, IEnumerable<T> collection) { if (collecti ...

Using this.setState in ReactJS removes filters

Hey everyone, I've been struggling with a technical issue for the past few days and would really appreciate any hints or solutions. The problem lies in creating a table using the material-table library. Specifically, I need to extract the docID and do ...

Efficiently process and handle the responses from Promise.all for every API call, then save the retrieved data

Currently, I am passing three API calls to Promise.all. Each API call requires a separate error handler and data storage in its own corresponding object. If I pass test4 to Promise.all, how can I automatically generate its own error and store the data in ...

utilizing jQuery to deliver a $.post request to a .aspx file

Recently, I started following a jQuery tutorial on the phpAcademy channel hosted on thenewboston. In this tutorial, they demonstrate how to create an email validation form using ASP.net instead of PHP. However, despite following all the steps in the tutor ...

The system is unable to accept the Object ID

I am encountering an issue with displaying the Object ID from MongoDB in the console in VS Code. I am trying to retrieve the Object ID for the user who is currently logged into my application. I have created a hidden input tag with an id of ObjectID. <! ...

Setting the default value in setState in React Native allows you to initialize state

const fetchData = async (key) => { try { const jsonData = await AsyncStorage.getItem(key) return jsonData != null ? JSON.parse(jsonData) : false; } catch(error) { console.log(error); } } useEffect ...

Initiating and handling a POST request

In my node.js server, I have a simple setup like this: var express = require('express'); var app = express(); app.post('/savearticles', function (req, res) { res.send(req.body); }); Additionally, the javascript code is not very c ...

Sort through JSON data according to the current page's URL path

The issue at hand Currently, I am faced with the challenge of filtering JSON data and presenting only a specific portion of it on an Angular web page, depending on the URL of that particular page. Delving deeper into the matter Within my dataset, there ...

Generate a list of files and transfer them to an input file

I am currently working on creating a drag and drop area where I can retrieve dataTransfer items using webkitGetAsEntry, and then differentiate between directories and files. My goal is to convert these files into a FileList and transfer them to a file inp ...

Unable to backtrack once a response has been sent

My Express application keeps crashing after sending a response to the client. It appears that the code continues to run even after the response has been returned. Can you please review the code snippet provided below? const EditUser = async (req, res) => ...

Incorporating HTML themes within ReactJS

While I am still relatively new to ReactJS, I am eager to expand my understanding of it with this question. I have a preexisting HTML/CSS theme that I would like to integrate into a React application. Is there a method to incorporate this theme seamlessly ...

The variable __dirname has not been defined

Can anyone explain why my Google Cloud Run instance is unable to recognize the __dirname variable? My expressjs server contains the following code: import path from 'path'; const App = express() .get('/*', (_req, res) => { ...

Modify the bootstrap form dynamically in response to the user's input. Update the form layout instantly as the user types, with no need for clicking any buttons

Imagine a scenario where, as soon as you enter your credit card number, the form automatically undergoes a change without requiring a button click, similar to how a credit card logo pops up. The form detects changes instantly after the input field has be ...

Maintaining a persistent HTTP connection for requests under 1KB sent every second

I'm currently fine-tuning my web server configurations to accommodate a high volume of simultaneous users, and I've come across a dilemma regarding whether or not to deactivate HTTP Keep-Alive. Utilizing a CDN for all site images means that only ...

Discovering the Harshad number

I find myself in a predicament where the issue at hand is defined as: Harshad/Niven numbers are positive numbers that are divisible by the sum of their digits. All single-digit numbers are Harshad numbers. For instance, 27 is a Harshad number as 2 + 7 = ...

Is there a method in JS/jQuery to fill my input field with a constant string and ensure leading zeros are included?

I am looking to create an input textbox that starts with a fixed string followed by up to 6 leading zeros. As the user types in the input box, the leading zeros will be automatically removed once the maximum length of 6 characters is reached. The initial s ...