Ammar Ijaz Ammar Ijaz - 6 months ago 39
Javascript Question

Accessing a particular element in json while using ajax success method

I am using below ajax call to get a json object from server side(php)

$.ajax({
url: url,
method: "POST",
data: { cdrid : cdrid },
dataType: "json",
success: function(data)
{
$("#appName").val(data.appname);
$("#callDate").val(data.callDate);
$("#editHavenRecord").modal("show");
},
error: function()
{
alert("Unable to get haven data");
}
});


i am getting following json object as response from server

[{"id":"433","cdrid":"5339922","appid":"108","appname":"Haven Holidays(Service) 2009","dnis":"1172441753","CallDate":"2016-03-01","CallInTime":"2016-03-01 15:08:28","CallEndTime":"2016-03-01 15:11:25","TranscribeDateTime":"2016-03-02 05:16:56","agentid":"K9Q","calloutcome":"Good Record","TermCd":"GR","title":"Mr","fname":"Elwood","lname":"Ward","Addr1":"99 Enclingson Road","Addr2":"Bournemouth","Addr3":"","Country":"","city":"","town":"","postcode":"TH9 1HR","HeardAdvert":"BRAND_TV","ver_code":"VO","ver_date":"3\/2\/2016 5:26:32 AM","Duration":"177","HangUpCode":"8010","TranscribedBy":"Tom.Rodie ","batchid":"903"}]


However when i try to access any particular element like data.appname it is not working also when i try to print any element on console it gives me undefined

Answer

data is an array of one element inside, its element is the object you want. so data[0]

$.ajax({
        url: url,
        method: "POST",
        data: { cdrid : cdrid },
        dataType: "json",
        success: function(data)
        {
          

           // data is an array of one element inside, its element is the object you want. so data[0]
           $("#appName").val(data[0].appname);
           $("#callDate").val(data[0].callDate);
           $("#editHavenRecord").modal("show");                     
           
     
        },
        error: function()
        {
            
   
           alert("Unable to get haven data");
                
        }
    });