Reputation: 2876
I am trying to encrypt a password when submit button is pressed.
I don't understand why the value of password input is not changed, the ecryption is done correctly.
<script>
function cript(){
var pass = CryptoJS.SHA1("<?php echo $_POST["password"]; ?>");
var passString = pass.toString();
console.log(passString);
document.getElementById('inputPassword').value = passString;
}
</script>
and on HTML Form:
<input type="submit" class="btn btn-primary" value="Proceed" onclick="cript()">
Can anyone tell me the solution?
Upvotes: 1
Views: 10324
Reputation: 1466
Your PHP code can't execute on click. It can only be executed by server when you load the file, since you are waiting for user to input the password and then call the function it is not going to work.
Your javascript var pass is empty since you don't have POST at that point in time.
Flow that can work is: execute PHP -> deliver html + javascript -> user input -> do crypt -> submit
So you can not rely on PHP to give you data in this case. You need to go with different approach here.
Try
<script>
function cript(){
var pass = CryptoJS.SHA1(document.getElementById('inputPassword').value);
var passString = pass.toString();
console.log(passString);
document.getElementById('inputPassword').value = passString;
}
</script>
This only takes care of problem related with trying to pass PHP variable to javascript variable. Security issues about SHA1 are another topic and if this is school project or fiddling around to learn javascript then it is ok. This example for learning purposes how to use javascript to access values in elements is ok. However if this code is ever going to be put on server and be used, then SHA1 should definitely be avoided
Upvotes: 1
Reputation: 9314
JavaScript executes in the browser. PHP executes on the server. The code you've written doesn't work because it tries to execute them both in the browser.
"<?php echo $_POST["password"]; ?>"
executes first, while the page is constructed on the server. At this point in time, the password probably doesn't exist on the server, so the value in the javascript is most likely blank.
"<?php echo $_POST["password"]; ?>"
becomes ""
When the javascript loads in the browser, it is effectively var pass = CryptoJS.SHA1("");
. You can verify this with a debugger like firebug or with a proxy like ZED or just by viewing the source of the page from within the browser. When this executes, it's hashing nothing, and so storing nothing in the password field.
When you post, the password field is empty, because of #2. Your server gets nothing, so your password doesn't change.
By the way,
Upvotes: 6
Reputation: 2156
The form posts before cript
gets called.
Call the cript
function in the form's onsubmit
event:
<form onsubmit="cript()">
Upvotes: 1