It is not possible to directly call PHP function from JavaScript and vice versa. Part of the reason for this is that as @Pekka indicated JS runs clientside (in your browser) while PHP runs server-side (on your server).
It is however possible to use AJAX for your purposes:
HTML
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript">
function getCountryCode()
{
countryCode = qrcode_getinfo(qrCode1,"mfg_c_a_code",0)
return countryCode;
}
function doAjax(){
var countryCode = getCountryCode();
$.ajax({
'url' : '<THE_URL_TO_YOUR_PHP>?countryCode=' + countryCode,
'method' : 'GET',
'success' : function(data){
console.log(data);
// do your handling here
},
'error' : function(data){
console.log(error);
// this function is executed on an HTTP error
}
});
}
</script>
PHP
This is your php file that would do your validation. In principle it is a different file than the file that outputs the html as shown above.
$countrycode = $_GET['countryCode'];
# handle countrycode
echo "<What you want to return to JS>";
Edit
On the additional question of how to get session
variables to js.
Would I navigate to your page in my browser, the following would happen: If I requested a file with an .php
extension, the PHP processer gets run on it. This processer identifies all code between the tags <?php
and ?>
as PHP, and thus runs all this code. If it encounters an echo
statement, it echo's out the specific value at the location of the php-block.
After PHP is done processing, the page is served (given) to your browser, where it will be interpreted as a combination of HTML/javascript/... Javascript interprets everything between the tags <script>
and </script>
as javascript.
So, what if we where to make a request to index.php?par=val
on your server, and index.php
looks like
<script type="text/javascript">
function doStuff(){
var param = <?php echo json_encode($_GET['par']);?>;
}
</script>
(the json_encode
function ensures that the variable is in proper json format. Of course you can change the `$_GET['par']; to be whatever you would like.)
Remember, PHP only cares about whats between the <?php
and ?>
tags, so this would output:
<script type="text/javascript">
function doStuff(){
var param = "val";
}
</script>
You will need to edit this to match your requirements of course, but this is the basics of passing parameters from PHP to client-side (JS)