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'));
Related
I have a php file which uses a script within it.
I'm trying to get an image called by php (the_main_image) and prepend a set of links with this image (along with a favicon which is currently working fine) using jQuery. Here's what I have so far but it currently breaks the function
<script>
jQuery(document).ready(function($) {
$("#lesen").click(function() {
var bla = $('#my_hidden_input').val();
var test = "<?php the_main_image(); ?>";
$.ajax({
url: bla,
dataType: "text",
success: function(data) {
$(".text").html(data);
$(".text a[href^='http']").each(function() {
$(this).prepend(test);
$(this).prepend('<img src="https://www.google.com/s2/favicons?domain=' + this.href + '">');
});
}
});
});
});
</script>
How can I use jQuery var values that contain php within a prepend or other similar jQuery functions?
Hi I have done similar thing in my project, below worked for me.
Since you cannot write php directly in JavaScript, you need take help of your html.
Create a hidden input field in you html like below
<input type="hidden" id="something" value="<?php the_main_image(); ?>"/>
Then read this in jquery like
<script>
jQuery(document).ready(function($) {
$("#lesen").click(function() {
var bla = $('#my_hidden_input').val();
var test = $("#something").val();
$.ajax({
url: bla,
dataType: "text",
success: function(data) {
$(".text").html(data);
$(".text a[href^='http']").each(function() {
$(this).prepend(test);
$(this).prepend('<img src="https://www.google.com/s2/favicons?domain=' + this.href + '">');
});
}
});
});
});
</script>
hope this helps.
If your function in php does not echo result. Try to add echo. <?php echo the_main_image(); ?>. Seems like you forgot to echo result.
P.S. You can render results from php, even use it inside js code that placed in php files, but you should remember that mixin php with js is bad practice, and should be done cautiously.
How it works: php interpreter read your file before send static html to user and interpret all php related cod inside <?php ?>, if you echoing something it will appears in that row where you do this (or call function than do echoing). As mentioned by somebody if you echoing string with quotes it can break the js if you inline your php tags inside the same type of quotes.
Try to use ajax to get php value in jquery funcion.
I'm trying to figure out the least obtrusive and least computationally expensive way to store PHP objects coming from my MySQL database such that their data can be rendered by JavaScript on click by a user.
Currently, I'm storing the data as custom attributes on a button. But this generates a lot of code and I've heard is "slow". I'm wondering if I should JSON encode my PHP object, $items (see below), and how that JavaScript would then look. Note I'm using Codeigniter for the PHP so that's what up with the alternate foreach loop syntax.
Here's where I'm at so far with the HTML/PHP:
<img id="img"></img><a id="url"></a> <!--elements where data is rendered on click-->
<? foreach($items as $item):?>
<button data-id="<?=$item->id?>" data-url="<?=$item->url?>" data-img="<?=$item->img?>">click<?=$item->id?></button>
<?endforeach;?>
And here's my JS:
$(document.body).on('click', 'button', function(){
var $this=$(this), id=$this.data('id'), url=$this.data('url'), img=$this.data('img');
$('#img').attr('src', img);
$('#url').attr('href', url).html(url);
});
Most of my site's data is coming from PHP via MySQL and I've long been confused by the issue of when should I convert that data to a JavaScript array/JSON or not.
If you json_encode your $items array (assuming it only consists of data you will want in JS), you can assign this to a JS variable:
<script>var items = <?php echo json_encode($items); ?></script>
You can then remove the data-url and data-img attributes. Then, within your JS code:
var $this = $(this), id = $this.data('id'), url = items[id].url, img = items[id].img;
// the rest of your code
Edit: when you move the click handler in a separate file, you would get something like this:
function setup_click(items) {
var $img = $('#img'), $url = $('#url');
$('button').click(function(evt) {
var id = $(this).data('id'),
url = String(items[id].url),
img=String(items[id].img);
$url.attr('href', url).html(url);
$img.attr('src', img);
});
}
here's a JSfiddle showing off the javascript/JSON part: http://jsfiddle.net/fz5ZT/55/
To call this in one shot from your template:
<script src="[your ext script file path].js"></script>
<script>setup_click(<?php echo json_encode($items); ?>);</script>
Hope that helps :)
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.
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.
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;