0

I have a function:

            $("button.btn-info").click(function() {
                 var id=this.id;
            });

So, and I have to get item from PHP array $records with 'id' number. I need to insert this item into 'alert' function, but I don't know how I can pass variable from JS to PHP.

Please, tell me.

thecodeparadox
  • 86,271
  • 21
  • 138
  • 164
user1477886
  • 263
  • 1
  • 6
  • 19

2 Answers2

0

Use for example json_encode($records) and output it in a <script> tag in your html file like this:

<script type="text/javascript">
    var records = <?php echo json_encode($records); ?>;
</script>

this should usually stand before your other js code that depends on the records-var.

or else you could use ajax (jQuery.get) if you want to load this var dynamically.

Stefan
  • 2,028
  • 2
  • 36
  • 53
0

Not entirely sure I understand your question. It appears you just wish to write your PHP variable out to the javascript:

$("button.btn-info").click(function() {
    var id=<?php echo $records->id?>;
});

Just remember that the Web page that hosts the JavaScript is static. If you want it to interact with PHP, you need to utilize AJAX or something else more advanced.

John Green
  • 13,241
  • 3
  • 29
  • 51
  • id variable I have got in JS code. Why do you use it in PHP function? – user1477886 Jul 01 '12 at 10:27
  • Because your question doesn't make much sense. The code above gives a variable from PHP to the JavaScript. If you're wanting to send something to the PHP (which is not how I read your question), you need to use an AJAX bridge. The lifecycle of the PHP is over by the time the javascript is interactive, which means that you need to build on a session or a DB. – John Green Jul 01 '12 at 10:32