As the previous speakers already explained, you need to think in terms of client-side running code and server-side running code.
Whenever you want to share a state between those two parts of your application you need some communication mechanism.
Client -> Server
For this you need to make a HTTP request. This can either be a post or a AJAX call. For the latter one just have a look at jquery.ajax as you're obviously already using jQuery anyway.
$.post({ "savesample.php", {myPostVar: str} }).done(function() { alert("sample saved."); });
Of course you need a serverside script to handle this request:
<?php $yourVar = $_POST["myPostVar"]; // TODO use mysqli::escape_string or similar!! mysql_query("INSERT INTO sample (sample) VALUES ('".$yourVar."')"); ?>
Server -> Client
This is a lot easier. You can of course use ajax again (GET requests on your php file, which generates a nice javascript-compliant output like JSON).
Or just write your variable to an inline-script-tag:
<script> <![CDATA[ var yourJsvar = '<?= $yourPhpVar ?>'; ]]> </script>
Further Reading
As your php file is an open gate for all kinds of misuse you should secure it using one-time authorization tokens. Once you are used to the basic concepts, go on with the following topics:
- CORS
- SQL injection
- Authenticated AJAX calls