How to pass a variable from php to javascript - javascript

If I pass an hard coded numeric value from php to javascript, all works perfectly. But if i pass the numeric value from a variable, i get an error:
javascript file (gallery.js)
function goto_anchor(id)
{
var anchor = $("#anchor_" + id);
$('html,body').animate({
scrollTop: anchor.offset().top - 20
}, 1200);
}
php file
....
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js" type="text/javascript"></script>
<script src="js/gallery.js" type="text/javascript"></script><?php
$get_cat = 4;
if (isset($get_cat)) { ?>
<script>
$(document).ready(function() {
goto_anchor(4); // this will work PERFECTLY!!!
goto_anchor(<?php echo $get_cat; ?>); // this will NOT work !!!
});
</script><?php
} ?>
I need to pass the $get_cat variable in my php, not the harcoded numeric value. How ??
Thanks

I have such kind of problems before, can not fill
javascriptfunction(<?php echo $phpvirable ?>)
inside javascript function that causes error; Instead , according to your code, can echo it to javascript virable first before using it;
echo '<script> var get_cat = '.$get_cat.'</script>';
into your php
<?php $get_cat = 4; ?>
surely, Your php $get_cat can be captured from such as $_REQUEST['cat'] dynamic value from form submit event towards this page. then u convert it to javascript virable to use in function.
<?php
if(isset($getcat)):
echo '<script> var get_cat = '.$getcat.'</script>';
endif;
?>
// javascript function read predefined javascript virable that confirm work.
// u also avoid using mixed php and javascript statements which looks messy
<script>
$(document).ready(function() {
goto_anchor(get_cat); // this will work then.
});
</script>

Related

How can i use PHP variable (fetch_array) on JS ? (json encode)

I want to use code like this in script for my functions:
<script>
function selectCust(){
var data = <?php echo json_encode("$rs['name']"); ?>;
document.getElementById("txtfield").value = data;
}
</script>
I didn't work, i didn't want to use the hidden field. So, how will it work in simple way. thank you.
Try this one
<script>
function selectCust(){
var data = "<?php echo json_encode($rs['name']); ?>";
document.getElementById("txtfield").value = data;
}
</script>
Drop those double quotes around PHP variable:
<script>
function selectCust(){
var data = <?php echo json_encode($rs['name']); ?>;
document.getElementById("txtfield").value = data;
}
</script>
Otherwise PHP will parse that string literally and you will just put "$rs['name']" string into your txtfield element.

Unable to show php variable in javascript?

I am unable to show php variable in javascript;
this is my code here:
<script type="text/javascript">
$(document).ready(function (){
var n=<?php echo json_encode($count)?>;
for(var i=0;i<n;i++){
var div = document.createElement('div');
div.className = "d5";
div.id=i+1;
document.getElementById('wrapper').appendChild(div);
<?php
$query="select * from shop_product where shop_uniqueid='$unq'";
$result=mysql_query($query);
while($row=mysql_fetch_array($result))
{
$product=$row["in_product"];
?>
var product=<?php echo $product?>;
$('#'+div.id).html(product);
<?php
}
?>
}//for loop ends
});//ready ends
</script>
here i am trying to pass var product in html() of which value is coming from php like: var product=<?php echo $product?>;
but when doing so php value is not coming in Javascript's var product.
when I pass $('#'+div.id).html("abcd"); abcd value is showing in divs.
please help me.
Compare the first place you take data from PHP and put it in JavaScript:
var n=<?php echo json_encode($count)?>;
with your attempt to assign the product value:
var product=<?php echo $product?>;
You haven't converted the data from plain text to JavaScript in the second line. Use json_encode there too.

echo JS functions with PHP variables from SQL query

I have functions stored in SQL table that I need to use inside JS. The problem is, that I also need to use PHP variables in these functions.
The following:
<?php
$container='11';
$title='Header';
$function_text =
<<<EOT
$(function() {
$('#container$container').parent('div').find('h3').html('$title');
});
EOT;
echo $function_text;
?>
returns correctly:
$(function() {
$('#container11').parent('div').find('h3').html('Header');
});
but this one:
<?php
$ID=1;
$container='11';
$title='Header';
$article = $cls -> Query(sprintf('SELECT * from graphs WHERE ID="%s"', $ID));
$function_text = $article[0]['function'];
echo $function_text;
?>
prints exactly the contents of SQL field, without recognising variables:
$(function() {
$('#container$container').parent('div').find('h3').html('$title');
});
How could I get the variables to be injected to echoed text?
Change the data that is stored in your database, so that it uses format placeholders instead of references to variables:
$(function() {
$('#container%s').parent('div').find('h3').html('%s');
});
Use sprintf():
$function_text = sprintf($article[0]['function'], $container, $title);

Using JS within PHP for an if window.width issue

