SkySonny
SkySonny

Reputation: 103

Jquery get data from JSON (undefined)

When i try to get value from json data i getting undefined

$.get( baseURL + 'vacation/show/' + name_surname, function( data ) {
    alert(data); // return [{"id":"1","title":"Testas","start":"2015-03-04","end":"2015-03-04"}]
    alert(data.start); // return undefined (should be here 2015-03-04)
});

I need get only start value from data, how can i fix this?

Upvotes: 0

Views: 2904

Answers (5)

SkySonny
SkySonny

Reputation: 103

Ty to all, it works fine now, just wondering, or i doing good in my next step, if i retrieve from array for loop and then push only dates into array again to get min date, or it will not be a duplication of work?

 $.getJSON( baseURL + 'vacation/show/' + name_surname, function( data ) {
    if(data != '') {
        var dates = [];  
        for(var i = 0; i < data.length; i++) {
            var date = new Date(data[i].start);
            dates.push(date);
        }

        var minDate = new Date(Math.min.apply(null, dates));
        var year = minDate.getFullYear();
        var month = minDate.getMonth();     

        $('#calendar').fullCalendar('gotoDate', year, month);
    }
 });

Upvotes: 0

lshettyl
lshettyl

Reputation: 8181

If your data is not an object, you need to make an object out of it to be able to access its values. I am not sure what it is at the moment. Hence, I've put a condition to check the type and then alert accordingly.

$.get( baseURL + 'vacation/show/' + name_surname, function( data ) {
    alert(data);
    // return [{"id":"1","title":"Testas","start":"2015-03-04","end":"2015-03-04"}]
    if (typeof data === "object") {        
        alert (data[0].start);
    } else {
        alert (JSON.parse(data)[0].start);
    }
});

A demo@fiddle along the same lines.

Upvotes: 1

user3998237
user3998237

Reputation:

you can do like following:

$.ajax({
 type: 'GET',
 url: baseURL + 'vacation/show/' + name_surname,
 dataType: 'json',
 success: function(data) {
  for(var i = 0; i < data.length; i++) {
    console.log(data[i].start);
  }
 },
 error: function(e) {
  console.log(error);
 }
});

Upvotes: 0

Praveen
Praveen

Reputation: 86

Before Accessing a Json data from 'data' object, you need to parse it to Json Object.

you can achieve this as below:

var parsedJson=$.parseJSON(data)

Here after you can access the json objects like:

  alert(parsedJson[i].start);

where 'i' is the index on N-th data set in the Json object, it can take any numeric value ranging from 0,1,..N

Hope this Helps!!

Upvotes: 0

Jeremy Thille
Jeremy Thille

Reputation: 26370

Use this :

$.get( url, function( data ) {
    /* do stuff */
}, 'json');

or this :

$.getJSON( url, function( data ) {
        /* do stuff */
});

Upvotes: 0

Related Questions