Error Detected: the C# script is not compatible with Javascript and is causing

I am facing an issue where I can successfully send information from the database, but I am unable to load the table on the page. When I check the data received with an alert, it appears to be in JSON format, but it still displays the wrong image on the webpage. How can this be rectified?

Below is my HTML code:

<!DOCTYPE html>
<script src="Scripts/knockout-3.4.2.js" type="text/javascript"></script>
<script src="Scripts/jquery-3.1.1.min.js"></script>
...

And this is my Backend Code snippet:

[WebMethod]
        public static string GonderUrunler()
        {
            denemeDBEntities db = new denemeDBEntities();
            var result = from d in db.urunler.ToList()
                         select d;
            string output = new JavaScriptSerializer().Serialize(result);
            return output;
        }

Answer №1

To ensure that your ajax request works asynchronously, it is imperative to use a callback function. For more information on this topic, refer to this document.

 $(document).ready(function () {

      function functionViewModel(callback) {
            $.ajax({
                type: "POST",
                url: "KnockoutGrid2.aspx/GonderUrunler",
                data: "{}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (msg) {
                  callback({friends: ko.observableArray(msg.d)});
                }
            });
    };

    functionViewModel(function(response){
       ko.applyBindings(response.friends)
    });
});

Answer №2

Are you aware if the variable 'friends' is actually defined and is of type array? It appears that in your foreach template, you are referencing it. Knockout seems to be having trouble loading the array...

<tbody data-bind="foreach:friends">

Answer №3

When you receive a JSON-formatted string from the WebMethod, it must be deserialized in your JS code to work with the data within. This can be achieved using JSON.parse:

success: function (msg) {
  var data = JSON.parse(msg);
  console.log(data[0].id);
  console.log(data[0].name);
}

It's important to remember that data will be an array, so if you want to access all the information within it, a loop will be necessary. Additionally, when debugging, always rely on console.log or console.dir; using alert() can lead to unreliable type coercion.

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

Obtaining select options in jQuery by utilizing the $(this) selector

Looking for a way to loop through and log each option available in a select dropdown box, but struggling with how to use $(this). This is the code I have so far: $('select').each(function(){ $(this).find('options').each(function() ...

arranging data in html table columns using angular 2

I am facing a challenge where I require each column of a table to be sorted in ascending order every time it is clicked. The sorting logic implemented is a standard JavaScript method. While this method works well in most scenarios, it encounters issues whe ...

Assign a value using the select component from Material UI

I just finished creating a dropdown menu const [selectedValue, setSelectedValue] = useState(''); const handleSelectionChange = (e: any) => { //setSelectedValue(e) console.log('value', selectedValue) } .... <Fo ...

Adjusting editable property in FullCalendar during script execution

Currently, I am working with Angular JS and fullCalendar to customize the functionality of my calendar. My goal is to change the editable property of the calendar when a button is clicked. Although it seems like a straightforward task, I am facing difficul ...

Having trouble with jest mocking a function - it's not functioning as expected

I decided to create a simple test using jest to simulate a date change function. Here is the code snippet: import React from 'react'; import '@testing-library/jest-dom'; import { render, screen } from '@testing-library/react' ...

Using TypeScript's reference function within an HTML document

It feels like ages since my early days of web development. Back when I first started coding, we would reference a script using a <script> tag: <html> <head> <script src="lealet.js"></script> <!-- I know the path isn´t c ...

Avoiding an event from spreading in Angular

I am working on a navigation setup that looks like this: <a (click)="onCustomParameters()"> <app-custom-start-card></app-custom-start-card> </a> When the user clicks on the app-custom-start-card, the onCustomParame ...

Retrieve the chosen option index using AngularJS

It is common knowledge that a select list can have multiple options, each starting from [0]. For example: [0]<option>E.U</option> [1]<option>India</option> [2]<option>Peru</option> In my Angular application, I am using ...

Create a Bootstrap modal that includes a checkbox option to prevent it from appearing again in

I am attempting to display a bootstrap modal upon body load based on a value retrieved from a MySQL database. The bootstrap modal is included in the body and shown successfully depending on the database value using the following code snippet: $results ...

The issue of why iterating over an array of objects does not function properly in React JS

P.S: I have made some modifications to the code below. Extracting the doctor's value from JSON data, updating the state, and then mapping it to print out the values. Initially, there is only one doctor, but in the future, there could be more than one ...

Generate a custom website using React to display multiple copies of a single item dynamically

As a newcomer to React and web development, I've been pondering the possibility of creating dynamic webpages. Let's say I have a .json file containing information about various soccer leagues, structured like this: "api": { "results": 1376, ...

From Jquery to PHP to MySQL: Creating dynamic forms with variable fields

I am facing an issue with a multi-page form that uses multiple MySQL tables to store entered values. One of the pages contains a form that should allow users to click a + button to add extra lines for additional information. The user can add any number of ...

Harnessing the power of JavaScript functions to display an image when clicked

Looking for help with making an image appear when clicking on one of three images? Despite trying different approaches, the desired result is still not achieved. I'm aware of using if else statements but exploring other methods. Any insights on what m ...

Is it possible to reduce a field value in firestore after successfully submitting a form?

I have a variety of items retrieved from firestore: availability : true stocks: 100 item: item1 https://i.stack.imgur.com/hrfDu.png I am interested in reducing the stocks after submitting a form. I used the where() method to check if the selected item m ...

Create an image on a node's backdrop using a library of graph theory/networking techniques

I have a set of data that I need to visually represent as a graph on a web browser. While creating the graph itself is not an issue, I am looking to dynamically draw unique icons for each node. These icons are specific to the characteristics of each node ...

Retrieve a parameter from jQuery and pass it to a JavaScript function

Currently, I am working with Puppeteer and encountering an issue where the "selector" is undefined when calling this function. async function checkIfTextIsPresent(page, selector){ let myElement = await page.evaluate(() => document.querySelector(sel ...

What is the procedure for sending a chat message with an attachment?

I could really use some help with the logic of my PHP chat messaging application. Currently, users can send messages successfully but I am struggling to implement a feature that allows file attachments to be sent along with messages. The process should inv ...

use element ui tree and vue to filter files according to selected folder

Utilizing the element UI treeview to showcase folders. Each folder or its child folder contains files that need to be displayed based on folder selection. While it's easy to filter and list out these files in a normal list, I am facing challenges with ...

Modify the length of an array using a number input field

Currently, I am working with an array that contains objects and I want to dynamically change the number of objects in this array based on user input from a number type input box. Whenever the number in the input box is increased, I need to increase the len ...

What's the best way to retrieve the id or index of a card within a list?

Struggling to fetch the id's of documents retrieved from a MongoDB database and displayed on React and Material-Ui cards. Tried logging id in functions and APIs, but receiving 'undefined' or metadata from the delete function. Delete functi ...