2

I want to add JavaScript variable to php echo

arr[i]='<?php echo $winner[javascript variable]; ?>';

Thanks

Tharif
  • 13,794
  • 9
  • 55
  • 77
Osama Ahmad
  • 235
  • 3
  • 5
  • 14
  • 1
    I don't believe what you are asking is possible. Do you want some value calculated by JavaScript to be inserted into a PHP script? – dpk2442 Jun 01 '12 at 16:00
  • 1
    Possible duplicate of [Access a JavaScript variable from PHP](http://stackoverflow.com/questions/2338942/access-a-javascript-variable-from-php). See also http://stackoverflow.com/questions/7016701/creating-jquery-ajax-requests-to-a-php-function/7016795#7016795 – JJJ Jun 01 '12 at 16:02
  • if anything, you can use ajax to send a javascript variable to the server, then return the rendered PHP. but that's probably not the workflow you're looking for, since i'm sure you're talking about rendering a page normally... – Ian Jun 01 '12 at 16:03

1 Answers1

6

You can't.

  1. PHP runs on the server and outputs some text.
  2. The text is sent to the browser
  3. The browser interprets the text as HTML / JavaScript / etc

The PHP has finished running by the time the JavaScript is executed.

If you want to pass data back you need to make a new HTTP request and run a PHP script from scratch.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • I hava php array and I want to convert it to javascript array Is this possible ? – Osama Ahmad Jun 01 '12 at 16:03
  • 1
    `var myJSArray = ;` – Quentin Jun 01 '12 at 16:05
  • See http://stackoverflow.com/questions/393479/best-way-to-transfer-an-array-between-php-and-javascript – JJJ Jun 01 '12 at 16:05
  • i'm sorry. but it can be. you need to echo all the script including your php variables and then run javascript – MFarooqi Jul 07 '17 at 18:31
  • @MFarooqi — Your two sentences contradict each other. – Quentin Jul 07 '17 at 20:46
  • :D I mean to say "it is possible".. I said sorry for your "not possible" reason. and again (i apology for poor english) – MFarooqi Jul 07 '17 at 21:39
  • @MFarooqi — I understood what you were saying. You are still contradicting yourself. If [passing data from JS to PHP] is possible [without making a new HTTP request], then you don't have to do all the PHP stuff first. – Quentin Jul 07 '17 at 21:43