Reputation: 53
I am not great at Jquery and PHP I was coding in a way that sometimes I needed my javascript variables to get php post values something like that.
var articleCategoryA2 = '<?php if(isset($_POST['A2']))echo $_POST['A2'];?>';
When I was done with the coding I wanted to get everything organized I decided to have a javascript code in one single file, but it won't interact with the embeded php code in it after I include the javascript code in the php file that gets the post values
What should I do? For being noob I haven't got a clue.
Upvotes: 0
Views: 73
Reputation: 12121
One approach is to initialize the variable in JavaScript, then conditionally assign the value of that variable.
So in your JavaScript file:
var articleCategoryA2; //defined, but null
...then inline within your PHP file:
<?php
if(isset($_POST['A2'])){
/* if $_POST['A2'] is set, put its value into the JavaScript variable articleCategoryA2 */
echo('
<script>
articleCategoryA2='.$_POST['A2'].';
</script>
');
};
?>
If $_POST['A2']
exists, JavaScript will set its value into articleCategoryA2
.
Upvotes: 0
Reputation: 171690
Javascript files won't be compiled by php so if you need a php variable passed in you need to put it in a separate script tag
<script>
var articleCategoryA2 = '<?php if(isset($_POST['A2']))echo $_POST['A2'];?>';
</script>
<script src="app.js"></script>
Now the variable is available in app.js
.
Upvotes: 3