skip to Main Content

I need an emailing system for my react app(typescript).
Im making it as a plugin for my wordpress page, so i wanted to incorporate it with the wp_email() function.
The problem is i don’t really know much about php, an although the data is sent, the response i receive is not a valid json.

I tried this code on my react app

...
const sendEmail = async () => {
        try {
            const response = await fetch(
                '/wp-json/custom/v1/send-email',
                {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        'to': emailData.to,
                        'subject': emailData.subject,
                        'message': emailData.message
                    }),
                }
            );
             const data = await response.json();

             
            if (data.message === 'Email sent successfully.') {
                alert('Email sent successfully.');
            } else {
                alert('Email sending failed.');
            }
        } catch (error) {
            console.error('Error sending email:', error);
        }
    };
...

and this code for the .php file:

add_action('rest_api_init', 'register_custom_email_endpoint');

function register_custom_email_endpoint() {
    register_rest_route('custom/v1', '/send-email', array(
        'methods'  => 'POST',
        'callback' => 'send_custom_email',
    ));
}

function send_custom_email($request) {
    $to      = $request->get_param('to');
    $subject = $request->get_param('subject');
    $message = $request->get_param('message');
   // $headers = 'Content-Type: text/html';

    $result = wp_mail($to, $subject, $message);

    if ($result) {
        return array('message' => 'Email sent successfully.');
    } else {
        return array('message' => 'Email sending failed.');
    }
}

the error im getting is
Error sending email: SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

2

Answers


  1. It looks like the issue is with the response from your WordPress PHP endpoint not returning valid JSON. The error message you provided, "SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data," indicates that the response is not in a valid JSON format.

    To fix this issue, you should ensure that your PHP endpoint returns a valid JSON response. Here’s how you can modify your PHP code:

    add_action('rest_api_init', 'register_custom_email_endpoint');
    
    function register_custom_email_endpoint() {
        register_rest_route('custom/v1', '/send-email', array(
            'methods'  => 'POST',
            'callback' => 'send_custom_email',
        ));
    }
    
    function send_custom_email($request) {
        $to      = $request->get_param('to');
        $subject = $request->get_param('subject');
        $message = $request->get_param('message');
       // $headers = 'Content-Type: text/html';
    
        $result = wp_mail($to, $subject, $message);
    
        if ($result) {
            $response = array('message' => 'Email sent successfully.');
        } else {
            $response = array('message' => 'Email sending failed.');
        }
    
        // Send the response as JSON
        return rest_ensure_response($response);
    }
    

    In the modified code, I’ve wrapped your response array with rest_ensure_response to ensure that it is sent as a valid JSON response. This should resolve the "SyntaxError" issue you were encountering in your React app. Now, your React code should be able to parse the JSON response correctly.

    Login or Signup to reply.
  2. If you’re experiencing issues with the entire page being replicated in the response and suspect that it’s a problem with the REST API connection, you can follow these steps to troubleshoot the issue:

    -Check the REST API URL: Ensure that the URL you are using in your React app to make the POST request matches the REST API endpoint you registered in your WordPress plugin. In your case, the URL should be /wp-json/custom/v1/send-email.

    -Verify the WordPress REST API: Make sure that the WordPress REST API is enabled and functioning correctly. You can do this by visiting the REST API endpoints directly in your browser. For example, navigate to /wp-json/custom/v1/send-email in your browser and see if it returns the expected JSON response.

    -Check for Errors: In your PHP code, you can add error handling to log any potential errors that occur during the execution of your send_custom_email function. This can help you identify issues in your PHP code.

    function send_custom_email($request) {
        try {
            $to      = $request->get_param('to');
            $subject = $request->get_param('subject');
            $message = $request->get_param('message');
            // $headers = 'Content-Type: text/html';
    
            $result = wp_mail($to, $subject, $message);
    
            if ($result) {
                $response = array('message' => 'Email sent successfully.');
            } else {
                $response = array('message' => 'Email sending failed.');
            }
    
            // Send the response as JSON
            return rest_ensure_response($response);
        } catch (Exception $e) {
            error_log('Error sending email: ' . $e->getMessage());
            return rest_ensure_response(array('message' => 'An error occurred while sending the email.'));
        }
    }
    

    -Check Console for Errors: In your browser’s developer console, check for any errors or warnings that might be related to the API request. This can provide additional insights into what’s going wrong.

    -Test with a REST Client: You can use a tool like Postman or Insomnia to test your WordPress REST API endpoint separately from your React app. This can help you verify that the API is working as expected.

    By following these steps and carefully inspecting the responses and any error messages, you should be able to identify and resolve the issue with the connection to the REST API in your WordPress plugin.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search