Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Handling errors when saving to database or sending email #63

Closed
vipchristian opened this issue Dec 9, 2024 · 3 comments
Closed

Handling errors when saving to database or sending email #63

vipchristian opened this issue Dec 9, 2024 · 3 comments
Assignees
Labels
enhancement New feature or request user issue

Comments

@vipchristian
Copy link

Hello team,

I am currently using the SurveyJS WordPress plugin, and I noticed an issue that might impact users. When I tested by simulating a database connection loss (renaming the database), the form displayed a "Form completed" message, even though the data was not saved in the database. This could lead to confusion for users who rely on accurate data handling.

To address this, I modified my functions.php file to save the results to a different table and send the survey results via email. However, I also want to return a success or failure message to the user based on the following conditions:

If the survey data was saved successfully in the database.
If the email with the survey results was sent successfully.
The issue is that I don't know how to return these custom messages back to the SurveyJS form.

Could you please guide me on how to dynamically update the text displayed at the end of the form (success or error message) based on the success or failure of the database save, from within the functions.php file?

image

Thank you for your work on this fantastic plugin!

Here is a snippet of my current code in functions.php:

// Recursive function to convert array to string
function array_to_string($array)
{
    $result = '';
    foreach ($array as $key => $value) {
        if (is_array($value)) {
            $result .= '<strong>' . htmlspecialchars($key) . ':</strong> ' . array_to_string($value) . '<br>';
        } else {
            $result .= '<strong>' . htmlspecialchars($key) . ':</strong> ' . htmlspecialchars($value) . '<br>';
        }
    }
    return $result;
}


// SEND SURVEYJS PER MAIL
function surveyjs_save_result($SurveyId = null, $Json = null, $TableName = null)
{

    global $wpdb;
    $table_name = $wpdb->prefix . 'my_table'; // CHANGE TABLE NAME

    $survey_id = intval($SurveyId);
    $response_json = sanitize_text_field($Json);
    $uuid = generate_uuid();
    $submitted_at_var = current_time('mysql');
    $date = new DateTime($current_time);
    $submitted_at_var_eur = $date->format('d.m.Y \u\m H:i \U\h\r');

    $inserted_successfully = $wpdb->insert(
        $table_name,
        array(
            'survey_id' => $survey_id,
            'response_json' => $response_json,
            'submitted_at' => $submitted_at_var
        ),
        array('%s', '%d', '%s', '%s')
    );


    // VERIFY DATA
    if ($inserted_successfully) {
        // Retrieves the table ID
        $generated_id = $wpdb->insert_id;

        // Retrieve survey JSON data from the POST request
        $json_string = stripslashes($_POST['Json']);
        $array_data = json_decode($json_string, true);

        $email_customer = '';
        if (isset($array_data['Contact - E-Mail'])) {
            $email_customer = sanitize_email($array_data['Contact - E-Mail']); // CHANGE TO THE CUSTOMER EMAIL FIELD NAME
        }

        // Construct the email message with survey details
        $admin_email = '[email protected], [email protected]';
        $admin_plus_client_email = $admin_email . ', ' . $email_customer;
        $subject = 'MY SUBJECT';
        $message = '<html><body>';
        $message .= '<h2>WP Form:</h2>';
        $message .= '<p><strong>ID Number:</strong> ' . $generated_id . '</p>';
        $message .= '<p><strong>Date:</strong> ' . $submitted_at_var . '</p>';

        // Array to hold file attachments
        $attachments = array();

        // Add each question and its answer to the message
        foreach ($array_data as $question => $answer) {
            if (is_array($answer) && isset($answer[0]['content']) && strpos($answer[0]['content'], 'data:') === 0) {
                // Handle base64 file
                foreach ($answer as $file) {
                    $file_content = $file['content'];
                    $file_info = explode(',', $file_content);
                    $file_data = base64_decode($file_info[1]);
                    $file_name = sanitize_file_name($file['name']);

                    // Get the file extension
                    $file_extension = pathinfo($file_name, PATHINFO_EXTENSION);

                    // Create a temporary file with the correct extension
                    $file_path = wp_tempnam($file_name);
                    $file_path_with_extension = $file_path . '.' . $file_extension;

                    // Save the decoded file content to the temporary file with the correct extension
                    file_put_contents($file_path_with_extension, $file_data);

                    // Add the file path with extension to the attachments array
                    $attachments[] = $file_path_with_extension;

                    // Add file info to the email message
                    $message .= '<p><strong>' . htmlspecialchars($question) . ':</strong> ' . $file_name . ' (' . $file['type'] . ')</p>';
                }
            } else {
                // Use the recursive function to handle arrays
                $message .= '<p>' . array_to_string([$question => $answer]) . '</p>';
            }
        }

        $message .= '</body></html>';

        add_filter('wp_mail_from', function($email) {
            return '[email protected]';  // CHANGE SEND EMAIL
        });

        add_filter('wp_mail_from_name', function($name) {
            return 'My Name';  // CHANGE SEND NAME
        });

        // Send the email with attachments
        $headers = array('Content-Type: text/html; charset=UTF-8');
        $email_sent = wp_mail($admin_plus_client_email, $subject, $message, $headers, $attachments);

        if ($email_sent) {
            // If the email was sent successfully, display the confirmation ID and success message
            echo "<p>Your request has been sent. Your confirmation ID is: " . $generated_id . "</p>";
        } else {
            // If the email wasn't sent, display an error message
            echo "<p>There was a problem sending the confirmation email. Please try again.</p>";
        }
        
        // Clean up temporary files
        foreach ($attachments as $file_path) {
            unlink($file_path);
        }


    }
    /* INSERT ON TABLE - END */
}

// Hook the function to the 'wp_surveyjs_save_result' action
add_action('wp_surveyjs_save_result', 'surveyjs_save_result', 10, 3);
@JaneSjs JaneSjs added the question Further information is requested label Dec 30, 2024
@dmitry-kurmanov dmitry-kurmanov self-assigned this Dec 30, 2024
@JaneSjs JaneSjs added enhancement New feature or request user issue and removed question Further information is requested labels Jan 14, 2025
dmitry-kurmanov added a commit that referenced this issue Jan 28, 2025
@dmitry-kurmanov
Copy link
Member

@dmitry-kurmanov
Copy link
Member

I improved the plugin and added handling network issues to plugin's frontend part via this functionality of SurveJS.

I believe, that all you need now is to return HTTP error response from the surveyjs_save_result hook in functions.php. I am not a huge expert in Wordpress, but it seem that something like https://developer.wordpress.org/reference/functions/wp_send_json_error/ will work for this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request user issue
Projects
None yet
Development

No branches or pull requests

3 participants