I'm wanting to echo some code based on whether the user is on a mobile device (less than 768px) or larger.
I have done the following:
<?php
if ( is_home() ) {
?>
<script type="text/javascript">
if ($(window).width() < 768) {
document.write("<?php echo my_shortcode("[mobile-slider]"); ?>");
} else {
document.write("<?php echo my_shortcode("[desktop-slider]"); ?>");
}
</script>
<?php
} else {
//do the stuff for the other pages
} ?>
But now when the homepage renders it displays "); } else { document.write(" then the homepage slider and then "); }. Any idea why?
JS error
SyntaxError: unterminated string literal
document.write('
HTML Output - Seems to be adding a line break which I think is breaking the script?
<script type="text/javascript">
if ($(window).width() < 768) {
document.write("
<!--slider-->
"<?php echo my_shortcode("[mobile-slider]"); ?>"
CHANGE TO
"<?php echo my_shortcode('[mobile-slider]'); ?>"
^ ^ // changed quotes here
or escape quotes
"<?php echo my_shortcode(\"[mobile-slider]\"); ?>"
try this:
document.write(<?php echo "\"[mobile-slider]\""; ?>);
Well your quotes are definately off, as others have mentioned, your inner quotes must be different from the outer ones, or escaped.
Is it possible for you to run your php function in the main document(outside of the javascript), then choose to show/hide/alter its contents with the javascript?
If that's not possible, try calling your function directly, instead of through the do_shortcode hook.
As a final alternative, you may need to use an ajax call here. I don't know that you're able to call shortcodes the way you're attempting to do here.

php array to external page using jquery

I have a php page to creates a multi-dimentional array called $results.
I would like to:
catch submit of a form button
override default behavior of the submit using jQuery
copy and process $results on separate php using $.post
I have this which is not currently working and am not sure why?:
<form id='download_to_excel' method="post">
<input type="image" name="submit" value="submit" id='xls_download_button' src='images/common/buttons/download.png'>
</form>
<?php
$json_results = json_encode($results);
?>
<script type='text/javascript'>
$(document).ready(function(){
alert($json_results);
$("#xls_download_button").click(function(e){
alert('clicked');
e.preventDefault();
download_xls();
});
function download_xls(){
$.post('./libs/common/export_data_to_excel.php', {json_data : json_results};
}
});
</script>
When selecting the xls_download_button, the alert() never fires nor does any data get passed to export_data_to_excel.php
The export_data_to_excel.php file has the following:
<?php
$results = json_decode($_POST['json_data']);
#include the export-xls.class.php file
require_once('export-xls.class.php');
$date = date('Y-m-d');
$filename = "contacts_search_$date.xls"; // The file name you want any resulting file to be called.
#create an instance of the class
$xls = new ExportXLS($filename, $results);
#lets set some headers for top of the spreadsheet
$header = "Searched Contact Results"; // single first col text
$xls->addHeader($header);
#add blank line
$header = null;
$xls->addHeader($header);
$header = null;
$row = null;
foreach($results as $outer){
// header row
foreach($outer as $key => $value){
$header[] = $key;
}
// Data Rows
foreach($outer as $key => $value){
$row[] = $value;
}
$xls->addRow($header);//add header to xls body
$header = null;
$xls->addRow($row); //add data to xls body
$row = null;
}
# You can return the xls as a variable to use with;
# $sheet = $xls->returnSheet();
#
# OR
#
# You can send the sheet directly to the browser as a file
#
$xls->sendFile();
?>
I do know that the $json_results does display proper JSON encoded values when echoed. But from there are not sure why the rest of the javascript does not run; the alerts never fire nor does the JSON data get passed?
Can you see why this isn't working?
Your PHP-supplied json is not stored as a javascript variable in your js.
$(document).ready(function(){
var json_results = <?php echo $json_results; ?>;
...
This code shouldn't run:
function download_xls(){
$.post('./libs/common/export_data_to_excel.php', {json_data : json_results};
}
It is invalid (the ; doesn't belong there). Try this code:
function download_xls(){
$.post('./libs/common/export_data_to_excel.php', {json_data : json_results});
}
Right now you are just setting a php variable called $results you need to transfear it to you javascript.
<script type="text/javascript">
// set javascript variable from php
var $results = "<?php echo json_decode($json_data); ?>";
</script>
For sure you have an error in your javascript code (you were not closing the parenthesis after $.post), should be:
$(document).ready(function() {
alert($json_results);
$("#xls_download_button").click(function(e) {
alert('clicked');
e.preventDefault();
download_xls();
});
function download_xls() {
$.post('./libs/common/export_data_to_excel.php', {
json_data: json_results
});
}
});
Then you should assign your JSON to a javascript variable inside document.ready
$(document).ready(function() {
var json_results = <?php echo($json_results);?>;
You can't pass a PHP variable to the JavaScript like that: there live in totally different worlds. Use Ajax to get the JSON data from JS.

Categories

Resources