Internal Server Error 500: Issue with Ajax/JavaScript

I have reviewed some previous posts, but unfortunately, they did not provide the help I need. When my program runs and I click on a button to trigger a JavaScript function, nothing happens - there is no response. In the Chrome debugger under the network tab, I see a URL highlighted in red:

http://wms-wsdl.company.net/mobile.asmx/ContactGet?searchField=test&office=97&person=119&user=531&organization=14

Clicking on this link results in a red circle with a 500 internal server error. Examining the response, I see:

{"Message":"Invalid JSON primitive: test.","StackTrace":"   at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializePrimitiveObject()\r\n   at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeInternal(Int32 depth)\r\n   at System.Web.Script.Serialization.JavaScriptObjectDeserializer.BasicDeserialize(String input, Int32 depthLimit, JavaScriptSerializer serializer)\r\n   at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize(JavaScriptSerializer serializer, String input, Type type, Int32 depthLimit)\r\n   at System.Web.Script.Services.RestHandler.GetRawParamsFromGetRequest(HttpContext context, JavaScriptSerializer serializer, WebServiceMethodData methodData)\r\n   at System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context, WebServiceMethodData methodData)","ExceptionType":"System.ArgumentException"}

I am unable to decipher the meaning of this response.

When I double-click on the link, it displays all the data that should be inserted into a list view (the data is XML) such as

<string xmlns="http://company.net/">[{ "Name": "Myar", "Surname": "Tester", "Mobile": "080000000", "Email": "" ......}, etc

The JavaScript function I'm using is as follows:

function initContactView()
{
    alert("ContactView start test")
     var txtSearch = $("#searchTextField").val();
$.ajax({
        type: "GET",
        dataType:"json", 
        contentType: "application/json; charset=utf-8",
        crossDomain: true,
        url: "http://dsf-wsdl.company.net/mobile.asmx/ContactGet",
        data: "searchField="+txtSearch+"&office="+localStorage.getItem("office")+"&person="+localStorage.getItem("person")+"&user="+localStorage.getItem("user")+"&organization="+localStorage.getItem("organization"),
        success:successContact,
        failure: function (msg) {
            console.log(msg);
            alert(msg)
        }
    });  
    alert("ContactView End Test");
}


function successContact(data) {
    alert("Success Start Test");
    window.location = "#contactsview";
    $("#lstView_contacts").kendoMobileListView({
        dataSource: JSON.parse(data.d),
        template: $("#lstView_contact_Template").html(),
        endlessScroll: true,
        scrollThreshold: 8
    });
    alert("Success Start Test");    
}

searchTextField is retrieved from my HTML textbox.

It seems strange that despite getting the expected data, an error still occurs. The web service I am utilizing is a JSON webservice. Both alerts are triggered, but I suspect it goes into the failure state.

The response I receive in the debugger is:

<string xmlns="http://company.net/">[
  {
    "Name": "Myar",
    "Surname": "Tester",
    "Mobile": "080000000",
    "Email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3c48594f487c48594f48125f5351">[email protected]</a>"
  }]</string

This is how my web service looks:

<WebMethod()> _
    <ScriptMethod(ResponseFormat:=ResponseFormat.Json, UseHttpGet:=True)> _
    Public Function ContactGet(ByVal searchField As String, ByVal office As String, ByVal person As String, ByVal user As String, ByVal organization As String) As String

        Dim objSearch As New ArrayList
        Dim objSearching As New Search
        Dim intResult As Integer

        Try
            'Test String
            intResult = objSearching.SearchByKeyword(searchField, person, office, organization, user, company.ETMyProperty.Search.enmSearchType.enmContact, objSearch)

            Dim objContact As New Person
            Dim dt As New DataTable("Contacts")

            Dim col_Name As New DataColumn("Name", GetType(String))
            dt.Columns.Add(col_Name)

            Dim col_Mobile As New DataColumn("Surname", GetType(String))
            dt.Columns.Add(col_Mobile)

            Dim col_Office As New DataColumn("Mobile", GetType(String))
            dt.Columns.Add(col_Office)

            Dim col_Category As New DataColumn("Email", GetType(String))
            dt.Columns.Add(col_Category)

            Dim dr As DataRow

            For i = 0 To objSearch.Count - 1
                dr = dt.NewRow()
                dr("Name") = DirectCast(objSearch(i), company.ETMyProperty.Search).Return2
                dr("Surname") = DirectCast(objSearch(i), company.ETMyProperty.Search).Return3
                dr("Mobile") = DirectCast(objSearch(i), company.ETMyProperty.Search).Return6
                dr("Email") = DirectCast(objSearch(i), company.ETMyProperty.Search).Return7
                dt.Rows.Add(dr)
            Next

            Dim serializer As New JavaScriptSerializer()
            Dim rows As New List(Of Dictionary(Of String, Object))()
            Dim row As Dictionary(Of String, Object) = Nothing

            'serialize dt row to json output
            For Each drow As DataRow In dt.Rows
                row = New Dictionary(Of String, Object)()
                For Each col As DataColumn In dt.Columns
                    row.Add(col.ColumnName, dr(col))
                Next
                rows.Add(row)
            Next

            Dim str_json = JsonConvert.SerializeObject(dt, Formatting.Indented)

            Return str_json

        Catch ex As Exception
            Return Nothing
        End Try
    End Function

I've been tackling this issue for a few days now without finding a solution. Any advice would be greatly appreciated.

Answer №1

According to the jQuery documentation, it is recommended to use error: function() {...}, instead of failure. The success key should have a value that is a function, not a variable. An example would be success: successContact(),

For effective debugging, it is crucial to determine whether your ajax callback triggers success or error. If success is not being called, it could be due to the absence of an application/json content-type header in the response, or errors in the JSON structure.

Answer №2

To ensure the successful execution of your GET request, you must either remove or specify the contentType as:

application/x-www-form-urlencoded; charset=UTF-8

function initContactView()
{
    alert("ContactView start test")
     var txtSearch = $("#searchTextField").val();
$.ajax({
        type: "GET",
        dataType:"json", 
        crossDomain: true,
        url: "http://dsf-wsdl.company.net/mobile.asmx/ContactGet",
        data: "searchField="+txtSearch+"&office="+localStorage.getItem("office")+"&person="+localStorage.getItem("person")+"&user="+localStorage.getItem("user")+"&organization="+localStorage.getItem("organization"),
        success:function(data) {successContact(data);},
        failure: function(msg) {
            console.log(msg);
            alert(msg)
        }
    });  
    alert("ContactView End Test");
}

It is crucial to determine whether the error occurs during the Request Begin on the ASMX or within the ASMX Response.

For more insights on handling GET Requests, refer to: Do I need a content type for http get requests?

Additionally, configure your webservice to return JSON. The current response format is not in json. Adjust the dataType to handle ONLY json by modifying your WebMethod.

[WebMethod]
[ScriptMethod(UseHttpGet=true ,ResponseFormat = ResponseFormat.Json)]
public void HelloWorld()
{
    Context.Response.Clear();
    Context.Response.ContentType = "application/json";
    Context.Response.Write("Hello World");
    //return "Hello World";
}

Note: When utilizing webmethods, there's no need to manually convert the datatable to json as the webservice performs it automatically. Update your code snippet like so:

<WebMethod()> _
    <ScriptMethod(ResponseFormat:=ResponseFormat.Json, UseHttpGet:=True)> _
    Public Function ContactGet(ByVal Parameters....) As DataTable

Finally, below is an example showcasing effective .net serialization techniques:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Script.Services;
using System.Data;
using System.Collections;
using System.Linq;

/// <summary>
/// Summary description for WebService
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
[System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService {

    public WebService () {

        //Uncomment the following line if using designed components 
        //InitializeComponent(); 
    }

    [WebMethod]
    [ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
    public List<Dictionary<string, object>> HelloWorld()
    {
        DataTable TestTable = new DataTable();
        TestTable.Columns.Add("Name");
        TestTable.Columns.Add("Id");
        DataRow Row = TestTable.NewRow();
        Row["Name"] = "James";
        Row["Id"] = 0;
        TestTable.Rows.Add(Row);

        return RowsToDictionary(TestTable);
    }


    private static List<Dictionary<string, object>> RowsToDictionary(DataTable table)
    {
        List<Dictionary<string, object>> objs =
            new List<Dictionary<string, object>>();
        foreach (DataRow dr in table.Rows)
        {
            Dictionary<string, object> drow = new Dictionary<string, object>();
            for (int i = 0; i < table.Columns.Count; i++)
            {
                drow.Add(table.Columns[i].ColumnName, dr[i]);
            }
            objs.Add(drow);
        }

        return objs;
    }

}

For alternative serializers, consider exploring resources like . An ASHX handler may provide a better approach for returning JSON than an ASMX service.

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

Transition not influencing the scale property when activating a class

My modal is not scaling in and out properly when I toggle the 'active' class. It either fully scales out or scales in without any transition. Example: const openPopupButtons = document.querySelectorAll('[data-popup-target]'); const ...

The message "jest command not recognized" appears

My test file looks like this: (I am using create-react-app) import React from 'react'; import ReactDOM from 'react-dom'; import App from './components/Calculator'; import { getAction, getResult } from './actions/' ...

The jQuery function .val()/.text() is unable to retrieve information from a particular section of HTML

Implementing HandlebarsJS with PHP and Yii to generate a page. Here is a snippet of the html/handlebars code on the page {{#if embed_link}} <p class='f_hidden_p'> <a href='{{embed_link}}'> {{ ...

Issue: (SystemJS) Unable to find solutions for all parameters in $WebSocket: ([object Object], [object Object], ?)

Upon running the code snippet below, an error is thrown: Error: (SystemJS) Can't resolve all parameters for $WebSocket: ([object Object], [object Object], ?). app.component.ts import { Component } from '@angular/core'; import {$WebSocket} ...

Can you show me how to condense this using the ternary operator?

Although I don't necessarily have to refactor this code, I am intrigued by the idea of doing so. handleError: ({ error, email, password }, props) => authError => { if (email === "" || password === "") { return { error: `Plea ...

Using QuerySelector with Angular Directive will throw an error as it is not a recognized

When creating a directive that integrates a jQuery carousel, I want to hide it at the beginning until it is fully ready. Here's the directive code snippet: return { restrict: 'E', replace: true, scope: true, templateUrl: ...

Load a JSON file into the app.js of your project

Could someone please help me figure out how to successfully load a JSON file into my project's app.js? I've tried using the following code snippet: var j = require('./JSON1'); However, it didn't work as expected. My goal is to la ...

Rendering a js.erb partial from one js.erb file to another using Rails and Jquery

Currently, I am facing a situation where I have duplicate js.erb code in the ajax responses of different models. To avoid this redundancy, I am looking to refactor the duplicate js.erb code by passing arguments into a js.erb partial. Can anyone guide me o ...

Using ExtJS to populate a panel with data from various sources

I am currently working with an Ext.grid.GridPanel that is connected to a Ext.data.JsonStore for data and Ext.grid.ColumnModel for grid specifications. Out of the 10 columns in my grid, 9 are being populated by the json store without any issues. However, I ...

Rendering React.js components as children of DOM elements

Trying my hand at creating a custom Map component includes the task of designing a unique Map Annotation. Here's an example of how a MapAnnotation component appears in the render function: <MapAnnotation title='Annotation' latitude={ 12.3 ...

Discovering the corresponding elements within an array of objects

Within my array of objects, I am performing a search let arr = [ { name:"string 1", arrayWithvalue:"1,2", other: "that" }, { name:"string 2", arrayWithvalue:"2", other: "that" }, { name:"string 2", arrayWithvalue:"2,3", other: "that" }, ...

Guide to configuring browserify

After installing the modules (browserify, react, reactify), I attempted to process a JSX file using browserify. var React = require("react"); var App = React.createClass({ render: function () { return <h1>111</h1> } }); React ...

The C# [WebMethod] will not trigger if the Content-Type "application/Json" is missing

After creating a C# WebMethod, I was able to successfully call it using Ajax, angular, and Postman when adding the header Content-Type: 'application/Json'. Here is an example of the HTTP request that worked: $http({ url: 'default.aspx/G ...

Combining keys in Pandas when grouping by more than one column

I have a complex grouping structure based on three keys: key1, key2, key3. To calculate the sum of column c1 for different combinations of these keys, I currently have the sums stored in separate dataframes (sum_k1, sum_k1k2, sum_k1k2k3). I now need to mer ...

Using `req.body` to retrieve form data in express.js is not permitted

I have a form on my website that collects user data using input and selection fields. I'm looking to use an AJAX call triggered by the submit button's handler to save this data on the server. Below is an outline of the code: Client side: xhr.o ...

Add color to the cells within the table

I need help with dynamically adding colors to my table based on the results. If the result is 'UnSuccessfull', the color should be 'red'. If the result is 'Successful', the color should be 'green'. The challenge I a ...

What is the best way to specify the CSS :hover state within a jQuery selector?

I am trying to change the background color of a div element when hovered using jQuery, but for some reason the following code is not working as expected: $(".myclass:hover div").css("background-color","red"); Can someone provide guidance on how to achiev ...

Exploring the use of barcodes with node.js

Having some issues with generating a barcode using a barcode module from NPMJS called npm i barcode. I am getting an error message res is not defined even after following the instructions. Can someone please guide me in the right direction? Here is my code ...

Ways to present a Nuxt page as a reply from an express route

How can I achieve a similar functionality to res.render on a Nuxt page? The project is using the nuxt-express template, which combines Nuxt and Expressjs. Although Nuxt provides nuxt.render(req, res) and nuxt.renderRoute, I am having trouble making it wo ...

An issue occurred during the construction of an angular project: The Tuple type '[]' with a length of '0' does not contain any elements at index '0'

When I run the command ng build --prod, I encounter the following error: ERROR in src/app/inventory/inv-parts-main-table/dialog-component/dialog-component.component.html(5,16): Tuple type '[]' of length '0' has no element at index &apo ...