0

I am calling a webmethod from jquery and get the json object but I cannot parse and read the json object. please help me find what I am doing wrong. I have 3 alert() and I am putting comments next to them what they show...

my jquery code is this

$('#btn_second').click(function () {
            //$('#txt_isim_4').val('test arif');
            $.ajax({
                type: "POST",
                url: "Registration.aspx/get_selected_professional",
                data: "{'id':'2'}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (data) {
                    alert('1:' + data); // display [object Object]
                    alert('2:' + data.d.firstname); // display undefined
                    alert('3:' + data.d);  // display [{"id":"2","firstname":"arif"}]
                }
            });
        });

but I want to display only "Arif". is my json object wrong? should I use single quotation?

thank you

3 Answers 3

1

suppose your webmethod is something like this:

public string get_selected_professional(string id)
{
   List<MyClass> requiredData= GetRequiredData(id);
   //your required logic

   //string requiredData= "[{\"id\":\"2\",\"firstname\":\"arif\"}]";
   //return requiredData;

   //or

   return new JavascriptSerializer().Serialize(requiredData);
}

where MyClass is

public class MyClass
{
   public int id {get;set;}
   public string firstname{get;set;}
}

then you should do this inside your ajax :success on the client side:

success: function (data) {
                    var jsonData =$.parseJSON(data);
                    alert('1:' + jsonData); // display [object Object]
                    alert('2:' + jsonData.d.firstname); // display undefined
                    alert('3:' + jsonData.d);             
     }
Sign up to request clarification or add additional context in comments.

Comments

1

You have array, use index and also use curly bracket in data to make object.

Live Demo

Change the json string to

[{"id":"2","firstname":"arif"}]

Use array index indexer to access its elements

data.d[0].id

2 Comments

what should I use instead?
try var jsonData= jQuery.parseJSON(data);
0

You just need to parse you data:

var result = jQuery.parseJSON(data.d);
alert(result[0].Id);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.