I have a php file that generates a variable and I would like the variable to be put into a javascript function which is called by onclick on the main page. Is this possible to send from PHP to javascript?
|
You can do the following:
|
|||||||
|
Your JavaScript would have to be defined within a PHP-parsed file. For example, in index.php you could place
|
|||
|
Just write:
Now it's available as a JavaScript variable by the name of |
|||
|
A great option is to use jQuery/AJAX. Look at these examples and try them out on your server. In this example, in FILE1.php, note that it is passing a blank value. You can pass a value if you wish, which might look something like this (assuming javascript vars called
In the FILE2.php example, you would retrieve those values like this:
Then do your MySQL lookup and return the values thus:
This would deliver the message Here is another good example to review. The approach is to create your form, and then use jQuery to detect the button press and submit the data to a secondary PHP file via AJAX. The above examples show how to do that. The secondary PHP file receives the variables (if any are sent) and returns a response (whatever you choose to send). That response then appears in the Success: section of your AJAX call as "data" (in these examples). The jQuery/AJAX code is javascript, so you have two options: you can place it within In your case, it sounds like you can pretty much mirror the first example I suggested, sending no data and receiving the response in the AJAX success function. Whatever you need to do with that data, though, you must do inside the success function. Seems a bit weird at first, but it works. |
|||
|
If I understand you correctly, you should be able to do something along the lines of the following:
|
|||||||
|
You can pass PHP values to JavaScript. The PHP will execute server side so the value will be calculated and then you can echo it to the HTML containing the javascript. The javascript will then execute in the clients browser with the value PHP calculated server-side.
|
|||
|