Learn how to retrieve a JsonResult in JavaScript from a web service using ASP.NET C#

I am having trouble reading JSON results in JavaScript as it keeps giving me an error. The error occurs specifically on var jsonObj = JSON.parse(msg);. The error being thrown is: Uncaught SyntaxError: Unexpected token o. Despite debugging the code, the Web service returns perfectly formatted JSON data; however, the error seems to be happening during the success event in the AJAX call. I would greatly appreciate any assistance on how to properly loop through this JSON object.

<script type="text/javascript">

        var ProductCategoryList;

        function callpageload() {
            $.ajax({
                type: "GET",
                url: "WebService1.asmx/GetCategoryList",
                contentType: "application/json; charset=utf-8",
                success: function (msg) {
                    var jsonObj = JSON.parse(msg);
                },
                error: function (msg) {

                }
            });
        }

</script>

Webservice snippet:

public string GetCategoryList()
{
    DataSet ds = Persistance.GetCategoryList();
    List<ProductCategories> prodlst = new List<ProductCategories>();
    if (ds.Tables[0].Rows.Count > 0)
    {
        for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
        {
            ProductCategories prod = new ProductCategories();
            prod.pid = ds.Tables[0].Rows[i]["pid"].ToString();
            prod.id = ds.Tables[0].Rows[i]["id"].ToString();
            prod.name = ds.Tables[0].Rows[i]["name"].ToString();
            prodlst.Add(prod);
        }
    }
    string json = JsonConvert.SerializeObject(prodlst.ToArray());
    return json;
}

Answer №1

Consider utilizing message.data and switching to POST method for enhanced security measures.

Answer №2

Hi there, I faced a similar issue before and it turned out that I was also using JQuery.

Instead of the code snippet you provided:

var jsonObj = JSON.parse(msg);

I would recommend trying this instead:

var jsonObj = $.parseJSON(msg);

Another thing to consider is setting a breakpoint in your C# code to ensure that there are no exceptions or errors while using Newtonsoft JSONconvert. Sometimes it may return an empty JSON string.

Feel free to let me know if this solution works for you.

In my case, the issue was caused by someone declaring var JSON={} somewhere in the code.

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

Utilizing Dynamic User Query Parameters in Mongoose for Enhanced $all Queries

Utilizing the schemas below to represent product specifications, const MoldSpecific = new Schema( { name: { en: String, ar: String, kr: String, }, values: [MoldValue.schema], }, { versionKey: false, } ); export de ...

Retrieving the result of a callback function within a nested function

I'm struggling with a function that needs to return a value. The value is located inside a callback function within the downloadOrders function. The problem I'm encountering is that "go" (logged in the post request) appears before "close" (logged ...

Are arrays being used in function parameters?

Can the following be achieved (or something similar): function a(foo, bar[x]){ //perform operations here } Appreciate it in advance. ...

Verify if the date string includes the day

Here's the scenario: a user clicks on one of two links, either 2012/10, or 2012/10/15. I am extracting the day value from the link to pass it onto an AJAX request that will change days on an archive page. Is using a regular expression like /\d{ ...

Why am I receiving an undefined value when I try to log the createdAnimal?

My main goal with this code is to successfully console.log(createdAnimal) and have the objectAnimal with specific parameters printed out. The following code snippet demonstrates the desired parameters: animalMaker('cat','flying',true); ...

jQuery trigger event when a DropDownList/SELECT item is selected

My current jQuery code filters a list of links on the page by firing when a link with a specified href is clicked. The id of the link determines which content remains visible. Here's an example: <script type="text/javascript"> $(docume ...

"Implement a queue system to assign individual tasks to each user using Node.js

One of the requirements is that the user should be able to perform multiple actions simultaneously by calling APIs, but some actions need to be executed sequentially for each user. For example, when a user clicks on the add item button and tries to clear ...

Unable to access webservice after uploading it to the server host

Please assist me with an issue related to a webservice: "The server encountered an error while processing the request. ---> An error occurred generating the XML document. ---> A circular reference was found during serialization of an object of type ...

Jquery and Ajax failing to function properly with multiple dropdown selections

I've been working on creating a functionality to have multiple dropdown menus using Bootstrap, JQuery, and AJAX. The goal is to select multiple countries from these dropdowns and store the selected values in CSV format in my database. Initially, I had ...

In what situations is it beneficial to utilize inherited scope, and when is it best to avoid it

Is it better to use inherited scope (i.e scope:true) when creating a directive, or is it more appropriate not to use it (i.e scope:false)? I grasp the distinction between scope types and their respective functionalities. However, I am uncertain about whic ...

Retrieving information from a server using AJAX and ASP.NET

Requesting assistance to identify my errors as a novice. I am completely lost at the moment. This is the code snippet in question: Service class with this get method: void OtvoriKonekciju() { uredjaj = new DBBL(); uredjaj.entity.Conn ...

Use knockout to bind an observableArray in the viewModel by connecting it to a separate JavaScript file that uses the getJson function

Utilizing Knockout JS and Durandal JS, my goal is to query the database through a separate Js file and then bind the retrieved data in the viewModel Js file. Within my index.js file, I have an observableArray named listData which is linked to the view (in ...

What is the best way to calculate the total of a field with matching Project and Employee names?

My task involves grouping data from an Array of objects by Project Name and Employee Name, whereby existing projects and employees have their hours added together. projects = [ { "project": { "id": 1, "name": "M ...

JavaScript objects and AJAX versus ASP MVC3 Model: A comparison of client-side and server

As someone who is still learning about MVC, I find myself a bit unsure about the best way to integrate MVC models with JavaScript objects and AJAX. For instance, in one of my applications, I have a calendar that displays user events stored in a database. ...

Javascript Circle Stroke

Exploring the concept of drawing a line through a circle Example image: https://i.sstatic.net/I8B60.jpg Check out my code snippet: https://codepen.io/ethan-horrigan/pen/OrRLXx var r = 200; var x1 = 800 / 2; var y1 = 540 / 2; var x = r * ...

Transmit and receive Json data but unable to interpret the response

I am working on an application that requires me to send JSON code through web requests. I am able to establish the connection and send and receive data using GET, POST, PUT, and DELETE methods. However, although I believe I am receiving JSON code in respon ...

What is the best way to retrieve the UTC value of a specific date and time within a particular time zone using JavaScript?

I want to create a Date object with a specific time: "Midnight in Los Angeles on Christmas 2011". Although I've used moment.js, which is good, and moment-timezone, which is even better, neither the default Date class nor moment constructors allow for ...

Issues with WordPress forms are causing frustration

Looking for some assistance here. I am in the process of creating a one-page WordPress theme and I am struggling with getting the contact form to submit without reloading the page. All my code is in the index.php file. The PHP code for form submission is ...

Angular: Enhance communication with controllers and directives

Currently, I am in the process of learning Angular. One interesting feature I have been working on is a directive that displays a select element. Whenever there is a change in this select element due to the ng-change event, a specific method defined in the ...

What is the best way to extract data from a table and transmit it to the server using AngularJS?

I'm attempting to extract all the content from a table in HTML. Is it possible to retrieve all rows from one side and send them in a post request to the server? I've been struggling to figure out how to do this. Do I need to bind each row using n ...