php-to-javascript

Passing variables and data from PHP to Javascript

Share this post on:

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 load in the 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 in which you can accomplish this task.

 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, 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 it special attention as it is not suitable for such a job. The second point to keep in mind is that PHP does not have definite Javascript escape functions, so by using the method described above, your code may be open to a second-tier injection attack. You can JSON encode data, but as I said before, it may not work with complicated XML or HTML code, as making ajax calls with such a practise 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 seriously. You don’t have to mix PHP with Javascript, and the code will be neat, clean, and more readable. Debugging also becomes easier and less time-consuming. You don’t have to wait for a page to load to get the results of your request in Ajax. However, because there are so many http requests, too many ajax calls cause network latencies.Ajax is, in my opinion, a better way to access PHP values in javascript.

ajax process flow
   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 as good as Ajax, but it is still usable.Its good point is that it still separates PHP and Javascript and works faster than AJAX. The method for implementing this concept is to create a hidden field with a unique 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 and 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.

Share this post on:

Author: Nohman Habib

I basically work in the CMS, like Joomla and WordPress and in framework like Laravel and have keen interest in developing mobile apps by utilizing hybrid technology. I also have experience working in AWS technology. In terms of CMS, I give Joomla the most value because I found it so much user freindly and my clients feel so much easy to manage their project in it.

View all posts by Nohman Habib >

Leave a Reply

Your email address will not be published. Required fields are marked *

PHP Code Snippets Powered By : XYZScripts.com