nielsv
nielsv

Reputation: 6820

Use a PHP variable in Javascript in same document

I have a question about using data (obtained in PHP) in Javascript. This is what I do for now:

file index2.html

<div class="container">
   <form class="well">  
       <label>Your appid</label>  
       <input type="text" class="span3" id="appid" placeholder="Type your appid here...">  <br>
       <button type="submit" id="submit" class="btn btn-primary" data-loading-text="Loading..." >Submit</button>  
   </form>
   <p id="errors" class="text-error"></p>

</div> <!-- /container -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/vendor/jquery-1.9.1.min.js"><\/script>')</script>
<script src="js/main.js"></script>

file main.js

$(document).ready(function() {
// CLICK ON SUBMIT BUTTON
  $("#submit").click(function(e) {
    // stop form submission first
    e.preventDefault();

    var btn = $(this);
    btn.button('loading');

    // GET VALUE OF APPID
    var appid = $("#appid").val();

    if (isNaN(appid))
    {
        alert("Only numbers allowed!");
    }

    else
    {
        // GET JSON FROM PHP SCRIPT
        $.ajax({
            type: 'GET',
            url: 'loadjson.php',
            data: {
                'appid': appid
            },
            success: function (data) {
                var object = JSON.parse(data);
                checkCompletion(object);
            },
            error: errorHandler
        });
    }

    }); // END OF CLICK FUNCTION
}); // END OF DOCUMENT READY

As you can see I make an AJAX call to loadjson.php!

file loadjson.php

<?php
  if(isset($_GET['appid']) && !empty($_GET['appid'])) {
      $appid = $_GET['appid'];
  }
  $json_url  ='http://api.tapcrowd.com/api/gateway/call/1.4/getApp?appid=' . $appid;

  $ch = curl_init($json_url);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

  $str = curl_exec($ch);
  curl_close($ch);

  $data = json_decode($str);
  $array = json_encode($data);

  echo $array;
?>

Now I have the question if there is a possibility that I don't need to make an AJAX call but maybe I can have PHP in my HTML file and use it in my Javascript?

Does anyone know if this is possible and so yes, how?

Upvotes: 0

Views: 342

Answers (1)

GGio
GGio

Reputation: 7653

If your html document extension is .php then yes you can simply use

var phpValue = "<?=$yourVariable?>";

Assuming that all json_encode and other functionalities are done on $yourVariable before its being used.

Upvotes: 1

Related Questions