Getting Yii to Return an AJAX Response with the JSON content-type

My particular application sends a JSON encoded message to my AJAX controller but I am having a hell out of time getting my corresponding data back in JSON.

my jQuery js looks something like this:




$.ajax({

	type: "post",

	url: "/ajax/vote/",

	data: data,

	dataType: "json",

	success: function(response, status) {

		alert("Success!");

	},

	error: function (response, status) {

		alert("Fucking Bull Shit!");

	},

});



my controller ends in:




$this->renderPartial('_ajaxContent', $data, false, true);



data being a simple integer and finally my _ajaxContent.php is simply:




<?php echo $data; ?>



I’m fairly certain I’m missing a json_encode i’m sure but everytime I change echo $data to echo json_encode I get null for a response.

What am I doing wrong?

Oh and quick edit. The content type always responds html instead of json but if i do json_encode my javascript sends a success message.

i think you must use following replace your controller code:


$this->renderPartial('_ajaxContent', array('data'=>$data), false, true);

I tried that but no go.

I’m using http://www.yiiframework.com/doc/cookbook/49/ as my base but I’m not too sure. I’d love to see some examples of how people accomplish their AJAXing within Yii. I saw a CakePHP tutorial which got me pretty far but CakePHP seems to do a lot of auto-detecting and changes for you so I’m missing some parts methinks.

Try this




<?php echo CJavaScript::jsonEncode($data); ?>



Without CJavaScript::jsonEncode() you’ll get status “parseerror” on response.

Edit:

The data should be there




success: function(response, status) {alert("Success! "+response);}



You probably don’t want the view so change controller code to




echo CJavaScript::jsonEncode($data);

Yii::app->end();



/Tommy