yii:chtml encode returns data string instead of array

Hi,

I use following JQuery request:




jQuery('body').undelegate('#closeUpdateDialog','click').delegate('#closeUpdateDialog','click',function(){

                            jQuery.ajax({'success': function(data) {

                                    $('#mymessage').text(typeof data);

                                    $('#quote-form-2')[0].reset();

                                    $('#egz').dialog('close');

                            },

                            'type':'POST','url':'/erfassungswerkzeug/index.php?r=quote/update&id=' + source_id,

                            'cache':false,

                            'data':jQuery(this).parents('form').serialize()}

                            );

                            return false;

                        });



The QuoteController returns a response via JSON:




 echo CJSON::encode(array('saved' => true,

                    'div' => 'Citation was updated.'));

                    Yii::app()->end();



I can see in Firebug, that the controller returns following key value pairs:




saved true

div "Citation was updated."



But I am not able to get the key and value pair inside the function(data) and $(’#mymessage’).text(typeof data); returns that the type of data is ‘String’. What I am doing wrong here?

– Franck

You need to set ajax dataType value to "json" so that it "knows" that you are returning a json array…

http://api.jquery.com/jQuery.ajax/

You’re doing nothing wrong. This is the way that Yii encodes to JSON.

I have solved this problem using the code below:




$data = '[';

foreach ($list as $item) {

    $data .= '"' . CHtml::encode($item) . '", ';

}

$data .= ']';

header('Content-type: application/json');



Thanks mentel and mdomba!

mdomba was right, dataType does the thing:




jQuery('body').undelegate('#closeUpdateDialog','click').delegate('#closeUpdateDialog','click',function(){

                            jQuery.ajax({'success': function(data) {

                                    if(data.saved == 'true'){

                                        $('#quote-form-2')[0].reset();

                                        $('#egz').dialog('close');

                                    } else {

                                         $('#quoteForm').html(data.div);

                                    }

                            },

                            'type':'POST','url':'/erfassungswerkzeug/index.php?r=quote/update&id=' + source_id,

                            'cache':false,

                            'dataType':'json',

                            'data':jQuery(this).parents('form').serialize()}

                            );

                            return false;

                        });






Now it works :-)!

– Franck