How to process ajax response in JSON format

Hi,

I have a function that makes an ajax call. The response is in JSON format, e.g.:


{"postcode":"1033SN","street":"Mt. Lincolnweg","cityName":"Amsterdam"}

The result is to be used to set two activeTextFields. I tried to following code:




                'success'=>'

                    function(data,status){

                        var obj = $.parseJSON(data); <----------------------  how to convert JSON to object?

                        $("#'.CHtml::activeId($model,"city").'").val(obj.cityName);

                        $("#'.CHtml::activeId($model,"street").'").val(obj.street);

                    }

                ',



The content of obj is null. Is there another way to convert a JSON-formatted string to an object? Or should I proceed differenty?

Thanks.

Check jQuery ajax options at http://api.jquery.com/. There is an option to convert response to object.

I haven’t used that yet but according to the documentation on $.ajax - http://api.jquery.com/jQuery.ajax/

if you use the ‘dataType’=>‘json’ in the ajax call you get a javascript object

Thanks samback and mdomba.

Yes, you are right, but I’m not able to get the parseJSON function running.

I tried both $.parseJSON and jQuery.parseJSON, but both of them respond with a null value.

I’m not sure if I’m using the jQuery the ‘yii way’.

Exactly, that is what I used and it works fine. The result is in JSON format, but I have to make an javascript object before I can assign the values to the activeTextFields.

I’m reading your remark again and you hit the mark on the spot. Using ‘dataType’=>‘json’ converts a json-string to a javascript automatically and can be used directly. For the record, the working code is:




    'dataType'=>'json',

    'data'=>array(

        'q'=>'js:$("#'.CHtml::activeId($model, "postcode").'").val()'),

        'success'=>'

            function(data,status){

                $("#'.CHtml::activeId($model,"city").'").val(data.cityName);

                $("#'.CHtml::activeId($model,"street").'").val(data.street);

            }

        ',



Thanks!