Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to Use Json_encode() Function to Pass PHP Array to JavaScript?

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 2
    • 0
    • 40
    Comment on it

    json_encode() is corePHP function which is used to generate JSON which will be a simple value (i.e nethier an object nor an array). So, in this tutorial, we will see how to use json_encode() function to pass PHP array to Javascript.

     

     

    PHP code:

    <?php
    $data = array(
        array('name'=>'pankaj', 'email'=>'Pankaj@gmail.com'),
        array('name'=>'Ayush', 'email'=>'Ayush@gmail.com')
    );
    
    ?>

     

    JavaScript Code:

    <script>
    getUserInfo(<?php echo json_encode($data); ?>)
    function getUserInfo(userObj){
        alert(JSON.stringify(userObj)); //convert object into string.
    }
    
    </script>

    Code Explanation :-

    In the above code, $data variable holds a multidimensional array which will pass to JavaScript with the help of json_decode().

    <?php echo json_encode($data); ?>

    Above line will convert $data array into simple values. 

    you can see the Javascript comment line, I have used one more function i.e JSON.stringify. JSON.stringify is Javascript function which is used to Convert JavaScript object into a string.

     

    Output:

    How to Use Json_encode() Function to Pass PHP Array to JavaScript?

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: