locked
JSON string not returning to jquery RRS feed

  • Question

  • User219039814 posted

    I have this following json values being generated dynamically through a web method

    [{"AuditoriumName":"XYZ","BookingStartDate":"26-06-2018 00:00:00","BookingEndDate":"26-06-2018 00:00:00","Id":null},{"AuditoriumName":"ABC","BookingStartDate":"27-06-2018 00:00:00","BookingEndDate":"27-06-2018 00:00:00","Id":null}]

    but these values are not being passed to JQUERY..

    events: function (start, end, callback) {
    $.ajax({
    type: "POST",
    url: "ajaxpg.aspx/TestOnWebService",

    success: function (data) {

    var events = [];

    var obj = $.parseJSON(data.d);              // this is showing error




    $(obj.event).each(function () {
    events.push({
    title: $(this).attr('AuditoriumName'),
    start: $(this).attr('BookingStartDate'),
    end: $(this).attr('BookingEndDate'),
    // id: $(this).attr('id')
    });
    });
    //callback(events);
    callback && callback(events);


    },
    error: function(xhr, status, error) {
    alert(xhr.responseText + "iam in error");
    }

    Tuesday, June 26, 2018 6:22 AM

Answers

  • User753101303 posted

    This is expected. Stringify is to convert an object to a json string so obj is really a string.

    What if you try to work with the object you seems to have already as suggested earlier ? (ie list[0].AuditoriumName, in your code obj is the stringified object while in one of the helper code, it is directly the object you get from your service which is named list in your own code).

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, June 26, 2018 10:41 AM
  • User-1171043462 posted

    var obj = JSON.stringify(list);

    This is wrong. Remove this. There is no need to do so.

    and simply try

    alert(list[0].AuditoriumName);
    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, June 26, 2018 10:44 AM
  • User-1171043462 posted

    Try

    $(obj.event).each(function () {
    events.push({
    title: this.AuditoriumName,
    start: this.BookingStartDate,
    end: this.BookingEndDate

    });
    });

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, June 26, 2018 2:07 PM
  • User753101303 posted

    Hi,

    If using https://fullcalendar.io/docs/events-array it seems you could just pass an array (iwith start, end and title porperties) and that you, could even just provide the url for a json feed.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, June 26, 2018 3:02 PM
  • User-330142929 posted

    Hi Vijaylakshmi,

    According to your description and code above, I think you may forget to assign the return type you want.

    In addition, if you have passed Json string to frontend from backend, there is no need to use the Json.stringify function.

    I have made a demo, wish it is useful to you. My webservice is asmx, so the function is not static.

    Please note the comments in my code.

    Script.

    <script src="Scripts/jquery-3.3.1.js"></script>
        <script>
            $(function () {
                $.ajax({
                    url: "WebService1.asmx/GetData",
                    type: "GET",
                    data: '',
                    datatype: 'json',
                    contentType: 'application/json',
                    success: function (data) {
                        var result = eval("(" + data.d + ")");
                        console.log(result);
     		//They have the same effect.
                        var obj = $.parseJSON(data.d);
                        console.log(obj);
                        $.each(result, function (i, e) {
                            $("#div1").append("ID:"+e.Id+" Name:"+e.Name+" Price:"+e.Price);
                            $("#div1").append("<br>");
                        })
                    }
                })
            })
        </script>

    Aspx.

            <div id="div1">
            </div>

    WebService1.asmx

    [WebService(Namespace = "http://tempuri.org/")]
        [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
        [System.ComponentModel.ToolboxItem(false)]
        [System.Web.Script.Services.ScriptService]
        public class WebService1 : System.Web.Services.WebService
        {
     
            [WebMethod]
            [ScriptMethod(UseHttpGet =true)]
            public string GetData()
            {
                List<Product> products = new List<Product>()
                {
                    new Product{Id=1,Name="Apple",Price=10}
                    ,new Product{Id=2,Name="Pear",Price=12}
                    ,new Product{Id=3,Name="Peach",Price=11}
                };
                string json1 = new JavaScriptSerializer().Serialize(products);
                return json1;
            }
        }
        public class Product
        {
            public int Id { get; set; }
            public string Name { get; set; }
            public int Price { get; set; }
        }

    How it works.

    Results.

    Please feel free to let me know if you have any question.

    Best Regards,

    Abraham

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, June 27, 2018 3:27 AM
  • User-1171043462 posted

    Have you tried what I suggested?

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, June 27, 2018 7:05 AM
  • User753101303 posted

    Try perhaps :

    $.each(obj,function (index,value) {
     events.push({
     title: value.AuditoriumName,
     start: value.BookingStartDate,
     end: value.BookingEndDate
    });

    It seems it could be a confusion between $.each and $(selector).each. Try http://api.jquery.com/jQuery.each/

    something is failing

    IMO it is best to always start from the real bad thing that happens rather than trying to read the code and wondering about how it could fail. Don't you have an error message on F12 Console ?

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, June 27, 2018 11:30 AM

All replies

  • User-1171043462 posted

    add

    debugger;

    and in IE check what is error and value of data and data.d

    Tuesday, June 26, 2018 8:00 AM
  • User753101303 posted

    Hi,

    "showing error". Instead always tell which error you have so that we can start from an actual errror rather than trying to guess (even for simple code you can have multiple errors). You checked what you have in data.d ? (and maybe data ?)

    From the server side you return a string rather than letting ASP.NET to serialize this for you ?

    Tuesday, June 26, 2018 8:05 AM
  • User219039814 posted

    the error is ... "undefined"

    Tuesday, June 26, 2018 8:31 AM
  • User219039814 posted

    If i try to print console.log(obj).. it shows "undefined"

    that is the error.

    When i run the web method in the ajaxpg.aspx the json is getting generated.

    But it is not passing in the other webform where the json values are required to populate the database.

    Tuesday, June 26, 2018 8:35 AM
  • User632428103 posted

    Hello all,

    @vijaylakshmi =>i think it's a page method locate in a aspx page is it right ? be sure that is on static and enable webmethod as tag into the method as this 

     [WebMethod]
            public static returningType MethodName(parameterName ..)

    copy paste the code here ..

    Tuesday, June 26, 2018 8:43 AM
  • User219039814 posted

    public static String TestOnWebService()

    {

    Connection con = new Connection();
    SqlConnection conn = new SqlConnection();


    conn = con.getConnection();
    conn.Open();
    String query = "SELECT AuditoriumName,BookingStartDate,BookingEndDate FROM booking";

    SqlCommand cmd = new SqlCommand(query, conn);

    SqlDataReader reader = cmd.ExecuteReader();

    string myJsonString = "";
    List<object> myList = new List<object>();


    if (reader.HasRows)
    {
    var an = reader.GetOrdinal("AuditoriumName");

    var bstartdate = reader.GetOrdinal("BookingStartDate");
    var benddate = reader.GetOrdinal("BookingEndDate");


    while (reader.Read())
    {

    var audiname = reader.GetValue(an).ToString();

    var bstartdate1 = reader.GetValue(bstartdate).ToString();
    var benddate1 = reader.GetValue(benddate).ToString();

    // Convert Implicity typed var to Date Time
    DateTime RealStartDate = Convert.ToDateTime(bstartdate1);
    DateTime RealEndDate = Convert.ToDateTime(benddate1);
    timetable t_table = new timetable(audiname, bstartdate1, benddate1);
    // timetable t_table = new timetable(audiname, bdate1, bfromtime1, btotime1, bstartdate1, benddate1, bstatus1);
    // timetable t_table = new timetable("XYZ", "26-06-2018", "26-06-2018");

    myList.Add(t_table);


    }


    myJsonString = (new JavaScriptSerializer()).Serialize(myList);

    conn.Close();
    }

    return myJsonString;

    }

    }

    Tuesday, June 26, 2018 8:45 AM
  • User219039814 posted

    I posted my webmethod. It is static, but still cant figure out what is going on.

    Tuesday, June 26, 2018 8:46 AM
  • User219039814 posted

    My json values look like this..

    [{"AuditoriumName":"ABC","BookingStartDate":"27-06-2018 00:00:00","BookingEndDate":"27-06-2018 00:00:00","Id":null}]

    i used the following code

    var list = result.d;
    var obj = JSON.stringify(list);
    alert(obj);

    I returened a list from my web method.

    Now how do i access my obj's values

    Tuesday, June 26, 2018 9:48 AM
  • User753101303 posted

    And what if you check the value of result rather than result.d ?

    Your method explicitely returns a string while ASP.NET is able to handle serialization/deserialization for you which might be the difference (AFAIK .d is used by ASP.NET when a list is returned from the ASP.NET perspective currently you just return a single string).

    Make this work first. Then consider maybe to simplify (ie your code doesn't have to handle serialization/deserialization, ASP.NET does this already).

    Edit: or the problem changed ??? It seems you are now telling that you are now converting your list to a string successfully and now Wonder how to access this list ???? You should work with objects rather than strings. alert(list[0].AuditoriumName); doesn't show the expected value ?

    Tuesday, June 26, 2018 9:57 AM
  • User219039814 posted

    Sir,

    After browsing the net, i changed my code to returning a list value from the wen method. So the first problem is kind of solved.

    So when i execute the following code

    var list = result.d;
    var obj = JSON.stringify(list);
    alert(list[0].AuditoriumName);      // prints the ABC which is the Auditorium Name in the database.
     alert(obj);   // this prints the following JSON values given below.

    [{"AuditoriumName":"ABC","BookingStartDate":"27-06-2018 00:00:00","BookingEndDate":"27-06-2018 00:00:00","Id":null}]

    The values of obj are in square brackets, So i suppose the values are actually one single array object??

    Can you please help. I am working on this for past 48 hrs..

    Tuesday, June 26, 2018 10:11 AM
  • User-1171043462 posted

    Since it is an Array you will get value this way

    alert(obj[0].AuditoriumName);
    alert(obj[0].BookingStartDate);
    alert(obj[0].BookingEndDate);

    You can also loop

    for(var i = 0;i<obj.length;i++)
    {
        alert(obj[i].AuditoriumName);
       alert(obj[i].BookingStartDate);
       alert(obj[i].BookingEndDate);
    }

    Tuesday, June 26, 2018 10:17 AM
  • User219039814 posted

    Sir,

    I already tried it..

    It is coming as Undefined.

    Infact i changed my code, after seeing your posts wherein you returned the list value and later converted to the JSON.

    After which i got the JSON values , but i am not able to access the indiviual values. 

    alert(obj[0].AuditoriumName);
    alert(obj[0].BookingStartDate);
    alert(obj[0].BookingEndDate);

    gives undefined

    Tuesday, June 26, 2018 10:21 AM
  • User219039814 posted

    var list = result.d;
    var obj = JSON.stringify(list);

    alert(obj);  // show the JSON values but in sqaure brackets.

    alert(obj[0].AuditoriumName);  // shows undefined
    Tuesday, June 26, 2018 10:23 AM
  • User219039814 posted

    If i do this..

    alert(obj.length) // this shows 116 as output.

    That means it is taking every single character as an array element.

    Tuesday, June 26, 2018 10:28 AM
  • User753101303 posted

    This is expected. Stringify is to convert an object to a json string so obj is really a string.

    What if you try to work with the object you seems to have already as suggested earlier ? (ie list[0].AuditoriumName, in your code obj is the stringified object while in one of the helper code, it is directly the object you get from your service which is named list in your own code).

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, June 26, 2018 10:41 AM
  • User219039814 posted

    Ok,

    I am working with fullcalendar sir, so basically i need to populate the calendar with the events in the database.

    If i can work with the list can you tell how to modify the folllwing code 


     $(obj.event).each(function () {
     events.push({
     title: $(this).attr('AuditoriumName'),
     start: $(this).attr('BookingStartDate'),
     end: $(this).attr('BookingEndDate'),

     });
     });

    Tuesday, June 26, 2018 10:43 AM
  • User-1171043462 posted

    var obj = JSON.stringify(list);

    This is wrong. Remove this. There is no need to do so.

    and simply try

    alert(list[0].AuditoriumName);
    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, June 26, 2018 10:44 AM
  • User219039814 posted

    Yes sir, 

    I realized it. 

    if i use the list values directly then how do i bind the fullcaledar with list values in the events function


     $(obj.event).each(function () {
     events.push({
     title: $(this).attr('AuditoriumName'),
     start: $(this).attr('BookingStartDate'),
     end: $(this).attr('BookingEndDate'),

     });
     });

    Tuesday, June 26, 2018 10:48 AM
  • User-1171043462 posted

    Try

    $(obj.event).each(function () {
    events.push({
    title: this.AuditoriumName,
    start: this.BookingStartDate,
    end: this.BookingEndDate

    });
    });

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, June 26, 2018 2:07 PM
  • User753101303 posted

    Hi,

    If using https://fullcalendar.io/docs/events-array it seems you could just pass an array (iwith start, end and title porperties) and that you, could even just provide the url for a json feed.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, June 26, 2018 3:02 PM
  • User-330142929 posted

    Hi Vijaylakshmi,

    According to your description and code above, I think you may forget to assign the return type you want.

    In addition, if you have passed Json string to frontend from backend, there is no need to use the Json.stringify function.

    I have made a demo, wish it is useful to you. My webservice is asmx, so the function is not static.

    Please note the comments in my code.

    Script.

    <script src="Scripts/jquery-3.3.1.js"></script>
        <script>
            $(function () {
                $.ajax({
                    url: "WebService1.asmx/GetData",
                    type: "GET",
                    data: '',
                    datatype: 'json',
                    contentType: 'application/json',
                    success: function (data) {
                        var result = eval("(" + data.d + ")");
                        console.log(result);
     		//They have the same effect.
                        var obj = $.parseJSON(data.d);
                        console.log(obj);
                        $.each(result, function (i, e) {
                            $("#div1").append("ID:"+e.Id+" Name:"+e.Name+" Price:"+e.Price);
                            $("#div1").append("<br>");
                        })
                    }
                })
            })
        </script>

    Aspx.

            <div id="div1">
            </div>

    WebService1.asmx

    [WebService(Namespace = "http://tempuri.org/")]
        [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
        [System.ComponentModel.ToolboxItem(false)]
        [System.Web.Script.Services.ScriptService]
        public class WebService1 : System.Web.Services.WebService
        {
     
            [WebMethod]
            [ScriptMethod(UseHttpGet =true)]
            public string GetData()
            {
                List<Product> products = new List<Product>()
                {
                    new Product{Id=1,Name="Apple",Price=10}
                    ,new Product{Id=2,Name="Pear",Price=12}
                    ,new Product{Id=3,Name="Peach",Price=11}
                };
                string json1 = new JavaScriptSerializer().Serialize(products);
                return json1;
            }
        }
        public class Product
        {
            public int Id { get; set; }
            public string Name { get; set; }
            public int Price { get; set; }
        }

    How it works.

    Results.

    Please feel free to let me know if you have any question.

    Best Regards,

    Abraham

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, June 27, 2018 3:27 AM
  • User219039814 posted

    Sir,

    What is obj here??

    to what value do i intialize it too?

    Wednesday, June 27, 2018 3:47 AM
  • User219039814 posted

    Yes sir,

    Thats what i started the code with.

    I have an aspx page with a web method which returns list of objects.

    This list of objects is converted to json 

    now the question is how to get the values of these json values to bind to events of fullcalendar

    Wednesday, June 27, 2018 4:48 AM
  • User219039814 posted

    events: function (start, end, timezone, callback) {
    $.ajax({
    type: "POST",
    url: "ajaxpg.aspx/TestOnWebService",
    data: '{}',


    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (result) {
    alert(result.d);
    var obj = $.parseJSON(result.d);
    console.log(obj);
    // alert(obj[0].BookingStartDate);
    // var list = result.d;
    // var obj = JSON.stringify(list);
    var events = [];
    // alert("the values" + obj);

    $(obj).each(function () {
    events.push({
    title: this.AuditoriumName,
    start: this.BookingStartDate,
    end: this.BookingEndDate
    // // id: $(this).attr('id')
    });
    });
    callback(events);

    },
    error: function(xhr, status, error) {
    alert(xhr.responseText + "iam in error");
    }
    });
    },

    When i see the obj values and json doc values.. it is coming perfect.

    But the events function something is failing. Can anyone check 

    Wednesday, June 27, 2018 5:09 AM
  • User-330142929 posted

    Hi Vijaylakshmi,

    There is no need to use obj here, I just want to prove that the $.parseJSON and Eval methods have a consistent effect when the result passed from the backend is a JSON string.

    In addition, if the result transferred from the backend is object, we could Use the JSON.stringify method. Just like the below.

    WebService.asmx.

    [WebMethod]
    [ScriptMethod(UseHttpGet = true)]
    public List<Product> GetProducts()
    {
    return new List<Product>()
    {
    new Product{Id=1,Name="Apple",Price=10}
    ,new Product{Id=2,Name="Pear",Price=12}
    ,new Product{Id=3,Name="Peach",Price=11}
    };
    }

    Script.

        <script>
            $(function () {
                $.ajax({
                    url: "WebService1.asmx/GetProducts",
                    type: "GET",
                    data: '',
                    datatype: 'json',
                    contentType: 'application/json',
                    success: function (data) {
                        //var result = eval("(" + data.d + ")");
                        //console.log(result);
                        //They have the same effect.
                        //var obj = $.parseJSON(data.d);
                        //console.log(obj);
                        var result = JSON.stringify(data.d);
                        var result1 = JSON.parse(result);
    //or we use this simply way
    //var result1=data.d $.each(result1, function (i, e) { debugger; $("#div1").append("ID:"+e.Id+" Name:"+e.Name+" Price:"+e.Price); $("#div1").append("<br>"); }) } }) }) </script>

    Feel free to let me know if you have any question.

    Best Regards,

    Abraham

    Wednesday, June 27, 2018 5:32 AM
  • User-1171043462 posted

    Have you tried what I suggested?

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, June 27, 2018 7:05 AM
  • User219039814 posted

    Yes sir i did and i did a little tweeking my self..

    and it is working..

    Thank you for all the patience..

    Wednesday, June 27, 2018 11:24 AM
  • User753101303 posted

    Try perhaps :

    $.each(obj,function (index,value) {
     events.push({
     title: value.AuditoriumName,
     start: value.BookingStartDate,
     end: value.BookingEndDate
    });

    It seems it could be a confusion between $.each and $(selector).each. Try http://api.jquery.com/jQuery.each/

    something is failing

    IMO it is best to always start from the real bad thing that happens rather than trying to read the code and wondering about how it could fail. Don't you have an error message on F12 Console ?

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, June 27, 2018 11:30 AM