Reputation: 87
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.
Upvotes: 1
Views: 6470
Reputation: 11
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.
Upvotes: 1
Reputation:
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!
Upvotes: 1