1

Hi everyone I have a PHP file and this code:

<?php echo "Hello World"; ?>
<script type="text/javascript">
    $(document).on('click', '.order-submit', function() {
        dataName = $(this).data('name');
        var company = <?php echo json_encode(get_Comp( /* dataName here */)); ?>;
    });
</script>

How I can pass javascript variable "dataName" to my php function "get_Comp"? I will be very glad if someone help. Thanks!

3

3 Answers 3

3

This is not possible, you will need to use ajax to achieve this :

PHP getcomp.php

<?php
   //put here your get_Comp() function

   $dataName = $_POST['dataName'];
   echo json_encode(get_Comp($dataName));
?>

JAVASCRIPT

<?php echo "Hello World"; ?>
<script type="text/javascript">
    $(document).on('click', '.order-submit', function() {
        dataName = $(this).data('name');
        var company;
        $.post('getcomp.php', {dataName: dataName}, function(data) {
            company = data; //company should be equal to json_encode(get_Comp($dataName));
        });
    });
</script>
Sign up to request clarification or add additional context in comments.

Comments

0

PHP code is rendered server side whereas JavaScript is rendered client side. So, there is no way that you can pass a JS variable to a PHP function.

What you can do is, you can make an AJAX request to your PHP server with the dataName to fetch the information.

Comments

0
This is not possible for render javascript client side script in the php server side script

you will need to use ajax call

or 
you can use javascript cookie for render javascript variable access in the php

set javascript cookie & get cookie value in the php code using $_COOKIE

javascript cookie value set like :

http://www.w3schools.com/js/js_cookies.asp

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.