How to properly echo PHP variables within JS script? - php

I have this script that needs to print and it is within a PHP file as I need to pass it options because I am using the jQuery UI Tabs plugin.
Here is what I have:
<?php
$collapsible = "true";
$active = "2";
$options = array( 'collapsible' => $collapsible, 'active' => $active );
?>
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery( '.tabs' ).tabs({
collapsible : <?php echo $options["collapsible"]; ?>,
active : <?php echo $options["active"]; ?>
});
});
</script>
Ok so everything works however the two options collapsible and active isn't effecting it. But if I bypass the php variables and just hardcode the option settings in for collapsible and active, then it works. So I am not sure why the variables have no effect. I've even tried type casting it with (int) for active and (bool) for collapsible but still no dice.
Thanks for looking.

Rather than adding quotes, run the value through json_encode. This will ensure proper escaping as well:
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery( '.tabs' ).tabs({
collapsible : <?php echo json_encode($options["collapsible"]) ?>,
active : <?php echo json_encode($options["active"]) ?>'
});
});
</script>
It also gives you the added benefit of being able to use literal types as opposed to all strings in your PHP:
<?php
$collapsible = true;
$active = 2;
And, per axel.michel suggestion in comments, could be simplified to:
<?php
$options = array('collapsible' => true, 'active' => 2);
?>
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery( '.tabs' ).tabs(<?php echo json_encode($options); ?>);
});
</script>

Try adding quotes around the values and encode the output
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery( '.tabs' ).tabs({
collapsible : '<?php echo $options["collapsible"] ); ?>',
active : '<?php echo $options["active"] ); ?>'
});
});
</script>

Related

jQuery - Pass variable to php

I'm very new to this and I've searched around all day today to get it working but I haven't managed to find a way to use a variable, only hard-coded values work. Here is my code with a hard-coded value:
<script type="text/javascript">
FB.Event.subscribe('edge.create',
function(response) {
$.post("http://www.my-domain.com/fbtest.php", { category: "845" } );
}
);
</script>
What I'd like to have is change that 845 value to a variable called $vpostid. When I change it to that it doesn't work, so I assume I need to get the double quotation marks around the number but I can't see to get the correct combination.
I'm assuming you mean "pass variable from php":
If short hand openings are enabled:
<script type="text/javascript">
FB.Event.subscribe('edge.create',
function(response) {
$.post("http://www.my-domain.com/fbtest.php", { category: "<?=$vpostid?>" } );
}
);
</script>
else:
<script type="text/javascript">
FB.Event.subscribe('edge.create',
function(response) {
$.post("http://www.my-domain.com/fbtest.php", { category: "<?php echo $vpostid; ?>" } );
}
);
</script>
try this code:
<script type="text/javascript">
FB.Event.subscribe('edge.create',
function(response) {
$.post("http://www.my-domain.com/fbtest.php", { category: "<?php echo($vpostid); ?>" } );
}
);
</script>

jquery and strings from php code

I have a problem how to pass for example $example=1; variable to this jquery like a value in bracket where is 20, 40, 60.....:
<script type="text/javascript">
$(document).ready(function() {
$("#pb1").progressBar(20);
$("#pb2").progressBar(40);
$("#pb3").progressBar(60);
$("#pb4").progressBar(70);
$("#pb5").progressBar(100);
$("#pb6").progressBar(100);
});
</script>
The main problem is that I want to example string have value from database, so that's why I need to make it outside of script.
If this code is in your .php page...
<script type="text/javascript">
$(document).ready(function() {
$("#pb1").progressBar(<?php echo $pb1 ;?>);
$("#pb2").progressBar(<?php echo $pb2 ;?>);
$("#pb3").progressBar(<?php echo $pb3 ;?>);
$("#pb4").progressBar(<?php echo $pb4 ;?>);
$("#pb5").progressBar(<?php echo $pb5 ;?>);
$("#pb6").progressBar(<?php echo $pb6 ;?>);
});
</script>
Where $pb1,$pb2,$pb3,$pb4,$pb5,$pb6 are Integers ..
This is simple:
<?php
//Insert your code to generate the values to $example
$example = ...
?>
// and here is your JS with php code inside it
<script type="text/javascript">
$(document).ready(function() {
$("#pb1").progressBar(<?php echo $example; ?>);
$("#pb2").progressBar(<?php echo $example1; ?>);
$("#pb3").progressBar(<?php echo $example2; ?>);
$("#pb4").progressBar(<?php echo $example3; ?>);
$("#pb5").progressBar(<?php echo $example4; ?>);
$("#pb6").progressBar(<?php echo $example5; ?>);
});
</script>
I hope it helps! Good Luck!
If you meant to pass php variable to client to dynamically replace numbers in jquery you can use like code in below
<script type="text/javascript">
$(document).ready(function() {
$("#pb1").progressBar(<?php echo example; ?>);
});
</script>
First off, having it in your database does not mean you cannot do so in the script. There are in fact several ways to do that. You could have your javascript file be php that generates javascript instead of html, or perhaps easier: you could use inline javscript. However, if you do want to keep the two separated it is still possible:
[..]
<script type='text/javascript'>var percentageDone = <?php echo intval($example) ?>;</script>
<script type="text/javascript">
$(document).ready(function() {
$("#pb1").progressBar(percentageDone);
});
</script>
[..]

How do I pass the value of a PHP variable to Javascript code?

