Why does ajax return empty string from php json_encode - Hack The Tech - Latest News related to Computer and Technology

Hack The Tech - Latest News related to Computer and Technology

Get Daily Latest News related to Computer and Technology and hack the world.

Monday, October 16, 2023

Why does ajax return empty string from php json_encode

I'm trying to return json_encode to an ajax function through php.

The echo json_encode($eMessage) function outputs this to the screen if I point the form target to the php file : php output to screen

But the ajax function returns this : ajax function output

Here's my code :

PHP in sendEmail.php :

<?php
    require 'aws/aws-autoloader.php';

    use Aws\Ses\SesClient;
    use Aws\Exception\AwsException;
    use Aws\Credentials\CredentialProvider;
    
    $profile = 'default';
    $path = 'aws/credentials';
    $provider = CredentialProvider::ini($profile, $path); 
    $provider = CredentialProvider::memoize($provider);
    $eMessage = [];
    $SesClient = new SesClient([
        'credentials' => $provider,
        'version' => '2010-12-01',
        'region'  => 'eu-north-1',
    ]);

    if($_SERVER['REQUEST_METHOD'] == "GET") {
        if(isset($_REQUEST['email']) && isset($_REQUEST['name']) && isset($_REQUEST['subject']) && isset($_REQUEST['message'])) {

            $from = $_REQUEST['email'];
            $name = $_REQUEST['name'];
            $topic = $_REQUEST['topic'];
            $message = $_REQUEST['message'];

            // Replace sender@example.com with your "From" address.
            // This address must be verified with Amazon SES.
            $sender_email = 'senderEmail@gmail.com';

            // Replace these sample addresses with the addresses of your recipients. If
            // your account is still in the sandbox, these addresses must be verified.
            $recipient_emails = ['recipientEmail@outlook.com'];

            // Specify a configuration set. If you do not want to use a configuration
            // set, comment the following variable, and the
            // 'ConfigurationSetName' => $configuration_set argument below.
            $configuration_set = 'configset';

            $subject = 'Email From ' .$name. ' at ' . $from;
            $plaintext_body = 'This email was sent with Amazon SS using the AWS SDK for PHP.' ;
            $html_body =  '<h1>'.$topic.'</h1>'.
                        '<p>'.$message.'</p>';
            $char_set = 'UTF-8';

            try {
                $result = $SesClient->sendEmail([
                    'Destination' => [
                        'ToAddresses' => $recipient_emails,
                    ],
                    'ReplyToAddresses' => [$sender_email],
                    'Source' => $sender_email,
                    'Message' => [
                    'Body' => [
                        'Html' => [
                            'Charset' => $char_set,
                            'Data' => $html_body,
                        ],
                        'Text' => [
                            'Charset' => $char_set,
                            'Data' => $plaintext_body,
                        ],
                    ],
                    'Subject' => [
                        'Charset' => $char_set,
                        'Data' => $subject,
                    ],
                    ],
                    // If you aren't using a configuration set, comment or delete the
                    // following line
                    'ConfigurationSetName' => $configuration_set,
                ]);
                $eMessage ['Success'] = "Email sent!";
                $messageId = $result['MessageId'];
                echo("Email sent! Message ID: $messageId"."\n");
                } catch (AwsException $e) {
                    // output error message if fails
                    echo $e->getMessage();
                    $eMessage ['Failed'] = "GWGWGWJR";
                    
                };
                echo json_encode($eMessage);

        };

    }


?>

I had to add this if check if(isset($_REQUEST['email']) && isset($_REQUEST['name']) && isset($_REQUEST['subject']) && isset($_REQUEST['message'])) to remove this error : Undefined array key

AJAX in app.js: ajax function

    $(document).delegate("#mybtn", "click", function() {

        $.ajax({
            type: "GET",
            url: 'sendMail.php', 
            success: function (response) {
            console.log(response)
            }
        });

    });

Please can someone help me with this.

I also tried the javascript fetch function : javascript fetch function

    const form = document.querySelector('form')
    form.addEventListener('submit', event => {
      // prevent the form submit from refreshing the page
      // event.preventDefault()

      fetch('sendMail.php', {
        method: 'GET',
        headers: {
          'Accept': 'application/json',
        },
      })
      .then(response => response.json())
      .then(data => console.log(data));

Which returned this output : first error message And if I comment out the .then(response => response.json()) line, it returns this output : second error message



source https://stackoverflow.com/questions/77298081/why-does-ajax-return-empty-string-from-php-json-encode

No comments:

Post a Comment