1

I have a webmethod which will read the first line in a csv file to get the column titles then store each item in the list which I will return to the ajax call. This is the code:

[WebMethod]
    public static string getAvailableSensors()
    {
        List<string> sensors = new List<string>();
        try
        {
            string path = "C:\\.....\\TestData3.csv";
            string line;
            using (StreamReader sr = new StreamReader(path))
            {
                line = sr.ReadLine();
                sensors = line.Split(',').ToList();
            }
        }
        catch (Exception ex)
        {
            string error = ex.Message;
        }
        JavaScriptSerializer jss = new JavaScriptSerializer();
        string output = jss.Serialize(sensors);
        return output;
    }

This is what the data looks like when it is returned to the ajax call: enter image description here

This is what my ajax looks like :

$.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: "WebSockets.aspx/getAvailableSensors",
            async: false,
            data: "{ }", // send an empty object for calls with no parameters
            success: function (result) {
                debugger;
                data = result.d;
                for (var i in result.d) {
                    sensors.push(result.d[i]);
                }
            },
            error: function (xhr, ajaxOptions, thrownError) {
                alert("an error has occured: " + xhr.responseText);
            }
        });

but this only populates the array 1 character at a time which is not what I am trying to do.

I cannot figure out how to iterate the damn json so that I can populate my var sensors = new Array(); with the columns. ex( sensor[0] should be "Time", sensor[ 1 ] should be "X Accel LH" ) etc.

2
  • what is the error you are getting? Commented Mar 5, 2014 at 2:58
  • not getting an error. More like having a problem iterating the returned data correctly. Every single idea I've tried only returns 1 character at a time Commented Mar 5, 2014 at 2:59

3 Answers 3

4

First of all you need to make that string as an object. Use jQuery.parseJSON() to make it as object.

data=jQuery.parseJSON(data);

In your case, you can use the data like a string array

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much. You just saved a computer and a window. I haven't done this in a while so I forgot about jQuery.parseJSON
1

In your AJAX options you should set dataType: 'json' so that the response is automatically converted to JSON before being handed to your callback. This is probably what you expected the contentType to do, but in reality that sets the type of the content being sent, not what you expect to be returned. You might also want to apply a ScriptMethodAttribute and specify the result being returned is JSON - I believe this will set the Content-Type header so that jQuery can automatically detect the format in the absence of specifying it in your options.

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string getAvailableSensors()
{
   ...
}

JavaScript

$.ajax({
    type: "POST",
    dataType: "json", // <-- this
    contentType: "application/json; charset=utf-8",
    url: "WebSockets.aspx/getAvailableSensors",
    async: false,
    data: "{ }", // send an empty object for calls with no parameters
    success: function (result) {
        debugger;
        data = result.d;
        for (var i in result.d) {
            sensors.push(result.d[i]);
        }
    },
    error: function (xhr, ajaxOptions, thrownError) {
        alert("an error has occured: " + xhr.responseText);
    }
});

If you're using a newer version of jQuery you might want to look into replacing your success and error callbacks with the done and fail methods.

$.ajax({
        type: "POST",
        dataType: "json", // <-- this
        contentType: "application/json; charset=utf-8",
        url: "WebSockets.aspx/getAvailableSensors",
        async: false,
        data: "{ }", // send an empty object for calls with no parameters
 })
 .done(function(result) {
     debugger;
     data = result.d;
     for (var i in result.d) {
          sensors.push(result.d[i]);
     }
 })
 .fail(function(xhr, status, error) {
     alert("an error has occured: " + xhr.responseText);
 });

1 Comment

thank you for the detailed answer. I will definitely be remembering this for better implementation.
0

You could just return an IList<string> from your web method instead of serializing manually.

[WebMethod]
public static IList<string> getAvailableSensors()
{
    List<string> sensors = new List<string>();
    string path = "C:\\.....\\TestData3.csv";
    string line;
    using (StreamReader sr = new StreamReader(path))
    {
        line = sr.ReadLine();
        sensors = line.Split(',').ToList();
    }
    return sensors;
}

Also, your error handling is not exaclty correct. For the client, the operation succeeded even if there is an error on server side. I just removed you try catch to let the exception propagate to the client.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.