Print js file Yii2 - javascript

Is there any way to print js file?
I know I can use register method of AssetBundle class to register a js/css file into page, also there is another option: to store javascript code in a php variable and use the following method:
\yii\web\View::registerJs($js, \yii\web\View::POS_READY);
But what I need is (on server-side) open a js file, get the contents and write down the code into the html.
The meaning of doing so is that the javascript code is needed only in one page, but also I don't want to add extra requests on client-side.
Also, I know, I can use php include method to load the file and store into a variable, but maybe there is a Yii-way.
So, is there any proper way to do so ? Any help will be appreciated.

Try this , I hope this will Help you.
<?php
$this->registerJs('
$(document).ready(function(){
$(\'.ordinary\').hide();
$(\'.special\').hide();
$(\'#company-typeofcompany\').change(function () {
var x = $(this).val();
if (x === "ordinary") {
$(\'.ordinary\').show();
$(\'.special\').hide();
} else {
$(\'.special\').show();
$(\'.ordinary\').hide();
}
});
});', \yii\web\View::POS_READY);
?>
Thank You..

Related

dynamically change select options with php

Okay, so I have this function in PHP that gets an attribute and returns an array. Something like this:
function getProvinces($countryID){
return arrayWithProvinces($countryID);}
Everytime the parent select changes, the function getProvinces() should be executed with the new ID and the arrayWithProvince should be included as options in the child select.
I'm using jquery to handle the events, as I found somewhere. I need to do something like this.
$("#selectCountry").change(function() {
var parent = $(this).val(); //get option value from parent
var prov = <?php echo json_encode($pagina->getProvinces( <PARENT> )); ?>;
list(prov);
My problem is that I don't know how to tell the getProvinces($countryID) php function which is the new value of the parent.
Thanks in advance.
You should use javascript for that in order to refresh part of your page with dynamic content.Below is an example using jquery's ajax function.When the select with id #parent_select changes you call your php script and you append the returned data (the html of the child select in the example) in a div you want.
Javascript part would be something like this:
$("#parent_select").change(function() {
$.ajax({
url: "your_script.php?cid="+$(this).val(),
success: function(html){
$("#child_select_container").append(html);
}
});
});
And your_script.php code would look something like :
<?php
function getProvinces($countryID){
return arrayWithProvinces($countryID);}
$countryID=(int)$_GET['cid'];
$provinces=getProvinces($countryID);
echo '<select id="child_select">';
foreach($provinces as $key=>$province){
echo '<option id="'.$key.'">'.$province.'</option>';
}
echo '</select>;
I havent tested the example.It is just a basic how to example.You should be able to work your way from here.But if you have any problems let me know.
As far as I know, you cannot execute the function without reloading entire page (I mean php should recompile it and pass it to the client).
You should use only JavaScript for that purpose. Store you arraylist in JS code, and validate it once upon form submission (just to be sure).
You need to make an Ajax request to the server.
Look at it this way: Your Javascript/jQuery is running on the client side (web browser) and you PHP is running on your web server.
So to communicate between the browser(jQuery) and the server(PHP) you need to make a Ajax request.
jQuery has a ajax function you could use, your best bet is to do some research on the subject as Ajax is something you will use all the time and understanding how it works is crucial.

How to load an external js file as plain text and assign to variable as a string

Really sorry if this is a dumb question but I can't seem to get this to work. As the title says i am trying to load an external js file and assign it to a variable as plain text. The project is a simple js "compiler" that stitches together a number of js files and minifies them into one. I am currently using the $.get() method and appending the response to a string.
The problem is that the js file that handles the above also needs to be included in the final minified file. I can load in all the other files and stitch them together just fine but when i load this main file into itself sourcing a js file it seems to evaluate and overwrite itself and so stops the process.
For the time being i have got around the problem by loading in a copy as a .txt file but it means i have to keep two files up to date which isn't ideal.
I found this article but it refers to javascript loaded via script tags in the head.
Any help would be appreciated. I will happily post code but not sure which bits would be useful.
Update: I probably should have mentioned that the project needs to run entirely client side so i can't use PHP/.NET pages. All the files I'm loading in are on the same domain though.
Try to use Ajax.get() :
var script;
$.get('script.js', function(data) {
script = data;
});
for Ajax.get() it will work inside your domain, you can't call external domains, if your application requires loading external JS file then my guess is that you have to use PHP or another server-side language as:
var script;
$.get('getScript.php', {url: "http://test.com/script.js"}function(data) {
script = data;
});
in getScript.php you can use CURL or file_get_contents
Note that $.get() and $.post() and $.ajax() are all the same thing.
$.get and $.post are just shorthand versions of $.ajax() that come with presets (obviously, type: "GET" and type:"POST" for one...). I prefer using $.ajax because the format can be more structured, and therefore easier to learn/use.
Javascript/jQuery would look something like this:
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
type: "POST",
url: "loadmyfile.php",
data: 'filename=js/myscript.js',
success: function(whatigot) {
//alert('Server-side response: ' + whatigot);
$('#myhiddentext').val(whatigot);
} //END success fn
}); //END $.ajax
}); //END $(document).ready()
</script>
Important: Note that you would need to do all the post-AJAX processing inside the success function. See this link for some simple AJAX examples.
Note that you can send data across to the PHP file by specifying a data: parameter in the AJAX code block. Optionally, you can leave out that line and simply hard-code the filename into the PHP file.
The text of the retrieved js file comes back into the AJAX success function (from the PHP file) as a string in the variable specified as the function param (in this case, called 'whatigot'). Do what you want with it; I have stored it inside a hidden <input> control in case you wish to retrieve the text OUTSIDE the AJAX success function.
PHP would look something like this:
loadmyfile.php
<?php
$fn = $_POST['filename'];
$thefile = file_get_contents($fn);
echo $thefile;
References:
PHP file_get_contents

CakePHP, pass parameter to js.php file?

Im trying to use PHP to generate a javascript file. I have the file included and all scripts are workning in it. The think i cant figure out is how i pass a parameter to this file?
To pass a parameter from the controller to the view i use:
$this->set('object_models', $object_models);
To pass it from the view to a element i use:
echo $this->element('pageElement', array('object_model' => $object_model));
Im including my js.php file by adding it in the view with:
echo $this->Html->script('modelDrawer.js.php?', false);
Have you considered using parseExtensions and including your JS file as a view for a controller that you can perform logic on directly?
This would work similarly to the way rss feeds and xml files are generated with Cake.
See this article
UPDATE
Go to your routes.php file, and add the line Router::parseExtensions('js');
Then, create a controller called, for the sake of this, DynamicController.php - and paste this in there:
class DynamicController extends AppController {
public $uses = array();
public function modelDrawer() {
// logic in here
$this->set( 'object_models', $object_models );
}
}
Create a view folder and view file:
/app/View/Dynamic/js/model_drawer.ctp
In that model_drawer.ctp file, you can place your view/script logic that you want to be cakeified.
You can then call your script like this:
<script type="text/javascript" src="/dynamic/modelDrawer.js"></script>
Give that a try!

How to include a file OR PHP code with JS?

How can I include code, for example using Javascript? Or if that can't be done, how can I include a whole PHP file?
P.S. Found some script called "require" or "include," but I prefer two lines of code instead of a huge library (using jQuery though). If that can't be done, let me know, I will try to think of something else.
EDIT:
Okay, an example of what I want to do:
function foo() { if(x = 1) return 1; else return 0; }
Then if the function returns 1, I want to either add HTML/PHP code to DIV tags OR I want to include a PHP file containing that code.
EDIT #2:
What about only HTML?
document.getElementById('test').innerHTML = 'a cool link';
That doesn't seem to work either.
I have an empty div tag with id="test" in my code.
function foo() {
if(x = 1) {$("#divid").load("somephp.php");return 1;}
else return 0;
}
Or
if (foo()) $("#divid").load("somephp.php");
The only files could Javascript includes is Javascript files, what ever the extension is. and the only way to do it is using
<script src="path/to some/file.ext"></script>
You should note that the file should be javascript text contents, else errors may be generated.
Javascript can call any file as long as it is on your server.It can't call files on the user's local files, for obvious security reasons.
However, javascript cannot, and will never be able to call PHP code, as in it cannot execute php code. This is because since javascript is client side, users can call their own javascript on your page, and execute PHP code, and potentially mess up your site or browse your backend.
You can, however add HTML code to your page using javascript, fairly simply using the innerHTML property of DOM elements or JQuery.
Javascript can also call more javascript code if you wanted, using eval()
If you wanted to call files off your server onto the page using javascript, you'd have to use AJAX
Google it up, and you can code it from scratch, or use JQuery's convenient AJAX handler.
Let's say you had a php file myfile.php that had some html/php, and you wanted to insert it into a div with the id "mydiv", or in css, "#mydiv"
If you just want to quickly load the html/php and push it into the div:
$("#mydiv").load("myfile.php");
If you want to have maximum control of the response from the html/php file:
$.ajax({
url: "myfile.php", // url to load
success : function(data) { // on success function
// data is the response of the ajax request, the response text
// you can manipulate it here
manipulateData(data);
$('#mydiv').html(data); // set the html of the div
}
});

No luck when trying to use JQuery with CakePHP 1.3

I'm new to cakePHP but am close to quitting using it due to my inability of getting jQuery to work with it.
I'm using cakePHP 1.3 and so thought the Html and Js helpers had made Javascript and Ajax redundant but I can't really find any help/api documentation on how to use Js that is sufficient.
All I'm trying to do first of all is send some data to cakePHP with jQuery and then get some data back into jQuery and alert() it. For some reason this just isn't working. Here is my code:
test.js
$('.social').click(function()
{
$.ajax({
type: 'POST',
url: '/activities/add_activity',
data: 'type=social',
dataType: 'json',
success: function(data)
{
alert(data);
},
error: function()
{
alert('wut');
}
});
});
activities_controller.php
function add_activity()
{
if($this->RequestHandler->isAjax())
{
$this->autoRender = false;
$this->autoLayout = false;
$this->header('Content-Type: application/json');
echo json_encode(array('result'=>'hello');
return;
}
}
Every time I click the button with class='social' I get the alert "wut" which means error.
I have the RequestHandler component and Javascript, Js, and Ajax helpers included in my activities_controller.php.
Also, test.js and jquery.js is linked using html->script(); in default.ctp and all other jQuery stuff is working so it's not that.
I've also got this in my beforeFilter() for activities_controller.php:
if($this->RequestHandler->isAjax())
{
Configure::write('debug',0);
}
parent::beforeFilter();
Any ideas what is wrong? Is it a jQuery thing or a cakePHP thing? Or both?
Thanks in advance,
Infinitifizz
P.S.
I have never done AJAX in jQuery before so maybe it is something to do with that that is messing up, I've only ever done simple javascript AJAX.
Don't give up on CakePHP. There is a learning curve, but it's worth it.
I would specify the url like this:
<?php $Url = Router::url(array('controller'=>'activities','action'=>'addActivity'),true); ?>
$('.social').click(function()
{
$.ajax({
type: 'POST',
url: '<?php echo $Url ?>';
...
On the CakePHP side, my method would be like this:
function addActivity()
{
$this->autoRender = false;
$this->autoLayout = false;
App::import('Helper', 'Javascript');
$javascript = new JavascriptHelper();
echo($javascript->object(array('result'=>'hello')));
exit(1);
}
I never use if($this->RequestHandler->isAjax()) although I'm sure some kind soul will tell me why I should.
I prefer to camelCase method names in line with CakePHP convention.
Note that this line in your code: echo json_encode(array('result'=>'hello'); is missing a closing bracket.
Also, I wouldn't use jQuery to do simple AJAX like this - it can make it difficult to debug, but that's just personal preference.
I hate the Ajax Helper in CakePHP... that is until I found this: http://blog.loadsys.com/2009/05/01/cakephp-jquery-ajax-helper-easy-scriptaculous-replacement/
Now I can use native CakePHP Ajax calls with jQuery! Look into this. I was able to solve all of my "simple" ajax issues with this darg-n-drop ajax helper replacements. I just drop this into the helpers directory in my app and replace the ajax.php that is there and viola! jQuery is working. You need to include the jQuery script in the layout of course. Try it, you will love CakePHP again!
I would recommend you to use CakePHP json layout to output the data from view instead of echo json data from your controller.
This probably is offtopic, but...
What I do in order to have the application's root in my javascript:
In the /app/views/layout/default.ctp I have following code
<?php
echo $javascript->codeBlock("var root = '".$html->url('/')."';");
?>
Your parameter url will look like:
url: root+'activities/add_activity',
this way even if you app is in a subfolder or in a tld domain the script will work properly.
Returning "wut" for me means that the script couldn't reach the page in your url parameter. Especially if you working in a subdirectory it will look in http://server.com/activities/add_activity. I am 99% sure that this is the problem :)
Another suggestion: Remove Ajax while it was meant to work with Prototype rather with jQuery

Categories