-1

I need to pass value from javascript file (javascript.php) to php file (php.php), and get it back.

file javascript.php

<script>
var name = 'catalin';
$.post('php.php', {jsvar: name});
</script>

file php.php

$phpvar = $_POST['jsvar'];

How do I get variable's value back on the file javascript.php ? Thanks!

catalin
  • 946
  • 6
  • 14
  • 31
  • Possible duplicate of [jQuery Ajax POST example with PHP](http://stackoverflow.com/questions/5004233/jquery-ajax-post-example-with-php) – KhorneHoly Jan 05 '17 at 10:53
  • get your suitable answer from below and check that as right answer in left ! – M. Alim Jan 05 '17 at 11:03

4 Answers4

0

if you r doing this with ajax then just echo the php value and get it with return value in jquery

  <script>
  $(document).ready(function(e){
  var name = 'catalin';
  $.post('php.php', {jsvar: name},function(returnedValue){
 alert(returnedValue);
  });
 })
 </script>

in php do this

  $phpvar = $_POST['jsvar'];
   echo  $phpvar ;

you can see the result in alert.

M. Alim
  • 153
  • 16
0
$.ajax({
  type: "POST",
  url: url,
  data: {"var":"value"},
  success: function(data) {
   // do something
  }
});

https://api.jquery.com/jquery.post/

harry
  • 483
  • 2
  • 12
0

You can use callback function as below:

file javascript.php

 <script>
    var name = 'catalin';
       $.post('php.php', {jsvar: name},function(data,status,xhr){
    alert(data);
    });
    </script>

file php.php

$phpvar = $_POST['jsvar'];
echo $phpvar;
Hikmat Sijapati
  • 6,869
  • 1
  • 9
  • 19
0

My answer is nothing new but find the complete code. I haven't tested it. Please be aware there might be a minor typo.

javascript.php

<!doctype html>
<html lang="en">
<head>
    <title>Document</title>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
    <button onclick="test_request()">Test Request</button>

    <script>
    function test_request() {
        $.post("php.php", {jsvar: name}, function(data_from_php) {
            console.log(data_from_php);
        });
    }
    </script>
</body>
</html>

php.php

<?php
    $phpvar = $_POST['jsvar'];
    echo  'Hello' . $phpvar;

What's happening is jQuery is posting some value to the HTTP server (aka a POST request) and the anonymous function(data_from_php) is waiting for the server to respond with some data. As soon as the data arrives the function is triggered.

You can verify it from the Chrome's debugger window (or Firefox etc). For example, in Chrome just press Ctrl+Shift+I to open the developers tools. Click on the Network tab and click on XHR and notice when the request is made. You will be able to see what is happening under the hood and how it is working.

Eddie
  • 1,043
  • 8
  • 14