14

I have the following code in JavaScript:

<script>
var a="Hello";
</script>

PHP Code:-

<?php 
$variable = // I want the above JavaScript variable 'a' value to be stored here
?>

Note : I don't want it in a form submission. I have some logic in JavaScript and I want to use it in the same PHP page... Please let me know how I can do this.

logan
  • 7,946
  • 36
  • 114
  • 185
  • 5
    You have to transmit the variable to the server. Have a look at AJAX for this purpose. – Sirko Feb 02 '13 at 14:34
  • @Sirko : I dont want to use AJAX as i want these Javascript & php in a backend scheduler page. It can not be accessed in front page – logan Feb 02 '13 at 14:42
  • @Sirko : Or is it possible store
    value in Php variable ?
    – logan Feb 02 '13 at 14:46
  • 1
    @logan Ajax is just a technique for asynchronous HTTP communication between client and server, it doesn't matter where you use it. JavaScript runs on the client side (e.g. in the browser) and PHP runs on the server side - if they want to talk to each other, they need a connection. You can achieve this by reloading the page with URL-parameter (synchronous) or by making a request in the background with JavaScript (asynchrounous) and injecting the results into the DOM, e.g. in a
    .
    – Quasdunk Feb 02 '13 at 14:46
  • 1
    @logan You can send any data over AJAX. In your case it seems you should serialize all necessary information of that div and then send it using AJAX. – Sirko Feb 02 '13 at 14:50

8 Answers8

24

You have to remember that if JS and PHP live in the same document, the PHP will be executed first (at the server) and the JS will be executed second (at the browser)--and the two will NEVER interact (excepting where you output JS with PHP, which is not really an interaction between the two engines).

With that in mind, the closest you could come is to use a PHP variable in your JS:

<?php
$a = 'foo'; // $a now holds PHP string foo
?>
<script>
    var a = '<?php echo $a; ?>'; //outputting string foo in context of JS
                                 //must wrap in quotes so that it is still string foo when JS does execute
                                 //when this DOES execute in the browser, PHP will have already completed all processing and exited
</script>
<?php
//do something else with $a
//JS still hasn't executed at this point
?>

As I stated, in this scenario the PHP (ALL of it) executes FIRST at the server, causing:

  1. a PHP variable $a to be created as string 'foo'
  2. the value of $a to be outputted in context of some JavaScript (which is not currently executing)
  3. more done with PHP's $a
  4. all output, including the JS with the var assignment, is sent to the browser.

As written, this results in the following being sent to the browser for execution (I removed the JS comments for clarity):

<script>
    var a = 'foo';
</script>

Then, and only then, will the JS start executing with its own variable a set to "foo" (at which point PHP is out of the picture).

In other words, if the two live in the same document and no extra interaction with the server is performed, JS can NOT cause any effect in PHP. Furthermore, PHP is limited in its effect on JS to the simple ability to output some JS or something in context of JS.

JAAulde
  • 19,250
  • 5
  • 52
  • 63
  • Everything @JAAulde said is exactly right. The only thing I wanted to add was that maybe the misconception is _where_ this code is running. PHP code is running on your webserver and is returning flat html/javascript to the browser. Then the browser is running your javascript. That's why JAAulde keeps saying the PHP is going to run first. You can't have a variable that both javascript and PHP both "know" about, they are running on completely separate machines. – xbakesx Nov 02 '17 at 17:51
  • You can pass information from PHP to javascript by having your PHP write out javascript, or pass data from javascript to PHP via network calls (AJAX / form submission, etc) – xbakesx Nov 02 '17 at 17:51
20
<html> 
<head>
    <script>
        var a="Hello";
    </script>

</head> 

<body> 
    <?php 
        echo $variable = "<script>document.write(a)</script>"; //I want above javascript variable 'a' value to be store here
    ?>
</body> 

Chetan Ghadiya
  • 366
  • 5
  • 16
4

The ideal method would be to pass it with an AJAX call, but for a quick and dirty method, all you'd have to do is reload the page with this variable in a $_GET parameter -

<script>
  var a="Hello";
  window.location.href = window.location.href+'?a='+a;
</script>

Your page will reload and now in your PHP, you'll have access to the $_GET['a'] variable.

<?php 
  $variable = $_GET['a'];
?>
Lix
  • 47,311
  • 12
  • 103
  • 131
1

If this is related to a form submission, use a hidden inputinside the form and change the hidden input value to this variable value. Then you can get that hidden input value in the php page and assign it to your php variable after form submission.

Update:

According to your edit, it seems you don't understand how javascript and php works. Javascript is a client side language, and php is a serverside language. Therefore you cannot execute javascript logic and use that variable value to a php variable when you execute relevant page in the server. You can run the relevant javascript logic after client browser process the web page returned from the web server (which has already executed the php code for the relevant page). After the execution of the javascript code and after assigning the relevant value to the relevant javascript variable, you can use form submission or ajax to send that javascript variable value to use by another php page (or a request to process and get the same php page).

Manjula
  • 4,961
  • 3
  • 28
  • 41
0

You really can't. PHP is generated at the server then sent to the browser, where JS starts to do it's stuff. So, whatever happens in JS on a page, PHP doesn't know because it's already done it's stuff. @manjula is correct, that if you want that to happen, you'd have to use a POST, or an ajax.

dmayo
  • 640
  • 6
  • 16
0

You can solve this problem by using AJAX. You don't need to load JQuery for AJAX but it has a better error and success handling than native JS.

I would do it like so:

1) add an click eventlistener to all my anchors on the page. 2) on click, you can setup an ajax-request to your php, in the POST-DATA you set the anchor id or the text-value 3) the php gets the value and you can setup a request to your database. Then you return the value which you need and echo it to the ajax-request. 4) your success function of the ajax-request is doing some stuff

For more information about ajax-requests look back here:

-> Ajax-Request NATIVE https://blog.garstasio.com/you-dont-need-jquery/ajax/

A simple JQuery examle:

$("button").click(function(){
  $.ajax({url: "demo_test.txt", success: function(result){
    $("#div1").html(result);
  }});
});
Da Flo
  • 39
  • 1
  • 5
0

in your view:

  <?php $value = '<p id="course_id"></p>';?>

javascript code:

  var course = document.getElementById("courses").value;
  
 document.getElementById("course_id").innerHTML = course;
majid khan
  • 31
  • 3
-1

JavaScript variable = PHP variable try follow:-

<script>
var a="Hello";
<?php
$variable='a';
?>
</script>

Note:-It run only when you do php code under script tag.I have a successfully initialise php variable.

Iron shield
  • 329
  • 4
  • 9