How to process ajax response in JSON format


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:



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





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


Check jQuery ajax options at There is an option to convert response to object.

I haven’t used that yet but according to the documentation on $.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:



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