Having trouble populating GridView in JavaScript, with no errors being captured

My current challenge involves populating an ASP GridView using JavaScript. Although the webService call is successful and I am able to retrieve data as expected, I encounter difficulties when trying to display it in my Grid.

Below are snippets of my JavaScript functions:


function SearchUsers() {
   AutoComplete.ShowLoginUserOnSearch("PL", "pi", "", "", "", 0, 20, onGetLoginUserSuccess);
}

function onGetLoginUserSuccess(result) {
    alert(result[1].ProviderName);
    $("#grdvUserInfo").append("<tr><td>" + result[1].UserName +
           "</td><td>" + result[1].ProviderName + "</td></tr>");
    alert(result[1].UserName);
}

Regarding the Asp.net implementation:

<asp:GridView ID="grdvUserInfo" AllowPaging="True" PagerSettings-
Mode="NextPreviousFirstLast" PageSize="20" runat="server" 
AutoGenerateColumns="False" Width="700px" SkinID="grdMySite" 
DataSourceID="ObjectDataSource1">

</asp:GridView>

Despite both alerts displaying the correct data, I am faced with the issue that nothing happens within the GridView. What could possibly be causing this problem?

Answer №1

HTML Example

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">script>
<script type="text/javascript">
    $(function () {
        $.ajax({
            type: "POST",
            url: "Default.aspx/GetCustomers",
            data: '{}',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: OnSuccess,
            failure: function (response) {
                alert(response.d);
            },
            error: function (response) {
                alert(response.d);
            }
        });
    });

    function OnSuccess(response) {
        var xmlDoc = $.parseXML(response.d);
        var xml = $(xmlDoc);
        var customers = xml.find("Table");
        var row = $("[id*=gvCustomers] tr:last-child").clone(true);
        $("[id*=gvCustomers] tr").not($("[id*=gvCustomers] tr:first-child")).remove();
        $.each(customers, function () {
            var customer = $(this);
            $("td", row).eq(0).html($(this).find("CustomerID").text());
            $("td", row).eq(1).html($(this).find("ContactName").text());
            $("td", row).eq(2).html($(this).find("City").text());
            $("[id*=gvCustomers]").append(row);
            row = $("[id*=gvCustomers] tr:last-child").clone(true);
        });
    }
<script>

Sample Web Method

[WebMethod]
public static string GetCustomers()
{
    string query = "SELECT top 10 CustomerID, ContactName, City FROM Customers";
    SqlCommand cmd = new SqlCommand(query);
    return GetData(cmd).GetXml();
}
private static DataSet GetData(SqlCommand cmd)
{
    string strConnString = ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
    using (SqlConnection con = new SqlConnection(strConnString))
    {
        using (SqlDataAdapter sda = new SqlDataAdapter())
        {
            cmd.Connection = con;
            sda.SelectCommand = cmd;
            using (DataSet ds = new DataSet())
            {
                sda.Fill(ds);
                return ds;

            }
        }
    }
}

https://i.sstatic.net/cUSlB.png

Answer №2

ASP.NET Development

 <asp:GridView ID="grdvUserInfo"  AllowPaging="True" PagerSettings-
     Mode="NextPreviousFirstLast"  PageSize="20" runat="server" 
     AutoGenerateColumns="False" Width="700px" SkinID="grdMySite" 
     DataSourceID="ObjectDataSource1">

    </asp:GridView>

Custom Function Implementation

   function processLoginUser(result) {
        alert(result[1].ProviderName);
        $("#grdvUserInfo").append("<asp:TemplateField><ItemTemplate>" + result[1].UserName +
               "</ItemTemplate></asp:TemplateField><asp:TemplateField><ItemTemplate>" + result[1].ProviderName + 
"</ItemTemplate></asp:TemplateField>");
        alert(result[1].UserName);
    }

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

The curious conduct of wild safari creatures

I have been using JavaScript to split my ePub chapter into pages by wrapping the code with new divs that represent separate pages. I have also created CSS styles for these new divs. Everything works perfectly when the file has a filename extension of &apos ...

The integer data type is not functioning properly when used as a parameter

I am currently working with a GridView that has a check box as an Item Template. I am updating the GridView whenever the check box is changed. Below is the code for my GridView: <Columns> <telerik:GridTemplateColumn> <ItemTemplate&g ...

Obtaining access to a class variable within a setTimeout function

