I have a created button in my post.php
screen where you can generate and download a PDF using the fpdf
libary. I've got this working by using a function and then firing it if the $_POST isset. I'm then calling this on the admin_init
like so:
add_action( 'admin_init', array($this, 'my_function_with_wc_functions'));
function my_function_with_wc_functions() {
if ( isset( $_POST['generate_posts_pdf'] ) ) {
$post_id = $_POST['pageid'];
if ( isset( $_POST['_close_competition_early'] ) ) {
$complete = false;
}
else {
$complete = true;
}
$this->output_pdf( $post_id, $complete );
}
<form method="post" id="as-fdpf-form">
<input type="hidden" name="pageid" value="<?php echo $post->ID; ?>">
<button class="button button-primary" type="submit" name="generate_posts_pdf" value="generate">Generate PDF from Competiion Entries</button>
<button class="button button-primary" type="submit" name="generate_posts_csv" value="generate">Generate CSV from Competiion Entries</button>
</form>
function output_pdf( $id, $complete ) {
global $wpdb;
if ( $complete ) {
$table = "tickets";
}
else {
$table = "tickets_regenerated";
}
if ( $wpdb->get_var( $wpdb->prepare( 'SELECT * FROM '.$wpdb->prefix.$table.' WHERE lottery_id= %d AND used = %d', $id, 1 ) ) ) {
$log = $wpdb->get_results( $wpdb->prepare( 'SELECT * FROM '.$wpdb->prefix.$table.' WHERE lottery_id=%d AND used = %d', $id, 1 ) );
global $pdf;
$title_line_height = 10;
$content_line_height = 8;
$pdf->AddPage('L');
$pdf->SetFont( 'Arial', '', 42 );
$header = array('Order Number', 'Full name (Billing)', 'Draw #');
$pdf->SetFont( 'Arial', 'B', 8);
$pdf->Cell(20,5,'Order Number', 1);
$pdf->Cell(35,5, 'Full name (billing)', 1);
$pdf->Cell(25,5, 'Draw #' ,1);
$pdf->Ln();
$i = 0;
foreach( $log as $row ) {
if($i%2 == 0) :
$pdf->setFillColor(255,255,255);
else :
$pdf->setFillColor(230,230,230);
endif;
$pdf->SetFont( 'Arial', '', 8 );
$pdf->Cell(20,5,$row->order_id, 1, 0, 'C', true);
$pdf->Cell(35,5, $row->full_name,1, 0, 'C', true);
$pdf->Cell(25,5,$row->ticket_number,1, 0, 'C', true);
$pdf->Ln();
$i++;
}
}
$upload = wp_upload_dir();
$upload_dir = $upload['basedir'];
$upload_dir = $upload_dir . '/entry-lists/'.$id;
if (! is_dir($upload_dir)) {
mkdir( $upload_dir, 0700 );
}
$pdf->Output('D', $id.'.pdf', true);
$pdf->Output('F', $upload_dir.'/'.$id.'.pdf', true);
exit;
}
The problem I have is that once the PDF has downloaded, the page automatically fires the admin-ajax.php
and creates an autosave which causes the update button to be disabled.
I've tried adding event.preventDefault();
to the button this stops the button from working.
Is there a way I can stop the admin-ajax.php from firing after I've clicked the button?