Creating a PDF document with multiple pages using a PHP loop, integrating with AJAX, and utilizing the m

Looking for assistance with a plugin development project involving PDF generation using AJAX. The challenge lies in generating multiple PDFs for each user within a loop.

The goal is to create PDFs with multiple pages for individual users. If that's not feasible, then separate PDFs per user will suffice.

The current code seems to be only producing one page for the first user in the loop, followed by a blank page and halting the process.

Check out the mPDF Library for more information.

Data

Array
(
    [group_name] => Food Lovers
    [group_admin] => John Doe
    [identifier] => AtR4deAVgU4Ensi1_1ac2b33a4df7c5f0cf148d6232074352
    [group_order_number] => 1615962332298
    [start_date] => 2021-03-20
    [group_user_ids] => Array
        (
            [0] => 63
            [1] => 73
            [2] => 83
        )

    [63] => Array
        (
            [products] => Array
                (
                    [0] => stdClass Object
                        (
                            [id] => 100
                            [order_number] => 2021031729863
                            [group_order_number] => 1615962332298
                            [product] => 100
                            [product_option] => 
                            [qty] => 6
                            [group_id...

Callback Function

function gs_group_users_order_pdf_generator_ajax()
{
    // Implementation details for handling AJAX requests

    ...
}

// Attaching the function to AJAX hooks
add_action('wp_ajax_gs_group_users_order_pdf_generator', 'gs_group_users_order_pdf_generator_ajax');
add_action('wp_ajax_nopriv_gs_group_users_order_pdf_generator', 'gs_group_users_order_pdf_generator_ajax');

Javascript

Calling function

// Initiating PDF generation on click event
$(document).on('click', '.gs-guo-pdf-orders', function () {
    if (confirm('Are you sure you want to generate group users order PDFs?')) {
        ajax_process.call(this, '', 'gs_group_users_order_pdf_generator', 'fa-window-close');
    }
});

Complete Javascript

(function ($) {
    $(function () {

        ...

    });
})(jQuery);

HTML for Button

<button class="gs-guo-pdf-orders btn btn-sm btn-outline-info ml-3" type="button" title="Generate Group Users Order PDFs" 
data-ordernum="1615962332298" data-gid="298" data-gadmin="72" data-identifier="AtR4deAVgU4Ensi1_1ac2b33a4df7c5f0cf148d6232074352">
<i class="fas fa-copy"></i></button>

Answer №1

I'm not certain if this may be causing the issue. However, in each iteration of the foreach loop, you are overwriting the $markup variable with the following line:

$markup = '<div class="info">';

It is advisable to initialize $markup as empty before entering the foreach loop and then concatenate strings within the loop.

$markup = ''; //<-- Start with this

// Place headers outside the loop for better performance
header('Content-type: application/pdf');
header('Content-Disposition: inline; filename="' . $filename . '"');
header('Content-Transfer-Encoding: binary');
header('Accept-Ranges: bytes');

foreach ($group_user_ids as $group_user_id) {

    $user_data = get_userdata($group_user_id);

    // create pdf
    $markup .= '<div class="info">'; //<-- Append here instead of resetting
    $markup .= '<p><strong>' . __('User', 'group-shop') . ':</strong> ' . $user_data->display_name . '</p>';
    $markup .= '<p><strong>Email:</strong> ' . $user_data->user_email . '</p>';
    $markup .= '<p><strong>Admin:</strong> ' . $data[ 'group_admin' ] . '</p>';
    $markup .= '<p><strong>Group:</strong> ' . $data[ 'group_name' ] . '</p>';
    $markup .= '</div>';

    $markup .= '<table class="table">';
        // insert table content here
    $markup .= '</table>';

    // end of order table

    $markup .= '<pagebreak />';  //add page break

} // $group_user_ids end

$mpdf->WriteHTML($markup, HTMLParserMode::HTML_BODY, TRUE);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing JavaScript For Loops for Code Repetition

Apologies for the ambiguous question title - struggling to articulate this properly. Essentially, I have some JavaScript code that I am looking to streamline by using a for loop. $('.q1').keyup(function () { if ($.inArray($(this).val().toLo ...

Changing the text color in a React Native TouchableHighlight component

How does TouchableHighlight change the text color when tapped? I have already configured the backgroundColor using underLayColor. Here is my updated code snippet: <TouchableHighlight style={{ borderRadius: 5}} ...

Create a new visual masterpiece using Canvas by repurposing an

I am currently working on the following code snippet; export default async function draw(elRef : RefObject<HTMLCanvasElement>, tileData : TileProps) { const canvas = elRef.current!; const ctx = canvas.getContext('2d')!; ctx.clearRect( ...

What is the best way to highlight a specific city on a map by placing a circle around it?

I am currently developing a project that involves creating a circle around the location of an item on a Google Map. In the code snippet below, when the show tab is clicked, it should display a circle around the item's location on the map: <div cla ...

When sending a single apostrophe as a parameter in an AJAX post request, it will result in an error

JavaScript Code: var name = jQuery("#name1").val(); jQuery.ajax({ url: siteUrl + 'search/ind', type: 'POST', data: { name: name, }, success: function(data) { jQuery('#input').val(''); } } ...

When the user clicks on the login text field or password field, any existing text will

Currently, I am working on the login section of my website and I would like to implement a similar effect to Twitter's login form, where the Username and Password values disappear when the Textfield and Password field are in focus. I have attempted to ...

Running a JavaScript animation within an Electron environment

My curiosity lies in developing man-machine interfaces using Electron. Currently, I am experimenting with a Star Trek life signs monitor demo. I came across this code that can be easily customized to create vertical and horizontal movements: http://jsfiddl ...

Using query parameters in Angular to interact with APIs

One scenario involves a child component passing form field data to a parent component after a button press. The challenge arises when needing to pass these fields as query parameters to an API endpoint API GET /valuation/, where approximately 20 optional p ...

Every time I attempt to load the table, I encounter an error

Encountering errors when attempting to load the table: 'Uncaught ReferenceError: usersArray is not defined at loadUsers (trgames.js:20:17) at trgames.js:22:1' and 'Uncaught TypeError: Cannot set properties of null (setting ...

The session in Express.js is not retained across different domains

I am currently developing a third-party application that will be utilized across multiple domains. My main goal is to manage a session per user who uses the app, which led me to implement the express-session module for this purpose. However, I encountered ...

JSON data not being returned by Ajax

I am attempting to execute a basic Ajax request that communicates with a groovy script and retrieves the JSON string generated by the script. Here is my Ajax: var urlPath = "connections.groovy"; $.ajax({ url : urlPath, type: 'GET', ...

Retrieving an HTML element that has been added through DOM manipulation

After successfully creating a Jquery function that inserts a 'save button' into the page when a specific button is clicked, I encountered an issue with another function meant to be activated when the save button is clicked. The first function see ...

Click to start viewing the video

I'm attempting to have a video play when clicked, either on the video itself or around the video. There are multiple videos on the page and I've tried various solutions including the script below which didn't work. $('video'). ...

Trouble with triggering events from Datatable buttons

Below is the code snippet I am currently using for my DataTable : var oTable12= $('#example').DataTable({ "aaData": tableData, "aLengthMenu": [[5, 10, 20, -1], [5, 10, 20, "All"]], "iDisplayLength": 5, "aoColumnDefs ...

Testing NestJS Global ModulesExplore how to efficiently use NestJS global

Is it possible to seamlessly include all @Global modules into a TestModule without the need to manually import them like in the main application? Until now, I've had to remember to add each global module to the list of imports for my test: await Tes ...

What is the solution to the error message stating that <tr> cannot be a child of <div>?

displayTodos() { return this.state.todos.map(function(item, index){ return <div todo={item} key = {index}>; <tr> <td>{item.todo_description}</td> <td>{item.todo_responsible}</td> ...

KnockoutJS - Using containerless control flow binding with predefined values

Inside a select control, I am using ko:foreach instead of the usual bindings. Everything is working perfectly, except that the initial value for "specialProperty" is set to unknown even when the select control is set to Option 1. It behaves as expected o ...

Attempting to modify read-only properties is prohibited in strict mode within the context of [background: url({{XXX}}) no-repeat center center

I encountered an issue in Edge, but everything works fine in Chrome. I can't figure out what's causing the problem... <div class="container-fluid project_img" style="background: url({{_project.images.web}}) no-repeat center center;"> ...

Ways to resolve the issue of the experimental syntax 'jsx' not being enabled

I encountered an issue while trying to implement react-fancybox and received an error. To resolve the error, I executed the following commands: npm install --save-dev @babel/preset-react, npm install --save-dev @babel/plugin-syntax-jsx, and npm install -- ...

Exploring the optimal SEO strategies for website creation using PHP programming

In my recent work, I've delved into the world of SEO and it's been quite an eye-opening experience. Admittedly, I've always been a bit skeptical about SEO, thinking it was just buzz-word nonsense with no real substance. I've always beli ...