0

How can I get a php variable inside javascript click()? My click() code is

$(".sample_icons").click(function(){
 var $srcimg=$(this).children("img").attr('src');
 image_icon($srcimg);
});

I have a variable $price in a php file and i want something to happen to this variable say increase price when this click() is used. Click() is in a js file. So how can I pass this variable to js file so that it can be used under click()?

MH2K9
  • 11,951
  • 7
  • 32
  • 49
Aby
  • 75
  • 10
  • 1
    possible duplicate of [How to pass variables and data from PHP to JavaScript?](http://stackoverflow.com/questions/23740548/how-to-pass-variables-and-data-from-php-to-javascript) – Matthias A. Eckhart Jul 25 '15 at 09:16
  • 1
    Already answered here http://stackoverflow.com/questions/17314926/how-can-i-edit-a-php-variable-if-i-click-on-a-button and here http://stackoverflow.com/questions/13840429/what-is-the-difference-between-client-side-and-server-side-programming – Antony Jul 25 '15 at 09:16
  • You can’t alter PHP variable values with JavaScript. The PHP script has been processed by the time the web page is rendered on your screen. PHP is a _server_ side language, JavaScript a _client_ side language. – Martin Bean Jul 25 '15 at 12:42
  • @MartinBean Thats why I asked how to integrate js and php. – Aby Jul 25 '15 at 12:49
  • @AbyBasheer You can’t “integrate” them. They’re ran at different times. PHP has finished doing its thing by the time JavaScript comes into the equation. You can’t change PHP variables with JavaScript. – Martin Bean Jul 25 '15 at 14:23

2 Answers2

1

Put this into wherever you need the php variable to be.

<?php echo $price ?>
shadryck
  • 191
  • 4
  • 17
  • so if I add $(".sample_icons").click(function(){ var $srcimg=$(this).children("img").attr('src'); image_icon($srcimg); }); whether I will get the value of variable price? – Aby Jul 25 '15 at 12:44
  • If you have $price set, then the whole code block above will be replaced with the value of $price. – shadryck Jul 25 '15 at 12:48
0

I make use of a hidden input:

<input type="hidden" id="this_price" value="<?php echo $price ?>">

$(".sample_icons").click(function(){
    var this_price = $('#this_price').val();
    var $srcimg=$(this).children("img").attr('src');
    image_icon($srcimg);
});
shadryck
  • 191
  • 4
  • 17
petebolduc
  • 1,233
  • 1
  • 13
  • 20