Issues with AJAX request to MySQL Database
-
I am having issues trying to create an AJAX request to the MySQL database hosted within my WordPress site. I have been implementing the PHP needed for the request through the XYZ PHP Snipped plugin, with the block implementing it being placed above my HTML/JS block. My compiled data is in the form of a JSON, as it it a variable amount of tables, which each contain a variable amount of rows. My AJAX request within the JS is as follows:
<script> var ajaxurl = '/wp-admin/admin-ajax.php'; if (confirm(
Are you sure you want to compile the data?\n\n${displayData}
)) { $.ajax({ type: 'POST', url: ajaxurl, data: { action: 'save_compiled_data', compiled_data: JSON.stringify(compiledData) }, success: function(response) { alert(response); }, error: function(error) { console.error(error); } }); } }) </script>And the PHP snippet is as follows:
<?php function save_compiled_data() { global $wpdb; // Check if compiled_data is set if (!isset($_POST['compiled_data'])) { error_log('No data received.'); wp_send_json_error('No data received.'); return; } // Retrieve the compiled data $compiled_data = $_POST['compiled_data']; error_log('Compiled Data: ' . $compiled_data); // Log the received data // Define the table name $table_name = $wpdb->prefix . 'compiled_data'; // Insert the data into the database $result = $wpdb->insert( $table_name, array( 'data' => maybe_serialize($compiled_data), 'timestamp' => current_time('mysql') ) ); // Check for database errors if ($result === false) { error_log('Database insert failed: ' . $wpdb->last_error); // Log any database error wp_send_json_error('Database insert failed: ' . $wpdb->last_error); } else { wp_send_json_success('Data saved successfully.'); } } add_action('wp_ajax_save_compiled_data', 'save_compiled_data');
Any help would be really appreciated, as I am not particularly experienced with WordPress as a whole.
Viewing 1 replies (of 1 total)
Viewing 1 replies (of 1 total)
- The topic ‘Issues with AJAX request to MySQL Database’ is closed to new replies.