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?

2
  • I have the same problem as you. Have you solved it ? Commented Dec 21, 2009 at 14:37
  • Such a GREAT question ,seriously! Thanks for posting Commented Nov 12, 2016 at 23:52

5 Answers 5

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'];
?>
Sign up to request clarification or add additional context in comments.

2 Comments

@garcon1986, Yes, $.get() is using ajax!
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.
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.

Comments

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.

Comments

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.

Comments

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']);
        }
    ?>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.