I feel like i’m going round in circles here and missing something really daft…
My setup is essentially using CodeIgniter on the server-side, and Bootstrap on the client, but that’s a little beside the point…
I’m trying to call a php value within a javascript function. The value is being stored in a protected variable within one of the php controllers, which is accessible by the views being loaded in that controller, as i’m accessing the variable directly in the html (and therefore I assumed i could access it in the javascript as well).
The code is here, it’s really straight forward:
$(document).ready(function() {
var UID = "<?php echo $the_user->id; ?>";
console.log(UID);
});
I’m expecting this do do a console output of, say, “1”, but it’s actually outputting the actual string of "<?php echo $the_user->id; ?>". This will also happen if i’m just echoing a simple string, rather than a php variable.
I feel like this might be a config issue, but I really have no idea. If I remove the quotes from the php call, I get a
TypeError: can't wrap XML objects
console.log(<?php echo $the_user->id ?>);
Any ideas? I feel really dumb at this point 🙁
If you see
<?php echo $the_user->id; ?>in the output, it means that your document is not parsed by PHP.Check the file extension, check that it is indeed send to PHP in your webserver configuration.
For example if you add PHP tags in a .js file, it won’t be passed to PHP, if you are using Apache, you would have to add:
or set your variables in the HTML and send it as a parameter to the external Javascript.