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()?

5
  • 1
    possible duplicate of How to pass variables and data from PHP to JavaScript? Commented Jul 25, 2015 at 9:16
  • 1
    Already answered here stackoverflow.com/questions/17314926/… and here stackoverflow.com/questions/13840429/… Commented Jul 25, 2015 at 9: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. Commented Jul 25, 2015 at 12:42
  • @MartinBean Thats why I asked how to integrate js and php. Commented Jul 25, 2015 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. Commented Jul 25, 2015 at 14:23

2 Answers 2

1

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

<?php echo $price ?>
Sign up to request clarification or add additional context in comments.

2 Comments

so if I add $(".sample_icons").click(function(){ var $srcimg=$(this).children("img").attr('src'); image_icon($srcimg); <?php echo $price ?> }); whether I will get the value of variable price?
If you have $price set, then the whole code block above will be replaced with the value of $price.
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);
});

Comments

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.