1

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 :(

2
  • What extension does that file have on the server? .js or .php? Commented Oct 2, 2012 at 21:43
  • Your PHP is never being executed. Check your serverside setup to ensure that all PHP is being executed, not treated as raw strings. Commented Oct 2, 2012 at 21:43

2 Answers 2

4

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:

AddType application/x-httpd-php .js

or set your variables in the HTML and send it as a parameter to the external Javascript.

Sign up to request clarification or add additional context in comments.

1 Comment

This is what I was missing, thankyou :) I naively assumed that external js files were processed the same way as js inline with the html.
0

mathieu-imbert is right about your file not being processed as a view. That's your first hurdle: make sure the page is being parsed.

Also, when trying to stick PHP variables into javascript, you have to think about escaping variables, dealing with unexpected values, etc.. Fortunately, there is an easy answer:

$(document).ready(function() {
    var UID = <?php echo json_encode($the_user->id); ?>;
    console.log(UID);
});

You can insert arbitrarily complex data into Javascript this way, provided you mind the usual restrictions with serializing PHP data.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.