1

i have a few php vars:

$test = 12345;
$test1 = "test1";
$test2 = "test2";

and i have a jquery function:

onlike:function(response){
    $('input#helpdiv').trigger('click');    
}

what i want is to pass those php vars through a jquery post to another test.php file.

I was thinking on something like this:

var test = <?php echo $test; ?>; 
var test1 = <?php echo $test1; ?>; 
var test2 = <?php echo $test2; ?>; 

onlike:function(response){
    $('input#helpdiv').trigger('click');
    $.post("test.php", { test, test1, test2 } );
}

and then how do i get them in the test.php? just like $_GET["test"], ...

any ideas on how to put this together?

thanks

Patrioticcow
  • 26,422
  • 75
  • 217
  • 337

3 Answers3

3
<script language='javascript'> 
 var test = "<?php echo $test; ?>"; 
  var test1 = "<?php echo $test1; ?>"; 
  var test2 = "<?php echo $test2; ?>"; 

  onlike:function(response){
      $('input#helpdiv').trigger('click');
      $.post("test.php", { test:test, test1:test1, test2:test2  } );
        }
 </script>

in test.php you can access them as $_POST['test'],$_POST['test1'],$_POST['test2']

EDIT:

to avoid problems caused by quotes in between the variable values, as explained in: how to post and get php vars with jquery?

  var test = "<?php echo json_encode($test); ?>"; 

and the values may be accesed in test.php as

 $test1 = json_decode($_POST['test'])
Community
  • 1
  • 1
Mithun Satheesh
  • 27,240
  • 14
  • 77
  • 101
  • Yes that's a better response. – voncox Aug 25 '11 at 16:47
  • 1
    You have to be careful here to escape the values properly. If there's a quotation mark in any of the $test variables it'll break shit. – Bill Criswell Aug 25 '11 at 16:51
  • @Bill Criswell: you are right.. adding addslashes here and filtering with stripslashes in test.php .. can this solve the issue? – Mithun Satheesh Aug 25 '11 at 16:57
  • I did some research and it seems like it could get to be messy. I came across this post though and it seems thorough... http://stackoverflow.com/questions/168214/pass-a-php-string-to-a-javascript-variable-including-escaping-newlines – Bill Criswell Aug 25 '11 at 17:10
2
var test = '<?php echo $test; ?>';

You need to put quotes around a value in JS

Also do you have those variables available when page loads ? As javascript will be rendered on page load it will take existing values at that time.

Also check http://api.jquery.com/jQuery.post/ for making call more clearner to handle response.

Pit Digger
  • 9,618
  • 23
  • 78
  • 122
1

Just to conclude the comments I made above: 1st quote the string literal vars e.g.

    $test = "test";
var test = '<?php echo $test; ?>';

Then add them as key value pairs to the object you're passing to the post function e.g.

{ test: test }
voncox
  • 1,191
  • 7
  • 13