diank
diank

Reputation: 638

jQuery variable in PHP file inside jQuery code

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!

Upvotes: 1

Views: 55

Answers (3)

Pratik
Pratik

Reputation: 139

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

Upvotes: 0

Sofiene Djebali
Sofiene Djebali

Reputation: 4508

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>

Upvotes: 3

kvn
kvn

Reputation: 2300

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.

Upvotes: 0

Related Questions