This is really weird..
I need to send a couple of variables through to jquery from PHP.. one is an INT and the other a string.
When $a is an INT it works fine but when i use a string, i get this error.. Uncaught ReferenceError: testString is not defined
Here is my code.
<?php $a = 'testString'; ?>
<script type="text/javascript">
var a = <?php echo $a; ?>;
alert(a);
</script>
I assumed that i needed to stick a (int) or (string) before the variable, but i wasn't entirely sure how to and unsuccessful in my googles/attempts.
Any ideas?
You forgot the quotes to make the value of var a a string:
var a = "<?php echo $a; ?>";
What you're writing into the document is:
var a = testString;
so javascript is looking for a variable called testString. Instead, you want the result to be:
var a = "testString";
so make sure you include the quotes around what php is writing in.
There are quotes missing in javascript code:
<script type="text/javascript">
var a = '<?php echo $a; ?>';
alert(a);
</script>
Related
Hiii Everyone,
<script src="../../record/recordmp3.js?id=<?php echo $_GET['id'];?>&&test_no=<?php echo $_GET['test_no'];?>"></script>
<script type="text/javascript" data-my_var_1="some_val_1" data-my_var_2="some_val_2" src="/js/somefile.js"></script>
And I tried to get that passing value in recordmp3.js is
var student_id = this_js_script.attr('data-my_var_1');
var test_no = this_js_script.attr('data-my_var_2');
And also by
var student_id = "<?php echo $_GET['id'];?>";
var test_no = "<?php echo $_GET['test_no'];?>";
And my value is not passing correctly.Instead only '0' is passing In my index page I have some PHP variable value I need to pass that value to recordmp3.js file.Please help me to solve this issue.Thank you so much in advance.
I tried like below its working fine
<script src="../../record/recordmp3.js"></script>
<script type="text/javascript">
MYLIBRARY.init(["<?php echo $id; ?>", "<?php echo $test_no; ?>"]);
MYLIBRARY.helloWorld();
</script>
var MYLIBRARY = MYLIBRARY || (function(){
var _args = {}; // private
return {
init : function(Args) {
_args = Args;
// some other initialising
},
helloWorld : function() {
window.id= _args[0];
window.test_no= _args[1];
}
};
}());
You need to convert these values to json array. You cannot directly assign the php values to JavaScript variables.
Hope this answer is useful. Please let me know if you find any difficulties on converting to json value.
.js files don't execute and compile the php files,so in order to access the php variables in javascript the file should be .php.
script.php
<?php
$foo = 'Hello cool';
?>
<script>
var foo ='<?php echo $foo ?>';
console.log(foo);
</script>
i hope this example will solve your issue
When I load a php page, i put within a javascript function, a name. The problem comes when this string has special chars like '.
Here I paste the code of a click event:
showSocialShare(event, '<?php echo $object->slug; ?>', '<?php echo htmlspecialchars($object->title); ?>', '<?php echo $object->image; ?>')
I thought that the function htmlspecialchars code somehow the string but the result is:
showSocialShare(event, '4049269', 'collection-'Noun'', '/img/Original.jpg')
As can be seen, at the second parameter, the name contains characters like ' and arises an error.
How can I avoid this?
Never output text from PHP directly into a Javascript context. As you're finding out, it's VERY easy to generate JS syntax errors.
Always use json_encode: e.g. given this
<?php $foo = 'bar'; ?>
<script>
var badly_broken = <?php echo $foo ?>;
var working_fine = <?php echo json_encode($foo); ?>;
</script>
You'll end up with
<script>
var badly_broken = bar; // oops - undefined variable "bar"
var working_fine = "bar";
</script>
And note that if you're outputting JS into an HTML attribute, you not only have to generate valid Javascript, you have to output valid HTML AS WELL:
<?php $foo = array('bar' => 'baz'); ?>
<a onclick="brokenCall(<?echo json_encode($foo) ?>)">
<a onclick="workinCall(<? echo htmlspecialchars(json_encode($foo)) ?>)">
produces:
<a onclick="brokenCall({"bar":"baz"})">
^--start attribute
^--end attribute - ruhroh
<a onclick="workingCall({"bar":"baz"}")>
I have got the most biggest problem, I have see.
piece of code (just and example, the main example use database querys):
<?php $var1="999"?>
<script>
bigvar= <?php echo json_encode($var1); ?>;
var lolo = {
big: 2
}
lolo.big=bigvar;
alert(lolo.big);
</script>
Problem:
It does not recognize the PHP variable (it doesn't change to 999 value), and passing php value to javascript variable, doesn't work.How can help me ?.It is a big issue.
you should add quotes while assigning value from php variable to javascript, like as follows
<script>
bigvar= "<?php echo json_encode($var1); ?>"
var lolo = {
big: 2
}
lolo.big=bigvar;
alert(lolo.big);
</script>
and its </script>, not </scripts>
<script>
var bigvar= "<?php echo($var1); ?>"
var lolo = {
"big": "2"
}
lolo.big=bigvar;
alert(lolo.big);
</scripts>
The above example works fine for me..Try it
You have to add quotes around your php, so your JS know that this value is a string.
bigvar = "<?php echo json_encode($var1); ?>";
First of all, this question looks a duplicate of Pass a PHP array to a JavaScript function, but I actually used the first solution of Pass a PHP array to a JavaScript function - and it doesnt seem to work:
More specifically, the php echo line in the code below seems to create erroneous js output according to console error message( Uncaught SyntaxError: Unexpected token <); the console shows created html starting with "var s1 = <br />
<font size='1'><table class='xdebug-error xe-notice' dir='ltr' border='1'..."
...while I'd expect a clean var s1 = [1,2,3,4,5,6,7,8,9] - the result I also see when I tested the echo line in ideone.com
Any idea why the echo line is creating this stuff, and how to fix this?
Related joomla php code:
<?php
// No direct access to this file
defined('_JEXEC') or die('Restricted access');
$document = JFactory::getDocument();
//add jqplot libraries
JHtml::_('jquery.framework');
JHTML::script(JUri::root() .'media/system/js/jquery.jqplot.min.js');
//$document->addStyleSheet(JUri::root() .'media/system/js/jquery.jqplot.min.css');
JHtml::stylesheet( JUri::root() . 'media/system/js/jquery.jqplot.min.css' );
JHTML::script(JUri::root() .'media/system/js/jquery.jqplot.min.css');
JHTML::script(JUri::root() .'media/system/js/jqplot.barRenderer.min.js');
JHTML::script(JUri::root() .'media/system/js/jqplot.categoryAxisRenderer.min.js');
JHTML::script(JUri::root() .'media/system/js/jqplot.pointLabels.min.js');
JHTML::script(JUri::root() .'media/system/js/jqplot.enhancedLegendRenderer.js');
JHTML::script(JUri::root() .'media/system/js/weqlib.js');
$chartvals = array(1,2,3,4,5,6,7,8,9);
?>
<head>
<script type="text/javascript">
jQuery(document).ready(function(){
var s1 = <?php echo json_encode(chartvals); ?>; //!the echo seems to create erroneous js output accoding to console(?)
plot1 = jQuery.jqplot ('chart1', [s1]); //copied from example at
}); //$(document).ready
</script>
</head>
You forgot the $ to referrence the chartvals var at the json_encode() function call:
var s1 = <?php echo json_encode(chartvals); ?>;
Should be
var s1 = <?php echo json_encode($chartvals); ?>;
To not trap into this sort of mistakes again you can add error_reporting(E_ALL); to the beginning of your script and set display_errors to on in your PHP config during development.
var s1 = <?php echo json_encode($chartvals); ?>; //!the echo seems to create
I have a form with potential errors in the form defined in php. I'm used javascript to change the form action depending on whether errors are present or not. I've converted the php error variable, $errors using json_encode so I can use it in javascript. Running the file in Firefox I get the following error in Firebug:
Syntax error: missing ;
before statement var errors = "{"firstnameErr:......etc}, with the pointer at the letter f in firstnameErr. It looks like I have the errors in the json_encode object.
Here is the javascript:
<script type = "text/javascript">
function switchFormAction() {
var errors = [];
var errors = "<?php echo json_encode($errors); ?>";
if(!empty(errors)) {
alert("Please correct these errors");
}
else {
var element = document.getElementById("regForm");
element.setAttribute("action", "serraInsertForm.php");
return true;
}
}
window.onload = function() {
document.getElementById("regForm").onsubmit = function()
switchFormAction();
}
</script>
Probably something simple but I can't work it out. Javascript and json are new to me.
Appreciate any help stackoverflow can offer.
var errors = "<?php echo json_encode($errors); ?>";
^--- ^--
The indicated quotes are not necessary and are in fact causing the problem. json_encode() will produce whatever quotes/brackets are necessary to turn the data in $errors into syntactically valid Javascript. You're producing:
var errors = "{"somekey":"somevalue"}";
^--start string
^--end string
^^^^^^^ undefined variable
All you need is
var errors = <?php echo json_encode($errors); ?>;
Losing the quotes around here ought to do it.
var errors = "<?php echo json_encode($errors); ?>";
Should probably be:
var errors = <?php echo json_encode($errors); ?>;