Post Not Working With Csrfvalidation=True

I have enabled csrf validation in config/main.php and I have a javascript function in view1.php which is sending a variable to view2.php file on client request using POST method. Thus if csrf validation is enabled POST method is not working. What is the best method to solve this problem considering I don’t want disable csrf validation? Also I don’t want disable csrf validation exclusively for POST since their are many other POST in my web application which are working fine with enabled csrf validation.

My javascript function for sending variable using POST


<script>

	function testing(col) {

		$("#bookId").val(col);

		$.ajax({

        type: 'POST',

        url: "<?php echo Yii::app()->createUrl('siteaccess/hello'); ?>",

        data: {"ad_id":col},

        dataType: 'text',

        success: function(col){console.log(col)},

});

	};

	</script>

You need to include the CSRF data in your request:




    var csrfTokenName = <?= CJavaScript::encode(Yii::app()->request->csrfTokenName); ?>;

    var csrfToken = <?= CJavaScript::encode(Yii::app()->request->csrfToken); ?>;

    var postParams = {"ad_id":col};

    postParams[csrfTokenName] = csrfToken;


    $.ajax({

        type: 'POST',

        url: "<?php echo Yii::app()->createUrl('siteaccess/hello'); ?>",

        data: postParams,

        dataType: 'text',

        success: function(col){console.log(col)},

    });



or something like that.

Thanks Keith. It’s working fine now.