Parameter pass from php script to javascript function - javascript

html
<?php $test="00010387";
javascript
<script>
function browsePricebySKU(test){
alert(test);}
</script>
the output is different with the parameter. Please help me.

Try this
php code
<?php $test="00010387"; ?>
<script type="text/javascript">
function browsePricebySKU(test){
alert(test);
}
</script>
Single quotes will not be Escape, It will output $test as a string, not the value of the $test variable;

html
<?php $test="00010387";?>
(close php before starting html)
or
html
<?php $test="00010387";
echo "";

Related

Pass a php variable to a jQuery function

I have searched and tried several different methods to pass a php $variable to a jQuery function. I can pass a string simply by using myfunction("Hello");. But if I try myfunction(); or myfunction($variable); with or without quotes it fails to run.
function wholesection(val) {
$("#whole-section").slideUp("fast", function () {
});
$('#label-cemetery').text("Section*");
$('#poc').val(val);
}
The above works if I send a literal string enclosed in double quotes, using:
<?php
echo '<script>',
'wholesection("Hello");',
'</script>'
;
?>
</head>
<body>
<?php
$variable = "Hello";
echo '<script>',
'wholesection(' . $variable . ');',
'</script>'
;
?>
Or other similar variants do not work.
'wholesection($variable);',
'wholesection("$variable");',
Suppose your $variable has value "Hello".
Then this code:
echo 'wholesection('.$variable.');',
is rendrered in html like
wholesection(Hello);
See? You're passing Hello to a function. Not "Hello" but Hello.
And Hello is considered a javascript variable. I bet you don't have it.
So, the fix is - add quotes:
echo 'wholesection("'.$variable.'");',
which will be rendered as:
wholesection("Hello");
You can pass it by echoing your php varriable in the script
try below code :
<?php
$variable = "Hello";
?>
<script type="text/javascript">
var simple = '<?php echo $variable; ?>';
</script>
<?php
$variable = "Hello";
if(true){
?>
<script>
wholesection("<?php echo $variable?>");
</script>
<?
}
?>

Passing PHP Array to Javascript OnLoad

