Reputation: 16214
I have a array in php file say
<?php $authcode = array("auth"=>"jshkjashdkj");?>
Now I want to access this array in a JS file, then how can I do it?
As in .js file <?php echo json_encode($authcode); ?>
wont work.
UDPATED
My custom.js file contains below code,where I have to use authcode in url:
$('#removeimage').click(function(){
$.ajax({
url:'deletefile.php?filename='+$('#filename').val()+'&make='+$('#make').val()+'&model='+$('#model').val(),
cache: false,
async: false,
dataType: "json",
success: function(data) {
window.location="/upload/?authcode=97A434B1-E250-490D-8CF1-4B664AB42EED&make="+data.make+"&model="+data.model+"&imagename="+data.filename;
},
error: function(data) {
alert("Service is down");
}
});
});
Please notice the authcode usage, thats the place I need to use my authcode array
Please guide me.
Upvotes: 0
Views: 1548
Reputation: 160863
<?php $authcode = array("auth"=>"jshkjashdkj");?>
<script>
// declare a global var, then you could access it in file.js
var authcode = <?php echo json_encode($authcode); ?>;
</script>
<script src="file.js"></script>
Upvotes: 1
Reputation: 47585
You have several possibilities depending on your use case.
You may wan't generate the .js file from PHP
file_put_contents('somefile.js', $content);
Allow PHP in .js file
AddHandler application/x-httpd-php5 .js
Put it in your layout and store your data in a global variable to let it accessible from every other js scripts.
Which methods fits your need is really up to you. But I would generally avoid the second method.
Upvotes: 0
Reputation: 22972
You'll need to tell php that it should process also the .js file. There are two ways for doing this:
The first one is easier. The other change you must do is to substitute in your html the call to your js file:
<script type="text/javascript" src="somefolder/file.php"></script>
edit: Make the file.php
script output a header("Content-Type: text/javascript");
at the top of the file
Upvotes: 3
Reputation: 142939
You cannot access PHP variables in a JS file without using AJAX.
That said, you can make your script a PHP file that returns an application/javascript
response.
Upvotes: 0