Access PHP Var from External JavaScript File

Access PHP var from external javascript file

You don't really access it, you insert it into the javascript code when you serve the page.

However if your other javascript isn't from an external source you can do something like:

<?php
$color = "Red";
?>
<script type="text/javascript">var color = "<?= $color ?>";</script>
<script type="text/javascript" src="file.js"></script>

and then in the file.js use color like so:

alert("color: " + color);

access php variable into external javascript file

Pass it as a parameter:

<input type="submit" onclick="func('<?php echo $var; ?>');">

in test.js:

function func(param){
console.log(param); // contents of $var
}

Or set it globally:

<script>
var param = "<?php echo $var; ?>";
</script>

How to access the php variable from my external javascript file

I love php, which does not knew about html at all.

Try to change your search.php to return json instead of html:

...
$result = array('users' => array(), 'method'=>'search');
while($row=mysql_fetch_array($sql_res))
{
$result['users'][] = $row;
}
header('Content-type: application/json; charset=UTF-8');
echo json_encode($result);

and handle all received data in javascript:

success: function(json) {
var data = JSON.parse(json);
console.log(data);
// change DOM with new data etc.
}

calling php variable in external.js file

The possible reason that your code isn't working are:

  1. You haven't embedded jQuery library and been using $() identifier
  2. Your PHP variable $phpValue is empty

The following code works:

var user = $("#myPhpValue").val();alert ("the user is "+user);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<input type="hidden" id="myPhpValue" value="mike">

Get PHP variable in Javascript file

You may adopt one of 2 Possibilities... Option Nr. 1: You can expose the Number of Images as a Global Variable & Use it in your main.js (that is Assuming that main.js was included in the numberOfImages.php Script. Option Nr. 2 You can use Ajax to do that too:

OPTION NR. 1

    <?php 
//FILE =>numberOfImages.php:

$dir = "/my/directory/";
$fi = new FilesystemIterator($dir, FilesystemIterator::SKIP_DOTS);
$fileCount = iterator_count($fi);

// EXPOSE THIS VARIABLE TO JAVASCRIPT AS A GLOBAL VARIABLE..
//echo $fileCount;

?>
// SOMEWHERE IN THE SAME FILE: numberOfImages.php:
<script type="text/javascript">
var _NUM_IMAGES = "<?php echo $fileCount; ?>";
</script>

Now, you can access the Number of Images in the main.js by simply referencing the variable _NUM_IMAGES. So doing alert(__NUM_IMAGES) would work. However, be Sure that the main.js is included in the numberOfImages.php File

OPTION NR 2

    // INSIDE YOUR HTML/PHP FILE THAT RUNS THE SHOW; IMPORT BOTH JQUERY & YOUR main.js BELOW. 
// INCLUDE JQUERY LIBRARY: OTHERWISE THIS WON'T WORK...
// SURE YOU CAN ALSO DO ALL THESE IN PURE JAVASCRIPT, BUT WHY RE-INVENT THE WHEEL???
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.3/jquery.min.js"></script>
<script type="text/javascript" src="main.js"></script>

//YOUR main.js COULD LOOK SOMETHING LIKE THIS:::
jQuery.noConflict();
(function ($) {
$(document).ready(function(e) {
$.ajax({
url: 'numberOfImages.php', // <== POINTS TO THE VALID URL OF THE PHP FILE THAT OUTPUTS THE NUMBER OF IMAGES...
dataType: "HTML",
cache: false,
type: "POST",

//HANDLE THE SUCCESS CASE FOR THE AJAX CALL
success: function (data, textStatus, jqXHR) {
if(data){
alert(data);
}
},

//HANDLE THE FAILURE CASE FOR THE AJAX CALL
error: function (jqXHR, textStatus, errorThrown) {
console.log('The following error occured: ' + textStatus, errorThrown);
},

//HANDLE THE EVENT-COMPLETE CASE FOR THE AJAX CALL
complete: function (jqXHR, textStatus) {
}
});
});
})(jQuery);

And the numberOfImages.php could look something like this. Exactly the same way you did it:

        <?php

/**
* filename: numberOfImages.php
*/

$dir = "/my/directory/";
$fi = new FilesystemIterator($dir, FilesystemIterator::SKIP_DOTS);
$fileCount = iterator_count($fi);

die($fileCount);

However, be informed that You need JQuery for this to work. You can add this to the File in which you are importing the main.js but before you import the main.js.

Passing php variable to external javascript file

Try to remove quotes.

var test = <?php echo $monthlycalories; ?>; 

PHP variable inside a js file

Don't forget to properly escape your variables before passing them to JavaScript. Use json_encode() for this, as it escapes and encodes your values in a way suitable for using with JavaScript:

test=<?php echo json_encode($country) ?>;

Never simply send the variable un-encoded, as it might break things, or, worse, if the value comes from untrusted sources, compromise your security.

Also, rename your file to .php instead of .js if you want to be able to insert dynamic PHP code inside it.

Including PHP variables in an external JS file?

My solution combines several techniques, some of which are already mentioned within the answers to this question.

Yes, separate PHP from JS

First of all: yes, you should separate your JS from PHP. You can put it in a separate file, but you will need to make some changes into your current code. Do not make JS file dynamically generated - it actually kills the advantages of separating JS code into separate file (you cannot cache it etc.).

Common variables as global variables / function arguments

Next, store your common variables as global variables in the header of HTML file (you do not really have much choice, although there are other alternatives), preferably grouped in one object:

var Globals = <?php echo json_encode(array(
'active_user_id' => $active_user->id,
'token' => $token,
'hash' => $hash,
)); ?>;

Alternatively you can pass all of them as argument(s) to the function you will call, but I assumed you are using them also in other places in your script.

Container-dependent data stored in data- attributes

Then use data- attributes for storing real data associated with containers. You won't need post1/post2/post3-like classes and separate event handlers for them:

<div data-post-id="10">here is something</div>

instead of eg.:

<div class="post10">here is something</div>

How to read globals and data- attributes from external JS file

And then your JavaScript may look like:

$(document).ready(function(){
$('[data-post-id]').click(function() {
var el = $(this);
var data = {
'post_id': el.data('post-id'),
'user_id': Globals.active_user_id
};
data[Globals.token] = Globals.hash;
$.ajax({
'type': 'POST',
'url': 'http://domain.com/ajax/add_love',
'data': data,
'dataType': 'json',
'success': function(response) {
el.html(response.total_loves).toggleClass('loved');
}
});
return false;
});
});

And this should be sufficient (although I did not test it).



Related Topics



Leave a reply



Submit