Reading array data from jquery

Hi

I am trying to read data from the array returned by a action of a class which is as follows:


public function actionGetAddress()

	{

   		$optionList = array();

		$optionList['Search Engine'] = 'Search Engine';

		$optionList['Flyer'] = 'Flyer';

		$optionList['TV Advert'] = 'TV Advert';

		$optionList['Link from another Website'] = 'Link from another Website';

		$optionList['Mobile SMS'] = 'Mobile SMS';

		$optionList['SHS Newsletter'] = 'SHS Newsletter';

		$optionList['Existing or Former Client'] = 'Existing or Former Client';

		$optionList['Exhibition'] = 'Exhibition';

		$optionList['SHS Staff'] = 'SHS Staff';

		$optionList['Recommended by a Friend'] = 'Recommended by a Friend';

		$optionList['Other Source'] = 'Other Source';

        return json_encode($optionList);

	}

The following is the code for jquery:


<?

Yii::app()->getClientScript()->registerCoreScript('jquery');

Yii::app()->clientScript->registerScript("initGetAddress","function getAddress(str)

{	 

$.get('getaddress',

   function(data){

     $.each(data, function(key, val) {

            alert('index ' + key + ' points to file ' + val);

	});

   }, 'json');


}",CClientScript::POS_HEAD);?>

It is returning null.

I would appreciate if someone can give me clean code based on my requirements.

Regards,

SInce your action is actionGet[color="#FF0000"]A[/color]ddress, I think


$.get('getaddress',

should be


$.get('getAddress',

I tried changin that. it works the similar way.

in firebug it display an error and say ‘object is null’, length = object.length,

this is a jquery error.

Now I have simplified my jquery reuest even more:


<?

Yii::app()->getClientScript()->registerCoreScript('jquery');

Yii::app()->clientScript->registerScript("initGetAddress","function getAddress(str)

{	 

$.get('getaddress',

   function(data){

     alert(data);


   }, 'json');


}",CClientScript::POS_HEAD);?>

this return null. can’t find the reason

Some ideas:

  • Have you tried to run your action directly in the browser? What does it output?

  • Maybe you should "echo" instead of "return" json_encode($optionList)?

  • Can you echo a string in your action, and see if it works (removing also the json in you ajax call)?

It display the word ‘Array’ when tried echoing and by accessing it through browser

I passed string and it displayed

so definately it has got to do with the jquery code. it is really giving me headache now.

Your are serving you JSON as HTML. Replace


return json_encode($optionList);

with




header('Content-Type: application/json; charset="UTF-8"');

echo json_encode($optionList);

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



Francois, greatly appreciate your comment. You have pointed out the exact problem. It has resolved the matter. Such a small thing took 3 days to resolve. I would like to add you to my network so I can ask for help in future from you.

Many thanks once again.