Ecommerce Shopify WordPress Discussion

Custom plugin AJAX request results in error HTTP 400 (Bad Request)

Basically I am getting this error: Failed to load resource: responded with a status of 400 (Bad Request) I am developing a custom plugin which is a csv file upload script. I used the following script as a demo plugin that was working as expected. With the final version of the plugin I am getting this error, but I can't figure out why it's happening. Any help? if (!defined('ABSPATH')) { exit; } class BulkEmail { private $adminemail; function __construct() { //new BulkemailImport(); $this->adminemail = get_bloginfo('admin_email'); $this->bulk_email_send(); add_action('wp_ajax_email_csv_import', [$this,'email_csv_import']); add_action('wp_ajax_nopriv_email_csv_import', [$this, 'email_csv_import']); } public function email_csv_import() { global $wpdb; $fileMimes = array( 'text/x-comma-separated-values', 'text/comma-separated-values', 'application/octet-stream', 'application/vnd.ms-excel', 'application/x-csv', 'text/x-csv', 'text/csv', 'application/csv', 'application/excel', 'application/vnd.msexcel', 'text/plain' ); // Validate selected file is a CSV file or not if (!empty($_FILES['csvfile']['name']) && in_array($_FILES['csvfile']['type'], $fileMimes)) { // Open uploaded CSV file with read-only mode $csvFile = fopen($_FILES['csvfile']['tmp_name'], 'r'); // Skip the first line fgetcsv($csvFile); // Parse data from CSV file line by line while (($getData = fgetcsv($csvFile, 10000, ",")) !== FALSE) { // Get row data $email = $getData[0]; // If user already exists in the database with the same email $query = $wpdb->prepare("SELECT id FROM {$wpdb->prefix}orgsmtp_blukemail WHERE email = %s", $email); $check = $wpdb->get_results($query); if ($check) { $wpdb->update( "{$wpdb->prefix}orgsmtp_blukemail", array('email' => $email), array('email' => $email) ); } else { $wpdb->insert( "{$wpdb->prefix}orgsmtp_blukemail", array('email' => $email) ); } } // Close opened CSV file fclose($csvFile); exit; } else { echo "Please select a valid file"; } } public function orange_smtp_enqueue_assets() { $screen = get_current_screen(); wp_enqueue_script('jquery'); wp_enqueue_script('orange-js', plugin_dir_url(__FILE__) . 'assets/js/custom.js', array('jquery'), time(), true); wp_localize_script('orange-js', 'ajax_object', array( 'ajax_url' => admin_url('admin-ajax.php'), //'nonce' => wp_create_nonce('my_csv_upload_nonce'), )); wp_enqueue_script('datatables-js', plugin_dir_url(__FILE__) . 'assets/js/datatables.min.js', array('jquery'), time(), true); } } jquery Ajax script let ajax_url = ajax_object.ajax_url; jQuery(document).ready(($) =\> { jQuery('#uploadcsv').on("click", (e) =\> { e.preventDefault(); const fileInput = document.getElementById('csvfile'); const file = fileInput.files\[0\]; if (file) { const formData = new FormData(); formData.append('action', 'email_csv_import'); formData.append('nonce', ajax_object.nonce); formData.append('csvfile', file); const reader = new FileReader(); reader.onload = (e) => { const contents = e.target.result; // Split CSV content by lines const lines = contents.split(/\r\n|\n/); // Validate each email address const validEmails = []; const invalidEmails = []; // Email validity check for (let i = 0; i < lines.length; i++) { const email = lines[i].trim(); if (isValidEmail(email)) { validEmails.push(email); } else { invalidEmails.push(email); } } if (invalidEmails.length > 0) { alert('Invalid email addresses found: ' + invalidEmails.join(', ')); } // Only proceed if there are valid email addresses if (validEmails.length > 0) { jQuery.ajax({ url: ajaxurl, // Use ajaxurl global variable in WordPress type: 'POST', data: formData, processData: false, contentType: false, success: (data) => { console.log('submit'); // Handle success }, error: (xhr, status, error) => { console.log(xhr.responseText); } }); } else { console.log('No valid email addresses found'); } }; reader.readAsText(file); } else { console.log('No file selected'); } }); // Function to validate email address function isValidEmail(email) { //return email !== ''; var email = email.replace(/\s/g, ''); var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/; if (!filter.test(email)) { return false } return true } });
TurboCommerce make the better internet purchasing globaly

Turbo Multi-language Translator

Make the better internet purchasing globaly

Turbosify SEO Speed Booster

5.0 (7) Free plan available
Get better conversions by improving store loading speed Installed

Turbo Multi-language Chat - AI Customer service in one hand

TurboCommerce make the better internet purchasing globaly
Our products

The help you need, when you need it

App by Turbo Engine

3 apps • 5.0 average rating

Turbosify Speed Booster

5.0 (7)
Get better conversions by optimizing shopify store Google page speed Installed

Turbosify Translator for Wordpress Woocommerce

5.0 (74) Free Wordpress Woocommerce Plugin
Translate your wordpress website to multiple language within 1 click, no configuration needed, no No technical required

Grow your business here

Whether you want to sell products down the street or around the world, we have all the tools you need.