The approach used in this question is WRONG. As mentioned in comments, PHP is server side processing and JS is client side processing (browser). The 2 should not be mixed.
Seems like a trivial problem with an apparently easy solution. I have a PHP file which is loaded via a post. In this document I can retrieve the posted value as such:
$userid = $_POST["userid"];
Then in my Javascript in $(document).ready(function() I am trying to assign the post value to Javascript variable as such :
var jsvariable = <?php echo($_POST["userid"])?>;
Keep geeting either variable undefined in js error or syntax error, unexpected T_VARIABLE error inPHP.
Please advise how I can successful retrieve this value.
There are two approaches for this:
First if your js is present inside a php file then in that case.
var jsvariable = "<?php echo $_POST["userid"]; ?>";
And if your js is present in a .js file then in that case.
var jsvariable2 = "<?php echo $_POST["userid"]; ?>";
and below this line. Call the js file.
<script src="whatever.js" type="text/javascript">
And inside the js assign the above created variable to it:
var jsvariable = jsvariable2;
Hope it helps.
try
var jsvariable = <?php echo('\"'.$_POST["userid"].'\"')?>;
instead
var jsvariable = <?php echo($_POST["userid"])?>;
if userid="ehdrbs0318" in php,
in javascript
var jsvariable = ehdrbs0318;
you have to assign string like
var jsvariable = "ehdrbs0318";
You could use json_encode:
var jsvariable = <?php echo json_encode($_POST["userid"]) ?>;
This will add the necessary quotes if the PHP variable is a string, but will also respond well to non-string values.
As a side note: you can use the PHP short-cut notation to output values:
var jsvariable = <?= json_encode($_POST["userid"]) ?>;
PHP error
The error unexpected T_VARIABLE in PHP you (sometimes) get, is unrelated to the code you have provided: it is a simple syntax error, and it means the parser found a variable name at an unexpected place. Maybe you forgot to end the previous statement with a semicolon, or maybe you forgot a closing parenthesis or bracket....
Related
I'm trying to create a button which dynamically add input and since I'm using Zend framework I use this method to get the input from the Form file : <?php echo $this->formm->getElement('refA'); ?>
but I get this error : Uncaught SyntaxError: Unexpected identifier
and the jquery function for that add button is :
$(document).ready(function (){
var j = "<?php echo $this->formm->getElement('refA'); ?>";
$("#add-more").click(function(){
$(".row").append(j);
});
});
and when I click on that error it shows me where I have the error it seems like that it uses:
$(document).ready(function (){
var j = "<label for="refA" class="optional">Article:</label>
<select name="refA" id="refA" class="form-control">
<option value="test1" label="test1">test1</option>
</select>";
$("#add-more").click(function(){
$(".row").append(j);
});
});
is it possible to get the code generated in single line so I can make the button to work ?
Looks like it's a quoting issue - the data that PHP is chucking in there has double quotes which keep terminating your string. Try wrapping it in single quotes - with escapes for refA:
$(document).ready(function (){
var j = '<?php echo $this->formm->getElement(\'refA\'); ?>';
$("#add-more").click(function(){
$(".row").append(j);
});
});
Ok, after doing some more digging, you need to get those quotes and spaces out before it. Unfortunately, I'm not a PHP guy - so I'm hoping that the syntax is right - the idea, is to get the data from refA and store it in $message - then get rid of any spaces and escape any quotes, then echo the value out to be set as 'j':
$(document).ready(function (){
var j = '<?php $message = $this->formm->getElement("refA"); $message = preg_replace("/\r?\n/", "\\n", addslashes($message));echo $message?>'
$("#add-more").click(function(){
$(".row").append(j);
});
});
PHP methods found here:
https://www.the-art-of-web.com/php/javascript-escape/
Another option that would completely take care of the issue would be to use es6 - template-strings (back-ticks)
$(document).ready(function (){
var j = `<?php echo $this->formm->getElement("refA"); ?>`;
$("#add-more").click(function(){
$(".row").append(j);
});
});
most modern browsers will nativity handle es6
Template Strings
As said by Kyle, you're facing a quoting issue. But, unlike what he said, quotes inside PHP tag must not be escaped, since they are rendered server side.
This should do the trick:
window.onload = function() {
$(document).ready(function (){
var j = '<?php echo preg_replace("/\r|\n/", "", $this->formm->getElement('refA')); ?>';
$("#add-more").click(function(){
$(".row").append(j);
});
});
}
Edit: looking at your screenshots and other comments, it seems that you are trying to access jQuery ($) before loading (I suppose you are loading all the JS dependencies at the end of the layout).
Since you can't use PHP code in JS files, you have two options:
You create a JS variable inside your template (ajouter.phtml), like var inputTemplate = <?php echo preg_replace(....);?>;, and use that variable in your JS file
You make sure that that JS snippet is executed only when the page has been fully loaded (hence the use of window.onload = function(){}
Personally, I'd suggest you the first option. Inserting JS code inside the phtml is conceptually wrong, because if you somehow you decide to not use jQuery anymore, you won't have to go inside all templates to find those snippets.
I want to pass the php variable inside the window.location javascript this is my php code and i am unable to do that.
echo '<script>location.href = "reportConsumption.php?creategenReport="'.$genid.'"&sDate="'.$startdate.'"&eDate="'.$enddate;</script>';
try to set quotation marks
echo '<script>location.href = "reportConsumption.php?creategenReport='.$genid.'&sDate='.$startdate.'&eDate='.$enddate.'"</script>';
You are closing your quote in JS
echo '<script>location.href = "reportConsumption.php?creategenReport="'.$genid.'"&sDate="'.$startdate.'"&eDate="'.$enddate;</script>';
Should be
echo '<script>location.href = "reportConsumption.php?creategenReport='.$genid.'&sDate='.$startdate.'&eDate='.$enddate.'</script>';
This will cause an error in JS on the client side, you could see this by pressing f12 and looking in the console log in the browser debugger. Your source code will look like this
<script>location.href = "reportConsumption.php?creategenReport="35"&sDate="...
//where this is a quoted block
"reportConsumption.php?creategenReport="
//and this is just chilling in space
35
//and then a new quoted block, etc.
"&sDate="
And you had this other (php syntax error) issue I took the liberty of fixing.
.$enddate;</script>';
Just in PHP you can redirect with
header("Location: $url");
But you have to be sure of 2 things:
You do not output "Anything" not even a line return before calling header
You call exit(); immediately after it. If you don't PHP will continue to execute the current script after it executes the redirect. Which is probably not desirable.
You are closing the double quotes too early. It should be close at the end of the URL. So you have a syntax error in your JavaScript:
echo '<script>location.href = "reportConsumption.php?creategenReport='.$genid.'&sDate='.$startdate.'&eDate='.$enddate.'";</script>';
Or separate using a variable to be more clear:
$url = 'reportConsumption.php?creategenReport='.$genid.'&sDate='.$startdate.'&eDate='.$enddate;
echo '<script>location.href = "'.$url.'";</script>';
You should not use double quote around the values for GET param
echo '<script>location.href = "reportConsumption.php?creategenReport='.$genid.
'&sDate='.$startdate.'&eDate='. $enddate .'"';</script>';
I am using the following code in a seperate js file to use a php $_SESSION variable. However, I am getting a syntax error of SyntaxError: missing ; before statement. I have tried putting the ; in the usual place, but still the same.
What is the correct way to use a php session in js file. Thanks
var companycode = '<?php echo $_SESSION['ls_idcode_usr']?>';
There may be special characters in the value of the session variable. Use json_encode() to output a valid Javascript literal:
var companycode = <?php echo json_encode($_SESSION['ls_idcode_usr']);?>;
You can only use PHP in files ending in .php, otherwise the web server won't parse them looking for code to execute, and it'll just get passed down to the client.
You can certainly make a whatever.js.php file, where PHP will be involved in the production of the Javascript file that is passed down to the browser.
I am using laravel 5.2 , I am using like below
var data = <?php json_encode($data['value']); ?>
when I am using JavaScript code below in the blade file, then its working fine, but when I am using the code as a separate file and trying to gulp that , then it is not working , my data is not loading
var data = "<?=json_encode($data['value']);?>"
or
var data = "<?php echo json_encode($data['value']);?>"
You are not echoing out the value, your var is null
Other mate already provided the correct solution specially #user1779617, now i am explaining with a basic example:
<?
// a simple array
$data['value'] = array(1=>'test');
$encodedData = json_encode($data['value']);
?>
<script type="text/javascript">
var data = <?=$encodedData?>;
console.log(data); // Object { 1="test"}
</script>
If you have posted original code than you have an error in your javascript, you miss the ending termination semicolon (;) plus you need to echo the result as other mentioned in answers.
UPDATE 1
if you are still facing the same issue than use JSON.parse in javascript
<script type="text/javascript">
var data = JSON.parse( ' <?=$encodedData?>');
console.log(data); // Object { 1="test"}
</script>
In my code, I need to get data from configuration file(.properties) .My configuration file looks something like this(.properties):
maxTime = 60
upVotePostMaxTime=60
but I don't know how to read the configuration file in JavaScript. Is there a better way of doing this?
It is not advisable to read configuration files from JavaScript. Instead you could do this:
Read the file on server-side (using PHP, .Net or Python or any other language that you prefer)
Render the valid values to JavaScript. Something like:
var maxTime = "<?php echo maxTime; ?>";
var upVotePostMaxTime = "<?php echo upVotePostMaxTime; ?>";
where <?php echo maxTime; ?> and <?php echo upVotePostMaxTime; ?> will have values 60 each.
This would show on the client-side as:
var maxTime = "60";
var upVotePostMaxTime = "60";
and then you may use it in JavaScript.
Values are assigned in double quotes to prevent breaking of JavaScript code in case null values are sent from the server.
Please ensure that proper values are assigned to JavaScript variables.