FlyingCat FlyingCat - 1 year ago 57
Javascript Question

How to pass PHP value to external JavaScript file

I am trying to pass my variables from my main page to external JS file. Please see my code.

Main page:

<script type="text/javaScript">

var add_project_link="<?= base_url().'add_project/show_form'; ?>";
var add_agent_link="<?= base_url().'agent/add_agent';?>";


External JS


I got:

uncaught referenceError add_project_link is not defined.

I thought the external JS would catch the variable declared in main page. Any thoughts? Thanks a lot!

Answer Source

Before you call your external JavaScript file, define your variables using PHP:

<script type="text/javascript">
   var site_url = '<?php echo site_url(); ?>';
   var current_url = '<?php echo current_url(); ?>';
<script type="text/javascript" src="file.js"></script>

In your external file.js you can now use site_url as a variable.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download