1

Suppose I have php page index.php

<?php
$x=$_POST[sent]  // I get some value in #x
?>
<html>
<head> 
<script>
function getVar()
{
var x= <How to fetch $x from php code>
alert(x);

}
</script>
</head>
<body> 
<button type="submit"> click </buttton>
</body>

</html>

How can I fetch $x in getVar(_) function? Or another case some variable is in JS then getting it into php code?

Is it possible or not?

Actually I have index.php and through ajax request loading new page url.php. I want to send few variables to url.php and want to access them in JS code in it.

Here is my ajax request:

 var id=mydata.id; // Guess I am getting some data here
 $.ajax({
                         url:'url.php'
                         ,async:     true
                         ,cache:     false
                         ,dataType:  'html'
                         ,success:   function(data){
                           $('body').html(data);
                           FB.XFBML.parse();
                         }

I want to send id in ajax request to url.php. I will fetch it as $x and want to use it in JS code.

3
  • 1
    Everything is possible. Please be more specific. Do you want to fill X with server value every time you call getVar()? In this case you need a $.ajax. Commented Oct 17, 2013 at 16:03
  • Did you read any basic stuff about JS and PHP, difference between Client- / Serverside and general HTTP communication? Commented Oct 17, 2013 at 16:09
  • Look at the related column Commented Oct 17, 2013 at 16:10

4 Answers 4

3

php to javascript can be done by using

<?php $x = "iam a php variable"; ?>
<script>
        function getVar()
        {
        var x= "<?= $x; ?>";
        alert(x);    //alerts **iam a php variable**(value of $x from php)
        }
</script>

The vise versa can be done via Ajax. Here is the simple example

<script>
function showUser()
{
var str= "iam a javascript variable";
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    alert(xmlhttp.responseText); //alerts response from php
    }
  }
xmlhttp.open("GET","new.php?q="+str,true); //you can send request through post or get methods 
xmlhttp.send();
}
</script>

Here, i am getting a javascript variable in php through ajax using GET. In new.php, i am just printing out the request received via GET

<?php 
    print $_GET["q"];    //prints **iam a javascript variable**(value of str from   javascript) 
?>
Sign up to request clarification or add additional context in comments.

Comments

1

Communication between PHP and Javascript is a classic example of client-server communication. In this case, PHP is your server application and Javascript is your client application. There are many protocols established for this communication, but you should take a look at AJAX and RESTful services.

In order to understand what is going on, i suggest that you read this tutorial on HTTP and REST, from a PHP programmer point of view. When designing a client-server application, PHP would "generate" all the content, by applying business logic and communicating with the database, and Javascript would ask PHP for this content on certain events (click, show table, etc). PHP, instead of outputting HTML, would output XML or JSON, so you can parse and show that data in Javascript.

Comments

0

Transfer boths ways:

function getVar($var)
{
var xmlhttp;

    xmlhttp=new XMLHttpRequest();

    xmlhttp.onreadystatechange=function()
      {

      if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
        $phpVar = xmlhttp.responseText;
            return $phpVar;
        }
      }

    xmlhttp.open("POST","/yourPage.php",true);
    xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlhttp.send("var=" + $var);


}

And then on yourpage.php:

<?
if (isset($_POST["var"])) {

  die($_POST["var"]);
  }
?>

Comments

0

If you're simply trying to get pass the value of $x variable to JavaScript, then it can be done as follows:

function getVar()
{
    var x= "<?php echo htmlspecialchars($x); ?>";
    alert(x);    
}

Here's a working example:

<?php
    $x = $_POST['sent']  // I get some value in #x
?>
<html>

<head> 
    <script>
    function getVar()
    {
        var x= "<?php echo htmlspecialchars($x); ?>";
        alert(x);
    }
    </script>
</head>

<body> 
    <button type="submit" onclick="getVar()"> click </buttton>
</body>

</html>

If the $x variable is received by the script correctly, then it will be alertd when you click the button.

2 Comments

I think he want to get with ajax.
<?php echo htmlspecialchars($x); ?>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.