1

I am trying to print out a variable from a default.js file. That variable counts up to a number, which I want to print on the html page.

So as it is now, I have:

We found <script type="text/javascript"> 
    var $tempCountPlaces;
    document.write($tempCountPlaces); </script> places for you!

    <div id="places_list">
    <script type="text/javascript">

      var places_file = '<?php echo site_url().'/places.html'; ?>';
      var region_id = <?php echo $region; ?>;
      var event_type_id = <?php echo $eventtype; ?>;
      var seats = '<?php echo $seats; ?>';      

    </script>

As you can see, I can send files from PHP to Javascript, and then use these variables in the default.js file. But how do I import a variable from default.js to the html page, and then print the variable, as shown above?

The var $tempCountPlaces; IS defined in the default.js file, and it is not a local variable within a function.

So basicly i want to pass the variable from default.js $tempCountPlaces into my HTML file using the script tag.

2
  • There are no Java variables in javascript Commented May 12, 2014 at 17:02
  • Yeah, ofcourse you are right. It is now changed Commented May 12, 2014 at 17:25

2 Answers 2

1

You might want to consider approaching the problem like this:

HTML file contains:

We found <span id="numOfPlaces"></span> places for you!

JavaScript file contains:

var tempCountPlaces = 10;//example value fetched from your PHP service

document.getElementById("numOfPlaces").innerText = tempCountPlaces;
//of if you choose to use jQuery: $("#numOfPlaces").text(tempCountPlaces);

Your resulting interface would end up looking like this:

We found 10 places for you!
Sign up to request clarification or add additional context in comments.

Comments

1

I use to ask the same question, and yes ajax and axios can help, but if you really need to pass any var from directly php to javascript, or from the script in your html yo you doc.js you have to do this:

<head> 
 <script type="text/javascript">
       var places_file = '<?php echo site_url().'/places.html'; ?>';
 </script>
 <script src="js/youDoc.js" type="text/javascript"></script>
</head> 

As you can see, you have only to declare your vars first and then add your js doc.

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.