-1

Hi again are there a way that i can get the variable "log" in a jquery code like the example bellow with out using alert, a field id, class and etc.

    <script>
    var log='1';
    </script>

   <?php 
    $run = log
    ?>

I want to get the data of a certain variable in a javascript and use it as a value of a variable in my php code

Dit Nik
  • 21
  • 10

2 Answers2

1

You can't do it that way.

Because:

  1. javascript runs in browser.
  2. PHP runs at server.

There are two ways one is form submission and other one is ajax. You have to send the values to the server to get it to echo.


As per your updates, i would suggest you to use ajax/form submit:

Ajax:

var log = '1';

$.ajax({
   url: 'path/to/php/file.php',
   type:'get',
   data:{log:log},
   success:function(data){
      console.log(data); // logs: The posted value is 1
   }
});

here in the data object log before : is the key while log after : is the var which refers to value '1'. So, in php you can do this:

<?php 
    if(isset($_POST['log'])){
       $run = $_POST['log'];
       echo 'The posted value is '.$run;
    }
?>
Jai
  • 74,255
  • 12
  • 74
  • 103
1

You cannot get client side variable on server side without the use of AJAX or some sort of post back. In all calls to a server, the server side code is execute then returned to render client side in the browser. Therefor, the client side code is ALWAYS run after the server side. You can look at using client side code to make an AJAX request to the server and return a value or post to to a page which will load and render it server side. You are trying to echo a value here, this can be done client side but if there is complex server side logic to get the value then I would use an AJAX request to get it.

AJAX http://www.w3schools.com/jquery/jquery_ajax_intro.asp

POST a form http://php.net/manual/en/tutorial.forms.php

Dhunt
  • 1,584
  • 9
  • 22