Skip to content
Advertisement

Calling javascript from php file failed

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:

function decrypt(filename){
            
           $.ajax({
               type: "POST",
               url: "app.php",
               data: { action:'decrypt', filename: filename }
           }).done(function( msg ) {
               alert( "Data returned: " + msg );
           });
           return false;
       } 

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:

<?php
if($_POST['action'] == 'decrypt') {
    my_decrypt($_POST['filename']);
}

function my_decrypt($filename) {
    $filedata = file_get_contents($filename);
    // Remove the base64 encoding from our key
    $key = 'wejnjfff';
    $encryption_key = base64_decode($key);
    // To decrypt, split the encrypted data from our IV - our unique separator used was "::"
    list($encrypted_data, $iv) = explode('::', base64_decode($filedata), 2);
    $result = openssl_decrypt($encrypted_data, 'aes-256-cbc', $encryption_key, 0, $iv);

    echo "<script type='text/javascript' src='./app.js'> 
            showPDF();
            alert('successful!') 
            </script>"; 
    return $result;
}

?>

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

  <?php

  if($_POST['action'] == 'decrypt') {
     $result = my_decrypt($_POST['filename']);
     echo json_encode(['result' => $result,'success' => 'successful']);
  }

  function my_decrypt($filename) {
      $filedata = file_get_contents($filename);
      // Remove the base64 encoding from our key
      $key = 'wejnjfff';
      $encryption_key = base64_decode($key);
      // To decrypt, split the encrypted data from our IV - our unique separator used was "::"
      list($encrypted_data, $iv) = explode('::', base64_decode($filedata), 2);
      $result = openssl_decrypt($encrypted_data, 'aes-256-cbc', $encryption_key, 0, $iv);

      return $result;
  }

  ?>

and in your ajax script

   function decrypt(filename){
        
       $.ajax({
           type: "POST",
           url: "app.php",
           data: { action:'decrypt', filename: filename },
           dataType: 'json',
           success: function (response) {
                if(response.success === 'successful') {
                    alert( "Data returned: " + response.result);
                    showPDF();
                }
            }
       })
       
       return false;
   } 
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement