I have a PHP script which uploads a CSV temporarily. One page reload the CSV data is got from $_FILES and converted to a JSON array.
I then iterate through the CSV Rows using $.each.
For each row I am doing an AJAX call to a PHP function which sets some order tracking data and sends an email.
Due to email restrictions I want to add a delay between each loop iteration. However i have attempted to do this using a set time out in the JavaScript which didn't work and also attempted to add a PHP sleep function before the email gets sent.
Neither work, the emails still get sent at the same time with no delay.
It would appear all the requests I am making regardless of the delays I am adding are being processed at once.
How can I ensure the email sending is delayed?
jQuery ($csv_rows is the CSV data which was just uploaded)
<script>
// Get CSV Rows into JSON array
var csvRows = '<?php echo json_encode( $csv_rows ); ?>';
var csvRows = ( jQuery.parseJSON( csvRows ) );
// Loop through each row
$.each( csvRows, function( key, value ) {
// Split row into array exploded by comma
row = value.toString().split( ',' );
// Get column values
order = row[0];
courier = row[1];
tracking = row[2];
// AJAX
var data = {
'action': 'shd_tracking_import',
'order': order,
'courier': courier,
'tracking': tracking,
};
// Do the ajax
$.ajax({
url: ajaxurl,
type: 'POST',
data: data,
success: function( response ) {
$( '#shd-import-results p' ).hide();
if( response !== '0' ) {
$( '#shd-import-results ul' ).append( response );
importedCount = parseInt( $( '#shd-import-progress span' ).text() );
$( '#shd-import-progress span' ).text( importedCount + 1 );
} else {
$( '<p>Error importing. Please ensure CSV meets requirements.</p>' ).appendTo( '#shd-import-results' );
}
}
});
});
</script>
PHP (this is the shd_tracking_import action referenced in AJAX)
if( isset( $_POST['order'] ) && isset( $_POST['courier'] ) && isset( $_POST['tracking'] ) ) {
// Delay (due to their Office 365 limits)
usleep( 4000000 ); // 4 Seconds (usleep used as sleep cannot contain fractions, usleep is microseconds, this was 2.5 seconds hence using usleep)
// My mailing function is here (which works just not delayed)
echo 'Done';
} else {
echo '0';
}
exit;