Jump to content

Dynamically edit js function with aid php


cs.punk

Recommended Posts

Hi there. I'm trying to figure out a way to 'add' to a javascript function dynamically.

 

Basically I'm using the JQuery library and within the $(document).ready() function I would like to add some 'code' that would change on each page generated via PHP. Basically it is just gonna be some variables that hold the 'original' values of some data. So because they can't be hard-coded, how could I 'add' them to the $(document).ready()? I could just run them as a normal script but I just thought I'd ask.

 

Any ideas how I could go about this? Thank you!

Link to comment
Share on other sites

You can just echo the PHP variable into a JS variable declaration:

 

var someVar = '<?php echo htmlspecialchars($someVar) ?>';

 

Added the escaping to ensure no characters within the string would break the JS syntax.

Link to comment
Share on other sites

You can just echo the PHP variable into a JS variable declaration:

 

var someVar = '<?php echo htmlspecialchars($someVar) ?>';

 

Added the escaping to ensure no characters within the string would break the JS syntax.

 

How would I insert this into $(document).ready() function which is loaded via <script type="text/javascript" src="js.js"></script>?

 

I'm guessing I'm just gonna have to rewrite my system to have the $(document).ready() dynamically in each page and just echo the 'javascript code' in there.

 

If anyone has any other ideas please let me know ;D

Link to comment
Share on other sites

You could just define it before the script is included?

 

<script type="text/javascript">
    var someVar = '<?php echo htmlspecialchars($someVar) ?>';
</script>
<script type="text/javascript" src="js.js"></script>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.