0

I have been trying to return an alert of a value in a php function using AJAX. However, the alert returns the entire php script, instead of looking for where 'echo' is used. Here is my ajax call in JS:

function sendEncryptionToServer(thisData) {

    $.ajax({
        url: 'http://myurl.com/encrypt.php',
        type: 'POST',
        data: { method : "encryptData", dataInQuestion : "Hello" },
        success: function(response){
            alert(response);
            console.log("SUCCESS");
        },
        error: function(response) {
            alert(response);
            console.log("ERROR");
        }
    });
}

And here is my php file

<?php

//Encrypt
  if(isset($_POST['dataInQuestion']) && $_POST['method'] == 'encryptData')
  {
    $data = json_encode($_POST['dataInQuestion']);

    $ciphertext = "fakecipher";
    $api_key = "fakekey";
    $encryptedData = openssl_encrypt($data, "AES-128-CBC", $ciphertext + $api_key, OPENSSL_RAW_DATA, $ciphertext); 
    $returnedEncryptedData = base64_encode($encryptedData);
    echo json_encode($returnedEncryptedData); //This shows the encrypted string
  }

  //Decrypt
  if(isset($_POST['dataInQuestion']) && $_POST['method'] == 'decryptData')
  {
    $data = json_encode($_POST['dataInQuestion']);

    $ciphertext = "fakecipher";
    $api_key = "fakekey";
    $decryptedData = openssl_decrypt($encryptedData, "AES-128-CBC", $ciphertext + $api_key, OPENSSL_RAW_DATA, $ciphertext);

    echo $decryptedData;
  }
?>

What ends up happening is my alert displays my entire php file, from start to finish. I thought it would look into the isset and echo out the response based on the data object? If it means anything, I am running a local server via node.JS, but the http:/myurl.com/encrypt.php exists on a real server.

  • have you seen this question? https://stackoverflow.com/questions/17752001/ajax-call-returns-entire-page-rather-than-just-the-echo-value – Niels Van Steen May 11 '20 at 19:21
  • You mean print the code? The webserver may not be configured to process php file. – Felippe Duarte May 11 '20 at 19:28
  • @NielsVanSteen Hey thanks for the fast reply. I have not, but my encrypt.php file has no html, what I copied into my question was the entire script. What seems to be happening? – Mick Marsden May 11 '20 at 19:31
  • Your PHP is not being executed for some reason. Check the two links shown as duplicates. If you take that URL that your ajax is trying to access and go directly to it in the browser, does it show the PHP code? If so, then you definitely need to read https://stackoverflow.com/questions/5121495/php-code-is-not-being-executed-instead-code-shows-on-the-page – aynber May 11 '20 at 19:32
  • @aynber Thanks for pointing me in the right direction. When accessing that url, it does indeed show the PHP code in full. I'll read the question, sorry about the duplicate. – Mick Marsden May 11 '20 at 19:36
  • No worries. It's a learning process. :-D – aynber May 11 '20 at 19:38

0 Answers0