Question about passing parameters to javascript.

I have been using several javascripts being embedded in 'protected/view/layouts/main.php' as follows.

main.php:

<script type="text/javascript" src="<?php echo Yii::app()->request->baseUrl; ?>/js/myscript.js"></script>

I may change this to CClientScript::registerScript() in future.

Though I haven't tested the latter yet, it seems to cause problem.

myscript.js:

ajaxUrl = '<?php echo Yii::app()->request->baseUrl.'/index.php?r=user/authAjax'; ?>';


 :

I have passed some parameters such as baseUrl to Javascript, it may not work for javascript inclusion shown above. Instead, I made a workaround to include it as a php file as follows.

main.php:

<?php require_once(Yii::app()->basePath.'/../js/myscript.php'); ?>

myscript.php:

<script type="text/javascript" src="<?php echo Yii::app()->request->baseUrl; ?>/js/myscript.js"></script>


<script type="text/javascript">


<!--


ajaxUrl = '<?php echo Yii::app()->request->baseUrl.'/index.php?r=user/authAjax'; ?>';


 :

As this is a php, thus I may not able to use CClientScript::registerScript(). Is there a good solution for this?

Quote

I may change this to CClientScript::registerScript() in future.

Though I haven't tested the latter yet, it seems to cause problem.

No, I tested it it's OK.

You can do the following:

XController.php:

$cs->registerScriptFile($this->createAbsoluteUrl('site/params'))

SiteControler.php:

public function actionParams() 


{


$params = CJson::encode(array('par1' => $val1,...));


$script = 'var PARAMS = eval('.$params.')';


echo $script;


}

Another way:



$params = CJson::encode(array('par1' => $val1,...));


$script = 'var PARAMS = eval('.$params.')';


Yii::app()->clientScript->registerScript($script);


Quick comment - It’s not tested code, just ideas :)

Thank you for your reply :) I am going to check based on your idea soon.

Please post the results of your testing here, I'm interested to learn this too.

Quote

Please post the results of your testing here, I'm interested to learn this too.

Thank you Konstantin. :D Now it’s working.

What I have done is to modify the interface portion to the persistentJS. And original discussion is here.


Original:

  main.php:

<?php require_once(Yii::app()->basePath.'/../js/persist-if.php'); ?>

Though it is an one-liner function, I do not think it is beautiful.

  persist-if.php:

<script type="text/javascript" src="<?php echo Yii::app()->request->baseUrl; ?>/js/persist.js"></script>


<script type="text/javascript">


<!--


$(document).ready(function(){


        var hostroot = '<?php echo str_replace('/', '_', $_SERVER['HTTP_HOST']."__".Yii::app()->reque


st->baseUrl); ?>';


  :

Modified:

  main.php:

<script type="text/javascript" src="<?php echo Yii::app()->request->baseUrl; ?>/js/persist.js"></script>


  :


<?php


   $params = array(


                   'BASEURL'=>Yii::app()->request->baseUrl,


                   'HTTPHOST'=>$_SERVER['HTTP_HOST']


                   );


   $script = 'var PARAMS = eval('.CJavaScript::jsonEncode($params).')';  // parameters


   $script .= implode('',file(Yii::app()->basePath.'/../js/persist-if.js')); // body


   Yii::app()->clientScript->registerScript('persist-if', $script);


?>

  persist-if.js:

var hostroot = PARAMS['HTTPHOST']+'__'+PARAMS['BASEURL'].replace(///g,'_');


  :

Someone please let me know if you know a better solution on this subject :), 'cause I will summarise it as an article of cookbook.

Hi mocapapa,

I think the cleanest way, would be to seperate the javascript and php code.

If you want to pass parameters from your php code to javascript, you could

convert your existing javascript code to a jQuery plugin. (What is pretty easy.)

For example:

showAjaxLogin.js



/**


 * Loads a login form via ajax request


 * and displays it in a container div


 */


jQuery.fn.showAjaxLogin = function(options) {





// the default options / script parameters


	var settings = jQuery.extend({


		user: "username", 


		pass: "password", 


		url:  "form.php",


		md5:  true


	},


	options);





// your main-code goes here...


	var Container = this;


	$.ajax({


		type: 'GET',


		url:  settings.url,


		data: '&user='+settings.user+'&pass='+settings.pass,


		dataType: 'html',


		success: function(data){


			Container.html(data).fadeIn('slow');


		}


	});





};


register the script file in your Yii project and do something like:



<?php 


// the div, that holds the ajax-loaded Login form


echo CHtml::tag('div', array('id'=>'container', 'style'=>'display:none;'));





// the php options, we want to send to the javascript


$encodedOptions = CJavaScript::encode(


	array(


		'user' => 'mocapapa',


		'pass' => md5('SuperSecurePass'),


		'url'  => 'site/ajaxLogin',


		'md5'  => true,


	)


);





// registers the calling javascript @ document-ready


Yii::app()->clientScript->registerScript(


	'ajaxFormLoad', 


	'$("#container").showAjaxLogin('.$encodedOptions.');', 


	CClientScript::POS_READY


);


?>


I hope that helps you. :)

greets ironic

(attached my test-project.)

Hi ironic,

Thank you for your suggestion. I will try to understand what you said, and will apply your idea to my application. :)

hi,

I’ve worked with passing JS params from PHP for the small extension I wrote, and what Ironic wrote, works fine. However, I had problems when an options was in fact a function (just like the success options above). In this case, JsonEncode would produce this

      'success': 'function(data){


         Container.html(data).fadeIn('slow');


      }'

(which is not what we want)…instead of this :

      'success': function(data){


         Container.html(data).fadeIn('slow');


      }

(without quotes).

Hope this helps …

8)

Thanks Raoul,

I had noticed your extension valuable, though I haven't tested yet… Anyway I would like to collect the method passing parameters from/to PHP to/from JS.