I am working on a JavaScript class that needs to publish events at regular intervals. The current code I have is as follows: class TimerService { constructor(BroadcastService) { this.Broadcast = BroadcastService; this.timeout; this.warningTi ...

Click event not triggering the doSomething() function in $scope, but works with onclick event for the same

The current controller being used is: angular.module('app.PostView', []) .controller('PostViewCtrl', function($scope, $http, Constants) { $scope.posts = []; $scope.doSomething = function(){ console.log("in doSo ...

Sending Location Data From JavaScript to PHP via Cookies

I encountered an issue while attempting to send Geolocation coordinates from JavaScript to PHP using Cookies. The error message I am receiving is: Notice: Undefined index: data in /Applications/XAMPP/xamppfiles/htdocs/samepage.php on line 24 The file name ...

Retrieving specific data from nested arrays in Vue.js

I am currently working on Vue.js template development and facing an issue with filtering nested data in a faq section. When I try to add a search bar, the nested data array returns all data without proper filtering. Dom <v-container> <v ...

Would this method be considered effective for discarding an SQL connection?

Just finished writing this code. I've been told by my senior that this is the best way to handle an open SQL connection. I wanted to double-check with the community here to ensure I'm following best practices. public bool SaveBulkpayment(List< ...

Transferring PHP array data into JavaScript array values

A PHP array structure is presented below. Array ( [0] => hal([[br,1],[cl,4]]) [1] => alk([[nc(1),1,2],[nc(1),3]]) ) I need to convert this array into JavaScript format like so: var hal=[["br",1],[cl,4]]; var alk=[[nc(1),1,2],[nc(1),3]]; In ...

In JavaScript, use regular expressions to replace every instance of a link with its corresponding href object (map link -> a href=link)

I am looking to replace the following text: "wjjghwkjghwkjgh https://www.google.com jhgkwjhgkwhgk https://youtube.com" with: "wjjghwkjghwkjgh <a href='https://www.google.com'>https://www.google.com</a> jhgkwjhgkwhgk <a href=&a ...

Can isolating scope functions through inheritance with $scope.$new bring new possibilities?

Is it possible to achieve the automatic attribute binding functionality of an isolate scope: scope : { someAttr: '@' } While also maintaining the transparent scope-->parentScope property access as shown in scope.$new(): $scope.foo = 'f ...

How to conceal a Card component using v-if in Vue.js?

Does anyone know how to hide the Card when the third element of the select box is selected? I am a new developer and would appreciate any help with this issue. Sorry for my lack of experience. <b-form-select v-model="InputRatingPlate.RatingP ...

Creating a dynamic traffic light display: A step-by-step guide

//traffic lights:red,yellow,green fill(trafficFirstLightColor) ellipse(315, 40, 20, 20) fill(trafficSecondLightColor) ellipse(315, 40 + 25 * 1, 20, 20) fill(trafficThirdLightColor) ellipse(315, 40 + 25 * 2, 20, 20) //if three ...

Struggling to retrieve data from AJAX call

I'm having trouble accessing the data returned from a GET AJAX call. The call is successfully retrieving the data, but I am unable to store it in a variable and use it. Although I understand that AJAX calls are asynchronous, I have experimented with ...

Experiencing difficulties when attempting to launch a React application and Express/Node.js backend on a shared port

I'm trying to set up my react front-end on localhost:5000, with API requests going to localhost:5000/api/some-path. After looking at similar questions, I've come to understand the following: Include a proxy in the package.json file Serve st ...

Revamping the Asp.net Action for Enhanced Performance

There's a recurring issue in many of my controller actions where I have code structured like this: var users = new List<SelectListItem>(); foreach(var user in userRepository.GetAll()) { var item = new SelectListItem { Text = user.FriendlyName, ...

Using setTimeout in a recursive function

Utilizing a recursive function to retrieve data from an external source, process it, and make additional calls if required. I require a method to pause prior to calling this external source numerous times in succession. How can I guarantee that I have co ...

Creating Child Components Dynamically using String Names in ReactJS

I've encountered an issue with dynamically rendering React Components within my DashboardInterface component. I have an array filled with string names of React Components, retrieved through an external mechanism. The goal is to render these Components ...

Retrieving data from dynamically generated input fields within a table

I currently have a table in my web application <form id="project-form"> <table id="project-table" class="table table-striped table-inverse table-responsive"> <caption>Projects</caption> ...

Is there a method in Node.js Express/Connect to manipulate the session to have an indefinite duration?

This is my current approach: app.use(express.session({ cookie:{domain:"."+settings.c.SITE_DOMAIN}, secret:'abc', store: redis_store, })); Upon checking my redis and running TTL se ...

Using React hooks to transfer an item from one array to another and remove it

export default function ShoppingCart() { const classes = useStyle(); const { productsList, filteredProductsList, setFilteredProductsList, setProductsList, } = useContext(productsContext); const [awaitingPaymentList, setAwaitingPaymentList] = us ...