I need help with putting this $id value into the javascript below
PHP:
<?php
$id = NULL;
$username = 'YouTube';
$xml = simplexml_load_file(sprintf('http://gdata.youtube.com/feeds/base/users/%s/uploads?alt=rss&v=2&orderby=published', $username));
if ( ! empty($xml->channel->item[0]->link) )
{
parse_str(parse_url($xml->channel->item[0]->link, PHP_URL_QUERY), $url_query);
if ( ! empty($url_query['v']) )
$id = $url_query['v'];
}
echo $id; // Outputs the video ID.
?>
JS: Need $id value ---> 'I need the value to go right here'
<script type="text/javascript">
$('document').ready(function() {
var options = { videoId: 'I need the value to go right here', start: 3 };
$('#video1').tubular(options);
});
</script>
Do something like this....
<script type="text/javascript">
$('document').ready(function() {
var options = { videoId: '<?php echo $id?>', start: 3 };
$('#video1').tubular(options);
});
</script>
But make sure, you are including this script in php file.
Other solution could be to use html hidden variable, and access that value using js.
by the use of
<script type="text/javascript">
....
</script>
I understand you're using javascript inside of your view! then why not just do this
var options = { videoId: '<?php echo $id; ?>', start: 3 };
Use
<script type="text/javascript">
var id= '<?= $id; ?>';
</script>
now you can use the id variable in your javascript
<script type="text/javascript">
$('document').ready(function() {
var options = { videoId: id, start: 3 }; // id variable which is filled by $ib variable of php
$('#video1').tubular(options);
});
</script>

How to merge php-mysql data with jquery to fade data

I'm having a simple select statement using php-mysql and I have this script to change text with another.
<script type="text/javascript">
$(document).ready( function() {
$('#deletesuccess').delay(500).fadeOut(function(){
$('#deletesuccess').html("text2");
$('#deletesuccess').delay(500).fadeIn("slow");
});
});
</script>
<div id=deletesuccess > text1 </div>
Trying to display data from table using php-mysql and jquery above script but it's displaying only the last row the loop is not working
$getTextQ = "select * from text";
$getTextR = mysql_query($getTextQ);
while($row = mysql_fetch_array($getTextR)){
?>
<script type="text/javascript">
$(document).ready( function() {
$('#deletesuccess').delay(500).fadeOut(function(){
$('#deletesuccess').html("<?php echo $row['desc']; ?>");
$('#deletesuccess').delay(500).fadeIn("slow");
});
});
</script>
<?php
}
But couldn't use it with the above PHP code to display data one by one.
You can do this easily by using jQuery ajax.
<script type="text/javascript">
$(document).ready( function() {
$.ajax({
url: 'getData.php',
dataType: 'json',
type: 'POST',
success: function(data) {
$('#deletesuccess').delay(500).fadeOut(function(){
$.each(data,function(key, value){
$('#deletesuccess').html(value);
$('#deletesuccess').delay(500).fadeIn("slow");
});
});
}
});
});
</script>
Now in getData.php page you need to do query and echo json_encode data. That means the getData.php file should contain the following code:
<?php
$getTextQ = "select * from text";
$getTextR = mysql_query($getTextQ);
$json = '';
while($row = mysql_fetch_array($getTextR)){
$json .= $row['desc'];
}
echo json_encode($json);
?>
Attention, you have not a clear difference between php and javascript code execution. The php code will make an echo of that javascript code, and after php has finish execution(on document ready) the javascript code will be executed at istant, so the last echo of javascript will have effect in the execution. try to separate the codes.
The problem is that you overwrite your JavaScript each time the loop runs. Instead you should make it like this:
<script type="text/javascript">
var php_results = '';
</script>
<?php
$getTextQ = "select * from text";
$getTextR = mysql_query($getTextQ);
while($row = mysql_fetch_array($getTextR)){
?>
<script type="text/javascript">
php_results += "<?php echo $row['desc']; ?> | ";
</script>
<?php
}
?>
<script type="text/javascript">
$(document).ready( function() {
$('#deletesuccess').delay(500).fadeOut(function(){
$('#deletesuccess').html(php_results);
$('#deletesuccess').delay(500).fadeIn("slow");
});
});
</script>
Of course this would have to be cleaned up to make it pretty, but it should work. I added the pipe as a separator between the different descriptions from the database.

Requirejs doesn't load jquery1.7 from CDN as module

I need to load jQuery1.7 as module, I've seen this code of #jrburke:
requirejs.config({
paths: {
'jquery' : 'http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min'
}
});
require(['jquery'], function($) {
//$ points to jQuery
});
It's not very useful for me, because all .js name are generated by server-side, I got them from php-array.
So, I wrote this:
require(['http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js'],
function($) {
//$ points to jQuery
});
But $ is null inside this function.
UPDATE:
Here is my php-template that render my js-scripts for this page:
<script src="http://requirejs.org/docs/release/1.0.1/minified/require.js">
</script>
<script>
require([
<?php echo "'". implode("',\n\t'", $this->scripts) . "'\n"; ?>
], function($){
console.warn ($); // null ;(
// loaded jQuery
window.$ = $;
// Load main client script for this page
boot( '<?php echo $this->eprint($this->content_page); ?>' );
});
</script>
and it is my php-array for this page (page index):
$scripts = array(
'http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js',
'http://ajax.microsoft.com/ajax/jquery.templates/beta1/jquery.tmpl.min.js',
'/js/libs/jquery.history.js?v=1321687090',
'/js/libs/coolclock.js?v=1321629683',
'/js/libs/excanvas.js?v=1321629683',
'/js/client.modules.js?v=1321703735',
'/js/client.all.js?v=1322512192',
'/js/boot.js?v=1322512037',
'/js/client.index.js?v=1321689884'
);
Have your php array of the form:
$jquery = array (
'jQuery' => 'http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js'
);
Then try:
requirejs.config({
paths: <?php echo json_encode($jquery) ?>
});
require(['jquery'], function($) {
//$ points to jQuery
});

Categories