This JavaScript code was in a PHP file, and I need to put this JS code into a .js file.
<script>
$j(".fresh").click(function(){
$j(this).html('<span><?php echo $this->lang_arr['my_new_func']; ?></span>');
$j.post( "<?= site_url('website/func_resh') ?>",
{ id : "<?= $webfun_one_arr[id] ?>",
website_id : "<?= $web_one_arr[id] ?>"
}
);
})
</script>
I know this code <?php echo $this->lang_arr['my_new_func']; ?> in the JavaScript format is {$this->lang_arr['my_new_func'];}
But I don't know how I change <?= site_url('website/func_resh') ?> and <?= $webfun_one_arr[id] ?> into JS format.
Thanks for any answer.
Interpolating PHP and JavaScript is a big can of worms that you should avoid opening. IMO the best way to deal with this is to use PHP to output a JSON object, which it has built-in support for, and then use the object in your JavaScript. This way you only have to put one tiny snippet of PHP in a <script> tag and you don't have to try to make the server parse .js files as PHP. Something like this:
In your PHP:
<?php $my_vals = array(
'myNewFunc' => $this->lang_arr['my_new_func'],
'postUrl' => site_url('website/func_resh'),
'postId' => $webfun_one_arr['id'],
'postWebsiteId' => $web_one_arr['id']
);
?>
<script>
$j.getScript('/path/to/your_script.js', function() {
myFunc(<%= json_encode($my_vals); %>); // turns your PHP array into a
}); // JavaScript object automatically
</script>
Then, in your_script.js:
// Look, Ma, no PHP!
function myFunc(someJson) {
$j(".fresh").click(function(){
$j(this).html('<span>' + someJson.myNewFunc + '</span>');
$j.post( someJson.postUrl,
{ id : someJson.postId,
website_id : someJson.postWebsiteId
}
);
});
}
Don't. Make it a .js.php file that returns a content type of text/javascript, and includes the other relevant PHP scripts.
Related
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'));
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");
I have this jquery code in a foreach loop. Basicaly the variable $perf gets a new value with every loop. How can I use jquery to display the different $perf value with each loop? Is it possible?
foreach ($perfs as $perf):
<script type="text/javascript">
$(document).ready(function(){
var performerName = $(".transparency").data('title');
var divcontent = $(".transparency").html();
if ( divcontent == ' ' ){
$(".transparency").html(''+performerName+'');
}
});
</script>
<div class="transparency" data-title="<? echo $perf; ?>"> </div>
endforeach;
You should do it like this:
<?
foreach ($perfs as $perf):
?>
<script type="text/javascript">
$(document).ready(function(){
var $perf = "<? echo $perf; ?>"; //Get from php
alert($perf); //Show it
//Here goes the rest of your script
var performerName = $(".transparency").data('title');
var divcontent = $(".transparency").html();
if ( divcontent == ' ' ){
$(".transparency").html(performerName);
}
});
</script>
<div class="transparency" data-title="<? echo $perf; ?>"> </div>
<?
endforeach;
?>
That's it. It works.
(I tried to modify your code at least as possible, cause I don't know if I can remove parts)
PS: There would be more 'elegant' solutions, do you want one? or this is enough?
Can you please describe what you are trying to do? I'm about 90% sure there is zero reason for any javascript, jQuery or otherwise.
Why not just do this?
<?php
foreach($perfs as $perf)
{
echo "<div class='transparency' data-title='$perf'>$perf</div>";
}
?>
Unless there is something more you are trying to do, you don't need javascript at all. And even if you do need javascript, take the function out of the loop and call it once each iteration. you dont need the exact same function defined multiple times.
I suggest you look into the relationship between server and client-side scripting. For starters - take a look at the HTML source generated by your PHP and see if thats anything close to what you want. Also, read up about ajax. It seems that you are trying to do combine PHP/javascript in such a way that it needs additional HTTP Requests (ajax calls)
It is impossible to have PHP and javascript interact directly without AJAX, and it is difficult to answer the question without more knowledge of what, exactly, you want to happen.
If you want a different transparacy div for each value of $perfs you can use:
<?php foreach ($perfs as $perf) { ?>
<div class="transparency" data-title="<?php echo $perf; ?>"> </div>
<?php } ?>
And they you can use the jquery .each() to iterate over the divs
$(".transparency").each( function() {
var performerName = $(this).data('title');
// do stuff //
});
If all you want is to pass the values in $perfs to you javascript function you can use
var perfs = <?php echo json_encode($perfs); ?>;
OK I think I see what you are trying to do now. You'll want something like this:
<script type="text/javascript">
$(document).ready(function(){
var perfs = <?php echo json_encode($perfs); ?>;
$.each( perfs, function( index, value ) {
$( ".transparency" ).append( value+'<br>' );
} );
} );
</script>
<div class="transparency"></div>
This will output each value of $perfs inside of the transparency div.
Using JQuery each and append.
You will never want to wrap an entire script in a foreach loop, as that will create a separate script for each element in the array. Using json_encode you will change the PHP array into a javascript object & you can do whatever you want to with it.
Remember javascript is only able to access elements written to the page using echo or something similar. Whatever you can see when you look at 'view page source' in your browser is all your script will be able to use.
How can we use PHP code in JavaScript?
Like
function jst()
{
var i = 0;
i = <?php echo 35; ?>
alert(i);
}
Please suggest a better way.
If your whole JavaScript code gets processed by PHP, then you can do it just like that.
If you have individual .js files, and you don't want PHP to process them (for example, for caching reasons), then you can just pass variables around in JavaScript.
For example, in your index.php (or wherever you specify your layout), you'd do something like this:
<script type="text/javascript">
var my_var = <?php echo json_encode($my_var); ?>;
</script>
You could then use my_var in your JavaScript files.
This method also lets you pass other than just simple integer values, as json_encode() also deals with arrays, strings, etc. correctly, serialising them into a format that JavaScript can use.
If you put your JavaScript code in the PHP file, you can, but not otherwise. For example:
page.php (this will work)
function jst()
{
var i = 0;
i = <?php echo 35; ?>;
alert(i);
}
page.js (this won't work)
function jst()
{
var i = 0;
i = <?php echo 35; ?>
alert(i);
}
PHP has to be parsed on the server. JavaScript is working in the client's browser.
Having PHP code in a .js file will not work, except you can tell the server to parse the file you want to have as .js before it sends it to the client. And telling the server is the easiest thing in the world: just add .php at the end of the filename.
So, you could name it javascript.php. Or, so you know what this file is PRIMARILY, you could name it javascript.js.php - the server will recognize it as .php and parse it.
This is the bit of code you need at the top of your JavaScript file:
<?php
header('Content-Type: text/javascript; charset=UTF-8');
?>
(function() {
alert("hello world");
}) ();
Yes, you can, provided your JavaScript code is embedded into a PHP file.
You're pretty much on the ball. The only difference is I'd separate out the JavaScript code so the majority was in an external static file. Then you just define variables or call a function from the actual PHP page:
<script type="text/javascript>
function_in_other_file(<?php echo my_php_var; ?>);
</script>
A small demo may help you:
In abc.php file:
<script type="text/javascript">
$('<?php echo '#'.$selectCategory_row['subID']?>').on('switchChange.bootstrapSwitch', function(event, state) {
postState(state,'<?php echo $selectCategory_row['subID']?>');
});
</script>
Here is an example:
html_code +="<td>" +
"<select name='[row"+count+"]' data-placeholder='Choose One...' class='chosen-select form-control' tabindex='2'>"+
"<option selected='selected' disabled='disabled' value=''>Select Exam Name</option>"+
"<?php foreach($NM_EXAM as $ky=>$row) {
echo '<option value='."$row->EXAM_ID". '>' . $row->EXAM_NAME . '</option>';
} ?>"+
"</select>"+
"</td>";
Or
echo '<option value=\"'.$row->EXAM_ID. '\">' . $row->EXAM_NAME . '</option>';
We can't use "PHP in between JavaScript", because PHP runs on the server and JavaScript - on the client.
However we can generate JavaScript code as well as HTML, using all PHP features, including the escaping from HTML one.
I have a PHP script that retrieves names (strings) from database. I would like to pass this array to Javascript using $.ajax().
I cannot understand how should I encode the array in PHP and then decode it in Javascript.
Could someone give an example code for this ?
Thanks a lot !!
<?php // test.php
$myArray = array(1, 2, 3);
echo json_encode($myArray);
?>
HTML File:
$(function() {
$.getJSON('http://localhost/test.php', function(data) {
$(data).each(function(key, value) {
// Will alert 1, 2 and 3
alert(value);
});
});
});
u can use json_encode
<?php
$arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);
echo json_encode($arr);
?>
full example you can read at :
http://www.prodevtips.com/2008/08/15/jquery-json-with-php-json_encode-and-json_decode/
or
http://www.prodevtips.com/2009/12/09/multiple-select-lists-with-jquery-and-json/
<?php
echo json_encode(array('key' => 'value', 'cool' => 'ice'));
?>
json is a javascript object. So there is no need to "decode" it. However, it looks like you are using jquery. There is a nifty function for retrieving json data:
jQuery.getJSON(url, senddata, function(returndata){alert(returndata.cool);})
or
jQuery.getJSON(url, senddata, function(returndata){mybigfunction(returndata);})
mybigfunction(data)
{
myvar = data.cool;
alert(myvar);
}
http://api.jquery.com/jQuery.getJSON/
or you could also do it with $.ajax as you mentioned:
jQuery.ajax({
url: url,
dataType: 'json',
data: senddata,
success: function(data){mybigfunction(data)}
});
mybigfunction(data)
{
myvar = data.cool;
alert(myvar);
}
http://api.jquery.com/jQuery.ajax/
The "callback" is a function that gets called and passed the json data returned from the url.
You will 'ice' baby... ermm... sorry for the corn.
The getJSON method is rather short and handy. Have a look at the links for more details.
This is Php File Code
<?php
$array = array(1, 2, 3);
echo json_encode($array);
?>
Then you can parse $array in your $.ajax() like this
success: function (data) {
var x = JSON.parse(data);
console.log(x);
}
To do this, you'll just have to echo out a script into the PHP page that contains your data, which you can then access from any other Javascript on the page, including jQuery and .ajax().
Again, if you just want to pass it via an AJAX call, just use json_encode():
<?php
echo json_encode(
array(
'groupidlist'=>$groupids,
'groupnamelist'=>$groupnames,
'serverurl'=>$serverurl,
'uid'=>$curuser->getID()
)
);
?>
And then process it with the callback functions from .ajax() or, probably better, .getJSON(), which is built for just this use.
I promise I don't just spam my blog here, but I wrote a post on passing variables between Javascript and PHP, because I did it often enough that I came up with a simple/reliable/clean and reusable way to do so. If you're regularly passing data from PHP to Javascript and don't need AJAX, I'll paste the essentials here:
At the top of each external js file, I add comments as to which PHP variables are required, so I can keep track of what I need when I include it (this is optional, of course, but nice):
/* This script depends on the following variables in phpvars:
groupidlist
groupnamelist
serverurl
uid
*/
Then, in the PHP file, I pass the needed variables with a single line of Javascript, assigning a JSON Array with all the needed values. Examples in PHP, directly from my code:
<script type="text/javascript">
var phpvars = <?php
echo json_encode(
array(
'groupidlist'=>$groupids,
'groupnamelist'=>$groupnames,
'serverurl'=>$serverurl,
'uid'=>$curuser->getID()
)
);
?>;
</script>
Once that is set up, I can then simply access whatever PHP Variables I need in the Javascript through the phpvars array. For example, if I needed to set an image source using my serverurl, I could do as follows:
imgElement.src = phpvars.serverurl + '/images/example.png';
Because it uses JSON, there is no worrying about making sure that you don't screw anything up in your Javascript by trying to insert the PHP variables. The encoding/decoding of the variables is handled on both ends by built-in JSON functions, so it is very hard to break it, and brainless to pass variables - you pass them like you would any other PHP array. In my fiddling that led to this, I had problems with both of these, and this solution takes care of them nicely.