1

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">
$(document).ready(function(){

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

</script>

External JS

 $(document).ready(function(){
    alert(add_project_link);
    alert(add_agent_link);
  });

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!

1
  • Don't define your JavaScript variables inside jQuery's $(document).ready(function(){ }); on the main page. The entire point is to define them BEFORE you call jQuery's external file. Look at my answer. Commented Mar 7, 2012 at 10:43

6 Answers 6

13

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>
<script type="text/javascript" src="file.js"></script>

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

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

1 Comment

I think it echo and not return you should use to make this code works
5

Take your php generated variables out of document ready. They are not accessible anyhwere else in your code due to closure of the ready event function they are in

Comments

3

What I would do is to store those variables to something easily called by JS later.

<input type="hidden" id="hidden_var" value="<?= base_url().'add_project/show_form'; ?>" />

var add_project_link = $('#hidden_var').val();

Comments

2

You just write in the head tag

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

Then load your External JS after the script above

1 Comment

this is what I have. no luck though. +1
2

best way is to to store those path in some tags like

<span id="site_url" style="display:none;"><?php echo site_url(); ?></span>
<span id="current_url" style="display:none;"><?php echo current_url(); ?></span>

then you can access this this using jquery like

$('#site_url').html();
$('#current_url').html()

1 Comment

While this technique can work as desired, this advice may be needlessly bloating the DOM with otherwise unnecessary elements/nodes.
1

the simplest thing to do is to bring the script into a script tag on the php page

you can go down the URL string variable route, but it's unnecessary I think

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.