Cakephp: how to pass values into a javascript file? - php

I have some javascript that is being included in a view and I used inkedmn's method in this thread:
adding-page-specific-javascript-to-each-view-in-cakephp
So I now have the following code in my view:
$this->set('jsIncludes',array('google')); // this will link to /js/google.js
But I need to pass some values from the view into the javascript file and I'm unsure of how to accomplish this.
Update: I guess one option would be to echo the values in the php file, enclose in a div tag, and then use a getElementById() in the javascript code.

You should be able to inject a <script> tag directly into the HTML with the data you want:
<script type="text/javascript">
var mynum = <?php echo intval($num); ?>;
var mystring = "<?php echo addslashes($string); ?>";
var myarray = <?php echo json_encode(array("one" => 1, "two" => 2)); ?>;
</script>
Any javascript elsewhere should be able to use these variables.
Note: if the code using this data runs earlier in the page, they obviously won't see these variables yet. If that's the case, either ensure that your data is loaded first, or you can delay the code from running until the page is fully loaded, using either setTimeout() or a document.onready event.

Do you have some code that runs automatically? You could wrap it inside a function, and pass the function the necessary parameters.
For example, let's you currently have the following code in my-script.js:
window.onload = function() {
alert('My favorite fruits are apples, and my favorite color is red.');
}
Wrap it in a function like this:
function initialize(args) {
window.onload = function() {
alert('My favorite fruits are ' + args.fruit +
', and my favorite color is ' + args.color + '.');
}
}
Then, output a <script> element using PHP somewhere after my-script.js is loaded, and call the function. Here's an example output:
<script>
initialize({fruit: 'apples', color: 'red'});
</script>

$this->Js->set('varname',$value);
from js file
var myvar = window.app.varname;

These are following step:
1) Include the js helper in AppController.php
public $helpers = array('Js');
2) Now Declare js variable in ctp file
Like that way :
$state = 'rajasthan';
$this->Js->set('state_name',$state);
echo $this->Js->writeBuffer(array('onDomReady' => false));
3) Now Use this js vairable "state_name" in js file
Like that way :
console.log(window.app.state_name);
var state = window.app.state_name;

Related

PHP - If div has certain class then

