OM The Eternity
OM The Eternity

Reputation: 16214

Using PHP's json_encode() function in .js file

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

Answers (4)

xdazz
xdazz

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

Boris Gu&#233;ry
Boris Gu&#233;ry

Reputation: 47585

You have several possibilities depending on your use case.

  1. You may wan't generate the .js file from PHP

    file_put_contents('somefile.js', $content);

  2. Allow PHP in .js file

    AddHandler application/x-httpd-php5 .js

  3. 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

Carlos Campderr&#243;s
Carlos Campderr&#243;s

Reputation: 22972

You'll need to tell php that it should process also the .js file. There are two ways for doing this:

  1. rename from file.js to file.php
  2. mess with the apache configuration to make it treat .js files as php

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

Peter Olson
Peter Olson

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

Related Questions