views:

148

answers:

3
$.ajax({
    type: 'POST',
    url: 'place/add',
    data: {
        lat: lat,
        lng: lng,
        name: name,
        address: address,
        phone: phone,
        review: review,
        category: category
    },
    success: function(data) {
    alert(data);
    alert(data.id);
    // ......
});

The first alert gives: {"id":"2","success":true}

but the second: undefined

+11  A: 

You need to specify your anticipated returned data type as JSON:

$.ajax({
    type: 'POST',
    dataType: 'json', // specifies the return type
    url: 'place/add',
    data: {
        lat: lat,
        lng: lng,
        name: name,
        address: address,
        phone: phone,
        review: review,
        category: category
    },
    success: function(data) {
        alert(data);
        alert(data.id);
        // ......
    }
});
cballou
Other valid return types include **xml**, **html**, **script**, **jsonp**, and **text**. The default return type is *html or xml*, so it is best to specify your required returnType to avoid the overhead.
cballou
A: 

You have to specify dataType: 'json' or eval returned data yourself like this var data = eval('(function(){return '+data+'})()');

BTW trust jQuery - use dataType: 'json' if you can.

NilColor
+1  A: 

An especially useful addition, if you run multiple ajax calls is $.ajaxSetup

$.ajaxSetup({
  type: 'post',
  dataType: 'json'
});

Any subsequent ajax calls will use these as the defaults.

czarchaic