mrbunyrabit mrbunyrabit - 5 months ago 72x
Ajax Question

send javaScript variable to php variable

Possible Duplicate:

How to pass JavaScript variables to PHP?

First I thought that I had to convert javascript to php, but then I found out that I cannot because of server and client side executions. So now I simply want to send ONE variable

<script type="text/javascript">
function scriptvariable()
var theContents = "the variable";

to a php variable


That function in the javascript executes when let's say I click on a button.

Now I have no idea on how to assign that phpvariable to the javascript one to use the phpvariable to look up stuff in my Database.
I know I can add it to my url or some thing and refresh the page.. But I would like to do it with AJAX as I might have to use this Ajax method further in my webpage...

So is there an easy way to do this without having to dump pages of code on my page to do one simple thing?


As Jordan already said you have to post back the javascript variable to your server before the server can handle the value. To do this you can either program a javascript function that submits a form - or you can use ajax / jquery.

Maybe the most easiest approach for you is something like this

function myJavascriptFunction() { 
  var javascriptVariable = "John";
  window.location.href = "myphpfile.php?name=" + javascriptVariable; 

On your myphpfile.php you can use $_GET['name'] after your javascript was executed.