0

I need to copy the value of a jquery variable into a PHP variable.

My code:

<script>
$(document).ready(function() {
  var gtext = "Sample text";
  console.log(gtext); //I get the gtext printed in console     
  <?php   $variablephp = "<script>document.write(gtext)</script>" ?>
  <?php echo $variablephp; ?> // I cannot get printed this php variable       
  <?php echo "hi"; ?> //This echo statement not get printed
});
</script>

Can anyone please help on this?

My question is different in the sense I want to store a jquery value inside a PHP variable. Not a PHP variable into a jquery element.

7
  • 1
    first set value in hidden field and then get using andy php server side method. Commented May 24, 2018 at 6:01
  • 2
    i see you are not familiar with how the web works, php is a server side language and javascrit in your case is a client side language, you can't use php in javascript Commented May 24, 2018 at 6:03
  • Possible duplicate of How do I insert PHP variable inside jQuery/JavaScript properly? Commented May 24, 2018 at 6:08
  • Don't mix PHP and JavaScript/jquery. It doesn't work and should be handled using hidden inputs or applying data attributes to the DOM somewhere. Also you can't have a script within a script. Commented May 24, 2018 at 6:08
  • The author wrote in the title php inside jquery, and then in the description jquery inside php lol, which way around are you looking for? Commented May 24, 2018 at 6:21

4 Answers 4

2

This would be a php to jquery method

<script type="text/javascript">
     $(document).ready(function(){
       var example = '<?php echo $phpVariable; ?>';
     });
</script>
Sign up to request clarification or add additional context in comments.

2 Comments

Or use this below which is safer as it checks to ensure that the variable exists first
var example = '<?php echo !empty($phpVariable) ? $phpVariable : null; ?>';
1

You can use php like this :

<script>
  $(document).ready(function (e) {
    <?php if (isset($variable) && $variable !=''){ ?>
      var abc = 'this';
    <?php }else{ ?>
      var abc = 'that';
  });
</script>

Comments

1

Okay. So Why I wanted to store the jquery value into a PHP variable is, I wanted the values I got in jquery as session variables in PHP.

Because I want these jquery values to be specific for each user.

Is there any other option in jquery itself, to behave this jquery value like a session variable in PHP?

Sorry if this is irrelevant, as I am new to all this.

4 Comments

If you are collecting data in jquery then it is tricky, the best trick would be to use jquery ajax to post the data to the php server, and store in session using php and then on page refresh the data will be available in the php session
Thank you for your valuable suggestion. I will try this out.
Yes sure thats ok, i added a working example i hope it helps :)
I updated the code example just now and added a cleanInput() function to help you to clean the input text to prevent unwanted code getting into your server as you should always filter user submitted data to some level
1

This would be a jquery to php method

inside index.php

<button id="button1">Press Me</button>

<script type="text/javascript">
    $( "#button1" ).click(function() {
        $.ajax({
            method: "POST",
            url: "server.php",
            data: { name: "John", location: "Boston" }
        }).done(function( msg ) {

        });
    });
</script>

<?php
    //This will display the session data
    if(!empty($_SESSION)) {
        print '<pre>';
        print_r($_SESSION);
        print '</pre>';
    }
?>

inside server.php

<?php

session_start();

function cleanInput($string)
{
    return preg_replace("/[^A-Za-z0-9 ]/", '', $string);
}

if(!empty($_POST['name'])) {
    $_SESSION['name'] = cleanInput($_POST['name']);
}

if(!empty($_POST['location'])) {
    $_SESSION['location'] = cleanInput($_POST['location']);
}

Then after the user clicks the button, if they refresh the page the php $_SESSION will contain the new data

1 Comment

i think the dom or hidden inputs method which is different would only be useful if you want the user to view the data without refreshing the page yet in most cases this is not needed and cannot push data to the session that way

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.