-4

i'm creating a function like this :

function DoSomething(var Var1)
{
  <?php
    echo Var1; //This will probably not work.
  ?>
    //Note : Not using the echo command originally , using fopen , fputs & fclose at the real one... Because the real function is long i won't put it.
}

Note : I saw the possible duplicates and didn't get my answer...

What is the best solution ?

Thanks for your attention.

Note II : Please don't set this as a duplicate of irrelevant posts... This Post is not about differences between server-side and client-side languages !

Arshia Aghaei
  • 17
  • 1
  • 1
  • 5

2 Answers2

0

I looked at the comments for more clarification, and it looks like you are trying to do something in PHP with the argument to the function.

You cannot achieve this goal with the code you currently have. PHP runs on the server and sends the HTML and JavaScript to the browser, which then renders the HTML and runs the JS. So, the JS runs after the PHP is run, and the JS cannot send info to the PHP because they are running on seperate entities.

Solution

However, you can use an AJAX request or an HTTP POST request. What these will do is send another request to the server with some data (Var1), and the server can respond with other information.

For this situation I suggest using AJAX, because you can send requests from JavaScript (like in thefunction DoSomething). HTTP POST is used when you submit a form or do something in HTML.

I suggest you look at JQuery, because it makes AJAX requests easy. Specifically, look at Jquery.ajax() and Jquery.post()

Hope this cleared things up! @mention me in the comments if you have any questions.

  • Some examples would help OP, also links to relevant docs or questions. – Soubhik Mondal Apr 02 '16 at 16:46
  • @TimothyHiginbottom , Isn't it better to put a php tag + the function with php parameters in tag and then call the function from js ? Or it is not possible ? – Arshia Aghaei Apr 02 '16 at 17:12
  • It is not possible. PHP runs on the server. The PHP interpreter scans the code, looking for PHP tags, and creates raw HTML and JS as output. Then it sends this newly generated text (code) to the browser which renders HTML and runs JS. PHP runs before js, so it can modify the raw js code, but JS cannot interact directly with PHP. – Timothy Higinbottom Apr 02 '16 at 17:13
  • @TimothyHiginbottom , Can you give an example to how to send the parameters to php variables ? For example there is a Var1 variable defined on the function , after that the – Arshia Aghaei Apr 02 '16 at 18:28
-1

put your variable in an hidden html input and read it in javascript.

<?php
 echo <input type="hidden" id="mystuff" value="your stuff">
?>

javascript

var stuff = document.getElementById('mystuff').value;
Denis Kohl
  • 739
  • 8
  • 13