I have three different files: index.html, app.js, app.php
. On HTML element <a href="./files/sweetsencrypt.pdf" onclick="return decrypt(this.href);">Decrypt Sweets</a>
I am calling javascript function in which I am giving ajax call to PHP:
JavaScript
x
12
12
1
function decrypt(filename){
2
3
$.ajax({
4
type: "POST",
5
url: "app.php",
6
data: { action:'decrypt', filename: filename }
7
}).done(function( msg ) {
8
alert( "Data returned: " + msg );
9
});
10
return false;
11
}
12
Till this everything is okay. When the PHP function is called, I need to call javascript functionality from app.js
file in app.php
file. But its getting failed. I am trying:
JavaScript
1
23
23
1
<?php
2
if($_POST['action'] == 'decrypt') {
3
my_decrypt($_POST['filename']);
4
}
5
6
function my_decrypt($filename) {
7
$filedata = file_get_contents($filename);
8
// Remove the base64 encoding from our key
9
$key = 'wejnjfff';
10
$encryption_key = base64_decode($key);
11
// To decrypt, split the encrypted data from our IV - our unique separator used was "::"
12
list($encrypted_data, $iv) = explode('::', base64_decode($filedata), 2);
13
$result = openssl_decrypt($encrypted_data, 'aes-256-cbc', $encryption_key, 0, $iv);
14
15
echo "<script type='text/javascript' src='./app.js'>
16
showPDF();
17
alert('successful!')
18
</script>";
19
return $result;
20
}
21
22
?>
23
Here, not the showPDF();
function is called nor the alert('successful!')
popup is shown. I am new to PHP. Where am I getting wrong? How to call javascript from PHP?
Advertisement
Answer
JavaScript
1
21
21
1
<?php
2
3
if($_POST['action'] == 'decrypt') {
4
$result = my_decrypt($_POST['filename']);
5
echo json_encode(['result' => $result,'success' => 'successful']);
6
}
7
8
function my_decrypt($filename) {
9
$filedata = file_get_contents($filename);
10
// Remove the base64 encoding from our key
11
$key = 'wejnjfff';
12
$encryption_key = base64_decode($key);
13
// To decrypt, split the encrypted data from our IV - our unique separator used was "::"
14
list($encrypted_data, $iv) = explode('::', base64_decode($filedata), 2);
15
$result = openssl_decrypt($encrypted_data, 'aes-256-cbc', $encryption_key, 0, $iv);
16
17
return $result;
18
}
19
20
?>
21
and in your ajax script
JavaScript
1
18
18
1
function decrypt(filename){
2
3
$.ajax({
4
type: "POST",
5
url: "app.php",
6
data: { action:'decrypt', filename: filename },
7
dataType: 'json',
8
success: function (response) {
9
if(response.success === 'successful') {
10
alert( "Data returned: " + response.result);
11
showPDF();
12
}
13
}
14
})
15
16
return false;
17
}
18