0

I’m using below a simple Jquery code to call a PHP page and get the button information back in a div:

<head>
<script>
  $(document).ready(function(){
    $('#myButtons input:radio').change(function() {
      var buttonValue = $("#myButtons input:radio:checked").val();
        $("#myDiv").load('myPHPfile.php', {selectedButtonValue : buttonValue});
    });
  });
</script>
</head>

<body>
  <div id="myButtons">
    <input type="radio" name="category" value="10" />ButtonA 
    <input type="radio" name="category" value="20" />ButtonB
  </div>
  <div id="myDiv">Click the button to load results</div>
</body>

myPHPfile.php

<?php 
  if( $_REQUEST["selectedButtonValue"] )
  {
     $buttonPHP = $_REQUEST['selectedButtonValue'];
     echo "Value button is ". $buttonPHP;
  }
?>

How can I get the PHP information inside JavaScript, as follows:

alert(<?php echo('buttonPHP'); ?>);

Note: The following code shows the alert box message, but I can’t use it since I need the $buttonPHP value:

$("#myDiv").load('myPHPfile.php', {selectedButtonValue : buttonValue}, function(data){ alert(data); });

I’ve tried $_SESSION in myPHPfile.php, and also all jQuery AJAX functions: load(), get(), post() and the ajax() method, none of them is giving the PHP value inside JavaScript.

I looked all over but I couldn’t find an answer.

6
  • 1
    JS runs on the client, PHP runs on the server. Either you embed the PHP value in the js code at the time the page is built, or you use AJAX to retrieve the php value when the JS code runs. Those are your only two options. Commented Jan 10, 2013 at 16:10
  • short answer no, long answer yes.. if your javascript is in your document and not a standalone js file then you can use standard php within it assuming its a php file. if its not theres ways to go about doing it. Example you can set a global style var in script tags in the document above the js file. or you could use php as your js file, but with a php extension and at the top of the file use javascript headers to fool it into thinking its a js file. theres a number of things you can do, none better than the other per say. But all in all the 2 dont work together Commented Jan 10, 2013 at 16:10
  • Why do you pass a form value to your PHP to then receive it in JS when you could simply access it directly? Commented Jan 10, 2013 at 16:11
  • Because in my JavaScript there is a PHP loop which is getting a PHP value (using this value). Commented Jan 10, 2013 at 16:19
  • Not correct. If you want to get a value form a PHP file then you can encode it into a JSON and return it that way. Simple encode it like the example below and you can grab the data from the PHP file that is separate from the php file your getting the data Commented Jan 10, 2013 at 16:23

4 Answers 4

2

You would be better with an $.ajax request. Don't echo the 'Value of button is' part, just echo the actual value. For example:

$.ajax({
  url: "myPHPfile.php",
  context: document.body
 }).done(function(data) {
   var buttonValue = data;
   // Whatever you want to do with the data goes here.
 });

See the jQuery docs http://api.jquery.com/jQuery.ajax/

Alternatively, if you are generating the page with PHP, just echo the PHP variable into the JavaScript

<script>
 ...
    var buttonValue = "<?php echo $buttonPHP; ?>";
 ...
</script>
Sign up to request clarification or add additional context in comments.

6 Comments

Thanks, but then again, it will not be a PHP value. I must get it as a PHP value inside JavaScript.
It won't be a PHP value, once the page gets rendered, it will look like this, `var button = "This is my whatever the $buttonPHP variable equals';
Thanks again, but please see my 'note' in my original post regarding showing an alert box message.
I'm failing to understand why you are passing a value into PHP, only for the same value to be returned to be used in the JS?
Because in my JavaScript there is a PHP loop which is getting a PHP value (using this value).
|
2

Encode it in JSON instead of trying to echo the data :

<?php 
  if( $_GET["selectedButtonValue"] )
  {
     $buttonPHP = $_GET['selectedButtonValue'];
     header('Content-Type: application/json');
      echo json_encode($buttonPHP);

  }
?>

Then use jquery get json to grab the data

$.get('myPHPfile.php?selectedButtonValue='+buttonvalue, function(data){
                    console.log(data);

                });

3 Comments

