Passing variables and data from PHP to Javascript

In this post I am showing you how to pass data or variables from PHP to Javascript. When we open a web page, HTML and Javascript loads in background, which can execute JS on that html.  It commonly occurs in your programming experience that you need to pass a variable from php to javascript. Here I am discussing some ways, through which you can accomplish this motive.

 1- Passing data directly to javascript:

    This first method is very simple and easy to implement. Here is an example:  

  <script>
    var data = <?php echo json_encode("42"); ?>; //Don't forget the extra semicolon!
</script>

            As you can see from the above example that this method is very easy to implement as the php variables are printed out directly to javascript. Passing normal values would be easy but if you are passing data in the form of html or XML, you have to give special attention as it is not suitable for such a job.  The second point to keep in mind is, PHP does not have definite JS escape functions, so by using the method described above, your code may be open to second tier injections attack. You can JSON encode data, but as I said previously, it may not work with complicated xml or html code as by making ajax calls with such a practice asynchronously, can lead to major overhead.          

2- Using AJAX technique:

          Ajax is basically used to create interactive web applications. In the ajax method, your server side and client side scripts are completely separated, so you can take this process, somewhat secure. You dont have to mix PHP with Javascript and the code will be neat, clean and more readable. Debugging also becomes easy and less time consuming. You don't have to wait for a page load to get the results of your request in ajax. But be aware that too much ajax calls produce network latencies because of so much http requests. In my opinion ajax is a better way to access php value in javascript.

   Example with ajax using jQuery

  jQuery(document).ready(function(){

   jQuery("#savename").click(function(){

   var name = jQuery('#name').val();

 // you can apply validation here on the name field.

   jQuery.post("/ajax.php?name="+name , {

        }, function(response){

               jQuery('#results').html(jQuery(response).fadeIn('slow'));

   });

  });

});

 HTML Code:

 <div id="results"></div>

  <input type="text" name="name" id="name" value=""> 

  <input type="button" class="button" id="savename" value="Save Name">

3- Printing the data into an html element and using Javascript to retrieve information from it.

   I have used this method many times in my coding practice. It is not that much good as ajax, but still implementable. Its good point is, it still separates php and javascript and works faster than ajax. The procedure to utilize this concept is, you create a hidden field with a specific name and id. That hidden field is used to store the data or information and then this data is fetched out of the hidden field. So, you can say that this element is only visible to Javascript, not the user or visitor. This method is not good, when playing with structured data as you have to escape and convert the strings first.

   Implementation:

 <input type="hidden" id="data" name="data" value="<?php echo $val; ?>">

<!-- Or in Div based method  -->

<div id="data" style="display: none;">

    <?php    echo $val;       ?>

</div>

 

<script>

    var inner = document.getElementById("data");

    var val = div.innerContent;

</script>

      Plz keep in mind that if you want to render html code, you have to use  <?php echo htmlspecialchars($val); ?> otherwise result will not be a valid HTML.

   

Please share this on


Submit to DeliciousSubmit to DiggSubmit to FacebookSubmit to Google PlusSubmit to StumbleuponSubmit to TechnoratiSubmit to TwitterSubmit to LinkedIn

Related Articles

 

You have no rights to post comments

Enjoy best web development services at an affordable price. Looking forward to build a good relationship and serve you better...

Copyright © 2017. All rights reserved.