10

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?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
venkatachalam
  • 102,353
  • 31
  • 72
  • 77

5 Answers5

11

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'];
?>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Uzbekjon
  • 11,655
  • 3
  • 37
  • 54
  • 1
    @garcon1986, Yes, $.get() is using ajax! – Uzbekjon Jan 29 '10 at 11:49
  • 2
    I'm trying to do this to pass Javascript variables to a new window. Would the PHP code need to be in the new window or in the parent window? I can't get it to work either way. – Kenny Johnson Apr 22 '13 at 22:06
1

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Demur Rumed
  • 351
  • 3
  • 9
0
    <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']);
        }
    ?>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
h0mayun
  • 3,466
  • 31
  • 40
0

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Jobo
  • 940
  • 6
  • 11
0

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.

J.J.
  • 4,856
  • 1
  • 24
  • 29