Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

214
Views
Is there any way to access a JS variable in PHP within the same file?

I have this html file which I am using to encrypt a string to sha1 hash. I receive the string like "1 | 2 | 3" from a javascript function (I haven't shown the function below), and I need to replace the | with - and then encrypt the modified string. Here's the code I have built so far -

<!DOCTYPE html>
<html>
<body>
<script type="text/javascript">
    var test;
    var value;
    var message = "1 | 2 | 3";
    test = message.split(' | ');
    value = "<?php $final = test[0] . " - " . test[1] . " - " . test[2]; echo sha1($final);?>";
    alert(value);
</script>
</body>
</html>

I came to know about posting the value to another PHP file using HTML form, and accessing it through $_POST/$_GET - but my app won't allow for 2 files; hence I am trying to combine it all in one html file...


PHP has a in-built SHA1 encryption function, but javascript doesn't - the value variable in the above code is broken; how do I pass a variable to PHP from JS and back from PHP to JS? Again, I just want to modify (encrypt it) a JS variable using PHP and then set the PHP modified variable's value to a new JS variable. What should I do? Please guide :)

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You can't access to javascript variable like that. PHP is executed by the server and JavaScript by the client. You can create an ajax function in JS that call your PHP script.

Tutorial: http://www.w3schools.com/ajax/

JS

function loadDoc() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (xhttp.readyState == 4 && xhttp.status == 200) {
       xhttp.responseText // return from your PHP;
    }
  };
 xhttp.open("GET", "yourphp.php?variable="+yourjsvariable, true);
 xhttp.send();
}

PHP

<?PHP

return $_GET["variable"]; 

?>
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!