My question is simple.
I have the following code:
<div class="last"
<?php
if hasClass(last){
echo " style='width:100%;' ";
}
?>
></div>
I know the if statement is wrong, but the idea is there. I want to know how can I check if this div has the .last class then echo something.
I've been searching around but didn't work anything (didn't find much though).
Best regards.
As already in the comments told it's possible with PHP with DOM parsers.
I'm gonna give you 2 very simple solutions which will save you a lot of work:
CSS:
<style>
.last {
width:100%;
}
</style>
jQuery:
<script type="text/javascript">
$(document).ready(function(){
if($('div').hasClass('last')){
$('div').css('width', '100%');
}
});
</script>
PHP runs on server, so it generates HTML. If you have that class="last" you don't need to check - it's part of the code....hard-coded.
But you can have some PHP variable and depending on it's place print out class and also style for that other element:
<?php
$print_last = true;
?>
...
<div <?php if ($print_last) echo 'class="last" ';
<?php
if ($print_last){
echo " style='width:100%;' ";
}
?>
></div>
But if you want to check on html element you have to do it on client side (browser) from JavaScript and jQuery can be helpful too.
It is possible to check that using PHP, however that couldn't be done easliy (you'll need to parse buffered HTML using DOM parser, then look up for divs, etc...).... Much better solution is to do that with Javascript/jQuery, using Document.getElementsByClassName() function.
Sample solution:
var elements = document.getElementsByClassName("last");
for(var i = 0; i < elements.length; i++)
{
var element = elements[i];
element.style.width = "100%";
}
#azhpo
Obviously the HTML being the front end language you have to pass the elements either through some submit button or via ajax request.
Using submit button: select the class name of div using either javascript
var className = document.getElementById("myDIV").className
document.getElementById("myHiddenField").value = className;
Now on clicking the submit button it would get submitted
Using ajax:
Again take the classname either through javascript / jquery
var className = jQuery("#myDiv").attr("class");
Now fire ajax query and send the class name to your script
jQuery.ajax({
url: 'file.php',
type: 'POST',
data: 'class='+className,
success: function(data){//do whatever you want},
error:function(){//do whatever you want}
});

Passing PHP Variable Into jQuery Function

I'm trying to implement jQuery Flare Video Plugin for my website.. There's a dropdown menu which the user must choose a year from, when the submit button is clicked, a video is meant to show on the screen. I have a database that grabs the path to the video from the database i.e $row['videoName'] .
My question is how can I pass PHP variables in jQuery function.. In the example given in the plugin a full path to the video was given insrc attribute of jQuery function. I'm trying to make the src dynamic by passing the PHP Variable into it.
I'm not getting any error, and the div containing the video appears on the screen, but the video does not show.
Thank you.
jQuery(function($){
fv = $("#video").flareVideo();
fv.load([
{
src: '$row['videoName']',
type: 'video/mp4'
}
]);
})
</script>
To access the PHP variable you must enclose the code in PHP brackets like so:
jQuery(function($){
fv = $("#video").flareVideo();
fv.load([
{
src: "<?php echo $row['videoName']; ?>",
type: 'video/mp4'
}
]);
})
</script>
This must also be on the same page as the PHP variable is created to allow access.
I would advice to keep PHP preprocessing out of javascript as much as possible. I have a convention of creating a hash of all variables from PHP in the view and then injecting them into my Javascript objects. In this case you could put something like this into the view:
<script>
var options = {
videoName: '<?php echo $row['videoName']?>'
}
</script>
or
<script>
var options = <?php echo json_encode($row);?>;
</script>
Later in any of your javascript files you could do this:
$(function(){
fv = $("#video").flareVideo();
fv.load([{
src: options.videoName,
type: 'video/mp4'
}]);
})
jQuery(function($){
fv = $("#video").flareVideo();
fv.load([
{
src: '<?= $row['videoName'] ?>',
type: 'video/mp4'
}
]);
})
</script>
Mix php and js code is ugly. So when you have all your js code into .js files you can do it in this way:
code into .js files
jQuery(document).ready(function($){
fv = $("#video").flareVideo();
fv.load([
{
src: videoName, // videoName is in the global scope
type: 'video/mp4'
}
]);
})
var videoName = ""; // init var to avoid undefined values
code into .php files
echo <<<EOM
<script type="text/javascript">
var videoName = '{$row['videoName']}';
</script>
EOM;
The URL to the Video should be somewhere within the HTML Scope. JS comes in handy to grab the URL, with something like
fv.load({
src: $('.videlink').attr('href'),
type: 'video/mp4'
})
I do not know the precise javascript of this flareVideo() thing, but the URL SHOULD really be somewhere inside your HTML. Do not just pass this to the JavaScript, this is really ugly design :\
Another way to pass PHP variables to jQuery is through the DOM. You said that you have a dropdown list of years that the user selects. When you build your page, get the whole array of videos like so:
$rows = array(
'1991' => '/url/to/your/1991-video',
'1992' => '/url/to/your/1992-video',
'1993' => '/url/to/your/1993-video',
'1994' => '/url/to/your/1994-video'
);
So you can just build your select list like so:
<select id="videoName">
<option value="<?php echo $rows['1991'] ?>">1991</option>
<option value="<?php echo $rows['1992'] ?>">1992</option>
<option value="<?php echo $rows['1993'] ?>">1993</option>
<option value="<?php echo $rows['1994'] ?>">1994</option>
</select>
I've used a simple array but you would use the results of your database query, and you could also use a foreach to build your drop down list.
Then your video script would just reference the $('#videoName').value().
By doing a .change() event handler on the select, you can start the video without having to reload any pages.
You can use the same approach to build tables of items based on a database query. Just name your objects or id them with unique values based on your database output.
(code is untested)
Thoughts about doing this with a cookie? I think something like this...
PHP
setcookie('your_cookie_name', json_encode($your_array), time()+3600, "\");
Javascript
You would then have the PHP array in JS to do whatever JS you wanted to preform on it.
var arrayVar = []
arrayVar = $.parseJSON($.cookie('your_cookie_name'));

How to call $_SESSION in javascript

I have two separate pages, one page is where it uploads the file and the other page displays the information.
In the imageupload.php page, I have this session below:
$_SESSION['fileImage']['name'] = $_FILES['fileImage']['name'];
I also have a javascript function which calls back to the javascript functiom:
<script language="javascript" type="text/javascript">window.top.stopImageUpload();</script>
Now on a seperate page (QandATable.php), I have a javascript function, but my question is how can I call the $_SESSION code above in the javascript function so I can append it to $('.list')?
Below is javascript function:
function stopImageUpload(success){
var result = '';
if (success == 1){
result = '<span class="msg">The file was uploaded successfully!</span><br/><br/>';
$('.listImage').append('<br/>');
}
else {
result = '<span class="emsg">There was an error during file upload!</span><br/><br/>';
}
return true;
}
You cant, because $_SESSION is a server side variable but you can access it by.
For the entire session variable
<script type="text/javascript" >
var session = <?php echo json_encode($_SESSION); ?>;
</script>
For a particular variable in session.
<script type="text/javascript" >
var session_var = <?php echo json_encode($_SESSION['VAR_NAME']); ?>;
</script>
Now you have js variable called session with that information. However it is not advisable in most situation to output all that info to public pages.
Session variables are stored on the server. JavaScript is executed on the cliend side, so it knows nothing about the server side. It know only as much as you pass to it.
To pass a variable to javascript, use an ajax request, or simply output the values:
<script>
var sesionValue = <?=json_encode($_SESSION['value']);?>;
</script>
You should look into using JQuery, as it makes these AJAX-like tasks much easier.
See my function I wrote just today to do something similar to what you're asking.
This takes some PHP output (returned in the success part of the call to ajax(). The format it takes is in JSON, which is compatible by both PHP and JavaScript (JSON: JavaScript Object Notation).
function viewClientDetails(id) {
var clientParams;
clientParams.clientID = id;
$.ajax({
url: BASE_URL + '/clients/get-client-details.php',
type: 'POST',
data: clientParams,
dataType: 'JSON',
success: function(myClient) {
var name = myClient.name;
$('td#name').html(name);
},
error: function(e) {
console.log(e.responseText);
}
})
}
In my PHP file (called /clients/get-client-details.php) I have something like this:
<?php
...
$myClient = array('name' => 'Mr Foobar');
print json_encode($myClient);
?>
This simply writes my PHP object to JSON format.
In the JS code above, the code inserts a part of the JSON data into an HTML table-data element whose CSS selector ID is #name, with the line: $('td#name').html(name);
Apologies if this confuses you more, I thought I'd show an example of what you can try some time..
This may help you a bit along the way...keep trying things, you'll get there :)
You can't. $_SESSION is a PHP variable, and that code runs server-side.
You'll need to store the value as a Javascript variable in the output from your PHP file, then access that variable in your Javascript.

Pass PHP variables to Javascript/jquery [duplicate]

This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 8 years ago.
So far I know two ways to pass php variables to javascript.
One is by using
<script>
$(document).ready(function()
phpvalue=$("#hiddeninput").val()
})
</script>
<input type="hidden" id="hiddeninput" value="phpvalue">
And the other one is by having for example a button and using onclick
<script>
function clickf(phpvalue) {
}
</script>
<input type="submit" onclick="clickf(<?php echo phpvalue ?>)">
All of them work great but:
Is there any other way that I'm missing?
Which one is the "best"?
Any chance that I can use inside the script or the external js ?
<script>
$(document).ready(function()
var phpvalue = <?php echo $var; ?>
});
</script>
Like others already answered, just put a PHP tag whereever you would place the JS value, like var foo = <?= $php_value ?>; or var foo = <?php echo $php_value ?>;.
If you want to use this in an external JavaScript file, you have to make sure .js files get parsed by PHP. If this is not an option for you (for example, your host doesn't allow it), I suggest you set the values in a <script> tag inside your <head> and then just reference thos variables from your external JavaScript. In that case, I would strongly suggest you namespace them like var app_vars = { foo: <?= $bar ?> } in order to not clutter the global object.
Another way would be to retreive the values via Ajax. But the viability of this approach depends on your use case.
And another hint: if you want to pass multiple variables or arrays, there's JSON baked into PHP since version 5.2:
<?php
$my_complex_var = array(
'array' => array('foo', 'bar'),
'val2' => 'hello world'
);
?>
<script>
var my_complex_js_var = <?= json_encode($my_complex_var) ?>
</script>
<script>
var javascript_variable = <?php echo $php_variable; ?>;
</script>
Instead of assigning values to hidden inputs, you could just generate JavaScript directly:
$script = <<<EOT
<script>
var phpvalue = $phpvalue;
</script>
EOT;
echo $script;
for the top example you do not need to use val you could use any attr you like.
For example
phpvalue="myvalue"
then within jquery
$("#hiddeninput").attr("phpvalue");

How to make the JS function get the data from the database everytime I call it?

I am using a code look like this:
<script>
function getdata()
{
var employee =
<?php
//connect to database and get employee name
echo "'" . $row['empnm'] "'";
?>;
}
</script>
print them
It works, but the function is running the PHP code only on the page loading and not every time I call the function. So, if the target employee name is changed the JS function will show the old name untill the page is reloaded. How to make the JS function get the data from the database everytime I call it?
look into a library like jQuery
Then using the following code
function getdata(){
$.post("path/to/file.php", function(data) {
var employee = data;
// do whatever with the data.
});
}
and you can still use your same html
print them
and file.php
<?php
// connect to your db, get your results, echo them back
echo $row['empnm'];
?>
When you first request the page, PHP renders out a whole string of html, then your browser executes that generated HTML, not the original PHP. i.e. your server is going to send something like
<script>
function getdata()
{
var employee =
"hello world";
}
</script>
print them
So, as far as the web browser knows, "hello world" is just hardcoded there.
You'll need to look into AJAX for how to make it work. Check out this beginners' tutorial on using jQuery for ajax: http://www.devirtuoso.com/2009/07/beginners-guide-to-using-ajax-with-jquery/
Define a global variable
<script>
var employee = <?php echo "'" . $row['empnm'] "'";?>;
function getdata(){
return employee;
}
</script>
Now keep on changing variable employee whenever it is changed
print them
If you're in a PHP loop -- it does looks like you are, since -- you can use PHP to define the parameter to be passed into getdata() in your loop; e.g.
<script type="text/javascript">
function getdata(employee) {
// connect to database and get employee name
}
</script>
<?php
foreach ($loopData as $row) {
print 'print them';
}
?>

Categories