You may actually have to change the $_REQUEST to a $_GET instead but i believe it should work with both
@ Chad, can you please explain where is PHP variable in JavaScript?
It should be coming back as the variable data. so in my example above you should write your logic as "data". you may want to look into JSON and how to read that
0

Try:

alert('<?php echo $buttonPHP; ?>');

3 Comments

Thanks, but either this or $_SESSION are not showing the value.
I forgot the quotes. Try now.
Thx. with the quotes or without…, still doesn’t show the PHP value.
0

As a temporary solution, you could quickly merge both into a dirty code like this:

index.php:

<?php 

  $buttonPHP = "10"; //Set up your default button variable

  if( $_REQUEST["selectedButtonValue"] == 10 )
  {
     echo "Selected button value: 10";  //You can also print $_REQUEST["selectedButtonValue"] here directly, but what's the point if you can select it from DOM through jQuery?
     exit;
  } else if ($_REQUEST["selectedButtonValue"] == 20) {
     echo "Selected button value: 20";
     exit;
  }
?>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
  var buttonValue = <?php echo $buttonPHP ?>;  //Duplicate default value from PHP to JS
  $(document).ready(function(){
    $('#myButtons input:radio').change(function() {
      var buttonValue = $("#myButtons input:radio:checked").val();
        $("#myDiv").load('index.php', {selectedButtonValue : buttonValue});
    });
  });
</script>
</head>

<body>
  <div id="myButtons">
    <input type="radio" name="category" value="10" />ButtonA 
    <input type="radio" name="category" value="20" />ButtonB
  </div>
  <div id="myDiv">Click the button to load results</div>
</body>
</html>

index.php rendered in browser:

<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
  var buttonValue = 10;  //Duplicate default value from PHP to JS
  $(document).ready(function(){
    $('#myButtons input:radio').change(function() {
      var buttonValue = $("#myButtons input:radio:checked").val();
        $("#myDiv").load('index.php', {selectedButtonValue : buttonValue});
    });
  });
</script>
</head>

<body>
  <div id="myButtons">
    <input type="radio" name="category" value="10" />ButtonA 
    <input type="radio" name="category" value="20" />ButtonB
  </div>
  <div id="myDiv">Click the button to load results</div>
</body>
</html>

EDIT: Stored session

<?php 

  session_start();

  if (isset($_REQUEST['selectedButtonValue'])) {
      $_SESSION['selectedButtonValue'] = $_REQUEST['selectedButtonValue'];
      echo $_REQUEST['selectedButtonValue'];
      exit;
  } else if (!isset($_SESSION['selectedButtonValue'])) {
      $_SESSION['selectedButtonValue'] = 10;
  }

?>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
  var buttonValue = <?php echo $_SESSION['selectedButtonValue']; //Get input value from session ?>;
  $(document).ready(function(){
    $('#myButtons input:radio').change(function() {
      var buttonValue = $("#myButtons input:radio:checked").val();
        $("#myDiv").load('index.php', {selectedButtonValue : buttonValue});
    });
  });
</script>
</head>

<body>
  <div id="myButtons">
    <input type="radio" name="category" value="10" />ButtonA 
    <input type="radio" name="category" value="20" />ButtonB
  </div>
  <div id="myDiv"><?php echo $_SESSION['selectedButtonValue']; //Get input value from session ?></div>
</body>
</html>

Also make sure you filter the $_REQUEST variable, because as of now, it will print anything. See http://en.wikipedia.org/wiki/Cross-site_scripting for details.

9 Comments

Thanks, your solution generate an error since $_REQUEST["selectedButtonValue"] is undefined (JavaScript has to make the call).
@user203952 ugh, try if (isset($_REQUEST["selectedButtonValue"])) { ... }
@user203952 I've added jQuery and tested it – it worked for me. What we're doing here now, is that we're passing buttonValue back and forth. If you want to print some text inside #myDiv based on selected button value, do so inside PHP responder logic.
@ Kai, I get in the alert box message: ‘true’, but I don’t get the value (10 or 20) when I choose the radio buttons.
@user203952 Well, I've edited the code so it prints what's been requested. But I really see no point in sending inputValue back to server in order to print it somewhere else in DOM.
|

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.