I am currently trying to pass in PHP array to a javascript Function through onload();
In my SimilarDomains.php:
<?php
$domainsJS = json_encode($similarDomainsUnique);
?>
<body onload="init(<?php echo "\"$domainsJS\""; ?>);">
I do this to pass it as a string object in order to later process the string using JSON.parse(). In the javascript i have
var obj = JSON.parse(domainsJS);
for string processing. But it seems like I have a SyntaxError: syntax error # line 1. This is the HTML Doctype. If I remove the doctype, it just goes to the next first line. it only appears when I have the body onload calling php as I did.
How can I process this php array in order to be used in JavaScript. After all this is said and done, I then have to input the processed values into a JS array.
Here is what the body onload turns out to be in the HTML
<body onload="init("{"0":"estatelawyer.com","1":"reaestatelawyer.com","2":"estately.com","3":"thestate.com","4":"estaterescue.com","5":"boisestate.edu","10":"99acres.com","11":"1point3acres.com","14":"green-acres.com","22":"backcountry.com","24":"baby-kingdom.com","25":"landattorney.com","27":"siteground.com","28":"247realmedia.com","30":"siteground.biz","31":"arealme.com","32":"farming-simulator.com","33":"amkingdom.com","34":"searchengineland.com","35":"shoretelsky.com","36":"grantland.com","38":"amsoil.com","40":"lostrealm.ca","41":"kingdomofloathing.com","42":"shorewest.com","44":"domaintools.com","45":"domain.com.au","46":"realmadridstream.net","47":"farming2015mods.com","48":"travelandleisure.com","49":"landofnod.com","51":"bringmesports.com","52":"cricketcountry.com","53":"bringthebaconhome.com\/user\/dashboard","54":"ollando.com","55":"domain.com","57":"travelandlearntrips.com","58":"scarffruit.country","59":"78land.com","92":"propertylawyer.com","93":"propertylawyergroup.com","94":"propertyattorney.com","95":"rocketlawyer.com"}");">
You should just need to echo it straight up without any extra quotes because it's a JSON object
<body onload="init(<?php echo $domainsJS ?>);">
Add the json to a var in the JS
echo <<<EOT
<script type="text/javascript">//<![CDATA[
var jsn = " . json_encode($similarDomainsUnique);
var obj = JSON.parse(domainsJS);
//]]>
</script>
EOT;
This is poor coding:
<?php
$domainsJS = json_encode($similarDomainsUnique);
?>
<body onload="init(<?php echo "\"$domainsJS\""; ?>);">
There is no reason to be jumping back and forth from PHP mode to HTML mode.
There is PHP overhead to each time you change modes.
Below is the basic proper way to create an HTML page.
I like to get the HTML on its way to the Browser ASAP. That is why I flush the output buffer somewhere just after the <body> tag and the Browser will have a few things to do preparing for Start Render.
To accomplish your passing json to <javascript> I assign the value to $js then embed $js in the `
And PHP is never switched to HTML mode.
<?php ob_start("ob_gzhandler");
header('Content-Type: text/html; charset=utf-8');
header('Connection: Keep-Alive');
header('Keep-Alive: timeout=50, max=100');
header('Cache-Control: max-age=3600');
echo <<<EOT
<!DOCTYPE html>
<html lang="en">
<head><title>Sample</title>
<style>
body{font:400 1emArial,sans-serif;color: #f00 ;}
#page{width:100%;background:#ff0;border:solid .5em #000;padding:2em;}
#contents{max-width:50em;background:#00f;margin:0 auto 0;height:10em;color:#ff0;padding:1em;}
h1{color:#000;text-align:center;}
</style></head><body><div id="page">
EOT;
ob_flush();
$js = "\nvar jsn = '" . json_encode($similarDomainsUnique) . "';\n" ;
echo <<<EOT
<h1>Headline</h1>
<p>Paragraph</p>
</div></div></body>
</html>
<script type="text/javascript">//<![CDATA[
function init(){
$js
var obj = JSON.parse(jsn);
}
window.onload = init;
//]]>
</script>
EOT;
ob_end_flush();
?>
If you need obj to be use by other functions:
<script type="text/javascript">//<![CDATA[
var obj = '';
function init(){
$js
obj = JSON.parse(jsn);
}
window.onload = init;
//]]>
</script>
EOT;
ob_end_flush();
?>

php in external javascript file

I have a the code below in my js which obviously works if the js is in the php file
filter: '<?php echo $my_cat>'
how can i make a variable maybe in the php file and pull it in my external js file?
You have to place this below code at the top part of your test.php page
<script>
var filter = '<?php echo $my_cat>';
</script>
and simply you can check it on your external.js file by alert
alert(filter);
<?php
function showme(){
echo "HelloWorld";
}
?>
<script type="text/javascript">
var my_var = '<?php echo showme(); ?>' ;
</script>
You can also use short tags.
<script>
var filter = '<?=$my_cat?>';
</script>

Add div class with php in jQuery

My variable contains a color name. My example:
<?php
$myvar = blueColour;
?>
I need to add this value to body of a html page using jQuery:
<script type="text/javascript">
jQuery(body).addClass("<?php echo $myvar; ?>");
</script>
Can I use php inside jQuery this way? Thank you.
EDIT: its an wordpress site. I use this in a if to add that class on a specific page template.
<script type="text/javascript">
jQuery("body").css("color", "<?php echo $myvar; ?>");
</script>
yes, as long as your html file is interpreted by php (having .php/.phtml extension)
I did it. Worked.
Correct is:
jQuery('body').addClass("<?php echo $myvar; ?>");
with
jQuery('body')
not
jQuery(body)
if ( is_page_template('nameOfYouTemplate.php') ) {
echo '<body class='. $myvar .'>';
} else {
echo '<body>';
}

PHP Echo Inside Javascript String

I want to be able to echo a PHP link inside a JavaScript string, i.e. <?php echo SITE_URL ?>. How can I do this with the code below?
<script type="text/javascript">
$.backstretch("http://www.example.com/bg.jpg");
</script>
<script type="text/javascript">
$.backstretch('<?php echo str_replace(array("\\", "'"), array("\\\\", "\\'"), SITE_URL); ?>');
</script>
I also made sure to escape ' and \ to avoid any problems.
you can do
<script>
var test= '<?php echo SITE_URL; ?>';// and use it as you please
</script>

Categories

Resources