I’m working on just basic stats for how long someone is on a page, these are sent via JavaScript to the controller, but I’m struggling to extract the values.
How exactly does it send teh data.
<script>
var timeStarted, a, b, c, timeLeft, pageData;
timeStarted = new Date().getTime();
a = 1;
b = 2;
c = 3;
window.onbeforeunload = function()
{
timeLeft = new Date().getTime();
pageData = [timeStarted, a, b, c, timeLeft];
// Set url for JavaSCript
var url = '/localhost/item/viewedItem';
<?php echo CHtml::ajax(array(
'url'=>'js:url',
'data'=> "js: $(pageData).serialize()",
'type'=>'post',
'dataType'=>'json',
)) ?>;
}
</script>
Then within the controller I just don’t know how i’d access the results. I’ve tried just
The ‘data’ option in an ajax call can be either an array/object or a string, so you don’t have to process it. And the serialize() method is used for DOM elements, not arrays/objects. If you’d want to turn an array/object into a string you would use the jQuery.param() method.
I think that serialize() in your current code could return an empty string. Test it yourself in the Firebug console by running this code:
pageData = [timeStarted, a, b, c, timeLeft];
$(pageData).serialize()
Without adding a colon ‘;’ after the last line it will make Firebug log the return value to the console.
You should do the same on the server side, just check the contents of $_POST by debugging, logging the value using Yii::log or error_log or simply echo’ing it using var_dump().
Thanks for your help, in the end I did change my data to be an array of objects and passed worked with returning the serialized data back via ajax gto see what was returned.