How Can I Pass Javascript Variable To Php In Yii

How can I pass a javascript variable to php function in yii using ajax?

You might send through GET or POST method. an example with JQuery:




	$.ajax({

		type: 'get',

		url: "<?php echo Yii::app()->createUrl('site/updateHint') ?>",

		data: {ad_id:"<?php echo $model->id ?>"},

		//success: function(data, textStatus, jqXHR){console.log(data+' - '+textStatus)},

		//error: function(jqXHR,textStatus, errorThrown){console.log(errorThrown)},

	});



1 Like

In my view file I did something like $v = $_GET[‘ad_id’] but it is giving error undefined index ad_id.

Please place your code.

in view1.php I have


<script> function testing(col) { 		

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

$.ajax({

type: 'POST',

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

data: {"ad_id":"<?php echo 'hello'; ?>"}, 

dataType: 'text',

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

</script>

while in create.php I have


$v = $_GET['ad_id']; 

echo $v;

There’s at least one obvious error:


type: 'POST',


$v = $_GET['ad_id'];

You’re sending the data in a POST request and attempting to retrieve it from the $_GET array.

Hi,

I hope this will help you to solve your problem

			&#036;.ajax({


	            type: &quot;POST&quot;,


	            url: &quot;&lt;?php echo Yii::app()-&gt;createUrl('programm/registration')?&gt;&quot;,


	            data: {status:&#036;('#register'+eventid).prop('checked')?&quot;add&quot;:&quot;delete&quot;,pgmid:&lt;?php echo &#036;model-&gt;pgm_id?&gt;},


	            success: function(data){

[size=2] [/size][size=2] [/size][size=2] [/size][size=2]},[/size]

				error: function(xhr, status, thrownError) {


					console.log('status '+xhr.status +'responseText '+ xhr.responseText + 'Error ' + thrownError);


		 		},


        	})

Sorry that just a typo error I copied that from older code but in my code it is $_POST[‘ad_id’] and I am getting error undefined index ad_id.

Hi,

Try this.

$adid = (isset($_POST[‘ad_id’])) ?$_POST[‘ad_id’]: $_GET[‘ad_id’];

ok I changed my code to


Yii::app()->request->getPost('ad_id');

and it is working now but why $_POST doesn’t work. Whenever I am using $_POST it is giving error “undefined index ad_id”.

Thanks chandran for help.

My other question is if I enable csrfvalidation POST fails while POST works if csrfvalidation is false. Is their any way to make POST work with csrfvalidation enabled?

Hi,

I hope this link will help you

http://www.yiiframework.com/wiki/274/how-to-validate-csrf-token-with-session/