How to get JavaScript function data into a PHP variable

I am using PHP and JavaScript. My JavaScript code contains a function, get_data():

function get_Data(){
    var name;
    var job;
    .....

    return buffer;
}

Now I have PHP code with the following.

<?php
    $i=0;
    $buffer_data;

    /* Here I need to get the value from JavaScript get_data() of buffer;
       and assign to variable $buffer_data. */
?>

How do I assign the JavaScript function data into the PHP variable?

Answers:

Answer

Use jQuery to send a JavaScript variable to your PHP file:

$url = 'path/to/phpFile.php';

$.get($url, {name: get_name(), job: get_job()});

In your PHP code, get your variables from $_GET['name'] and $_GET['job'] like this:

<?php
    $buffer_data['name'] = $_GET['name'];
    $buffer_data['job']  = $_GET['job'];
?>
Answer

JavaScript code is executed clientside while PHP is executed serverside, so you'll have to send the JavaScript values to the server. This could possibly be tucked in $_POST or through Ajax.

Answer

If you don't have experience with or need Ajax, then just stuff your data into a post/get, and send the data back to your page.

Answer

You would have to use Ajax as a client-side script cannot be invoked by server-side code with the results available on server side scope. You could have to make an Ajax call on the client side which will set the PHP variable.

Answer
    <script>
        function get_Data(){
            var name;
            var job;
            .....
            return buffer;
        }

        function getData()
        {
            var agree=confirm("get data?");
            if (agree)
            {
                document.getElementById('javascriptOutPut').value = get_Data();
                return true;
            }
            else
            {
                return false;
            }
        }
    </script>

    <form method="post" action="" onsubmit="return getData()"/>
        <input type="submit" name="save" />
        <input type="hidden" name="javascriptOutPut" id="javascriptOutPut"/>
    </form>

    <?php
        if(isset($_POST['save']))
        {
            var_dump($_POST['javascriptOutPut']);
        }
    ?>

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.