SParc
SParc

Reputation: 1779

JavaScript runtime error: Invalid character

I am trying to access a ASP.NET handler from Ajax. I am passing data to it using an anchor tag and returning some test string. Following is the code:

Ajax Code

function incvote(topicid) {
    $.ajax({
        type: "POST",
        url: "WCAccess.ashx",
        data: JSON.stringify({ "desid": "topicid" }),
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (response) {
            return response.d;
        },
        error: function (xhr, ajaxOptions, thrownError) {

            alertify.error("Some error occured. Please try again.");
        },
        //async: true
    });

Handler Code

public class WCAccess : IHttpHandler {

    public void ProcessRequest (HttpContext context) {
        JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
        string jsonString = string.Empty;
        List<ArgsVals> argsList = new List<ArgsVals>();
        context.Request.InputStream.Position = 0;
        using (var inputStream = new System.IO.StreamReader(context.Request.InputStream))
        {
            jsonString = inputStream.ReadToEnd();
        }

        argsList = jsonSerializer.Deserialize<List<ArgsVals>>(jsonString);
        string resp = "";
        foreach (ArgsVals arg in argsList)
        {
            resp += arg.desid;
        }
        context.Response.Write("<text>"+resp+"</text>");
    }

    public bool IsReusable {
        get {
            return false;
        }
    }
    public class ArgsVals
    {
        public string desid { get; set; }
        //public int vtype { get; set; }
    }
}

Everything is working well until the control leaves context.Response.Write() statement. The data resp is getting the data nicely. But the problem is, Javascript is showing this error: JavaScript runtime error: Invalid character.

I searched SO and other websites. And I also tried this solution: Ajax request has invalid characters But nothing seem to work. Same error persists.

Upvotes: 0

Views: 8954

Answers (1)

vogomatix
vogomatix

Reputation: 5041

It looks like you are trying to return HTML/XML instead of JSON in your response.

context.Response.Write("<text>"+resp+"</text>");

Read the JSON webpages for the structure of the message you are meant to send back.

Upvotes: 1

Related Questions