-5
function show_selling_price(sp,co)
{
    $r=sp;
    var e="select * from tbl where id='$r'; ?>";
    document.getElementById('selling_price_'+co).value=e;
}

//php assign value does not work why? //Please correct above code with proper description

AdityaParab
  • 7,024
  • 3
  • 27
  • 40
ridwan
  • 1
  • 3

2 Answers2

1

You can not set a PHP variable from JavaScript. For example this is not possible:

var js_var = 10;
$php_var = js_var;

However you can set a JS variable from PHP:

var js_var = <?php echo $php_var ?>;

PHP is executed on the server side and then the result shows up on the browser. JavaScript is executed on the client side once the server returns the response.

If you really need to pass a JS var then use AJAX to submit vars to the server.

Ahsan
  • 3,845
  • 2
  • 36
  • 36
  • Is there any solution if I want to use in mysql query ? in js – ridwan Sep 20 '14 at 08:45
  • Did you mean to use JavaScript variables in MySQL queries? Then surely you will have to pass the JS variable to the server using AJAX. The bottom line is, JS runs on client side (runs in your browser) and PHP/Mysql runs on server. JS needs to communicate with the server via TCP (for example) to get such things done. One of the easiest solution is to use Ajax. – Ahsan Sep 20 '14 at 09:05
  • would you please give an example of Ajax code as I describe in above question? Thanks for your kind response. – ridwan Sep 20 '14 at 09:29
  • This can be very good starting point: https://developer.mozilla.org/en-US/docs/AJAX/Getting_Started – Ahsan Sep 20 '14 at 09:42
0

It is not possible to assign a javascript variable to a php variable like your example above. Javascript is a client side language whilst PHP is a server side language.

What you can do is to echo out php variables to a javascript code before it is rendered at the visitors web browser like:

<script>
    var text = "<?php echo $variable; ?>";
</script>

If you are setting a variable in Javascript first, and then want to pass it on to PHP, you either have to use ajax, or use a html-form to post the information to the server

Ole Haugset
  • 3,709
  • 3
  • 23
  • 44