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

The issue of the window.open method malfunctioning on Internet Explorer 9

Struggling to make it work in IE9: Note: I forgot to mention that $variable is coming from a $_GET request based on a drop down menu selection. I am currently offline, <a href="#" onclick="window.open('https://domain.com/contact-form?chatq=& ...

How can I modify the fill color of a Cell when hovering over a Bar Chart in Recharts?

I have been rendering the chart in the following manner: <BarChart width={868} height={40} data={data} margin={{top:0, bottom: 10, left:0, right:0}} barSize={5}> <Tooltip labelStyle={{ textAlign: &apo ...

How does Facebook utilize ajax to refresh content on a user's side only upon request?

I'm curious about the inner workings of Facebook's newsfeed algorithm. I'm interested in creating a similar feature for my own project. Based on my observations, it seems that Facebook does not use a $jQuery refresh to update the newsfeed. ...

React doesn't have file upload configured to update the state

I am working on integrating a file upload button that sends data to an API. To ensure only the button triggers the upload dialog and not the input field, I have set it up this way. Issue: The File is not being saved to state, preventing me from using a ...

Determine the frequency of a specific letter in JavaScript by utilizing the indexOf method

Hey there! I'm currently working on a code to count the occurrences of a specific letter in a string using indexOf(). However, it seems like something may be off with my implementation. Can anyone point me in the right direction? Thanks! var string = ...

Enabling auto-expansion for textareas with every keystroke

Currently, I have implemented the following script: jQuery.each(jQuery('textarea[data-autoresize]'), function() { var offset = this.offsetHeight - this.clientHeight; var resizeTextarea = function(el) { jQuery(el).css('h ...

using conditional statements in an app.get() method in express js

app.get('/api/notes/:id', (req, res, next) => { fs.readFile(dataPath, 'utf-8', (err, data) => { if (err) { throw err; } const wholeData = JSON.parse(data); const objects = wholeData.notes; const inputId ...

Guide on how to use a tooltip for a switch component in Material-UI with React

I am attempting to incorporate a tooltip around an interactive MUI switch button that changes dynamically with user input. Here is the code snippet I have implemented so far: import * as React from 'react'; import { styled } from '@mui/mater ...

Tips for running a JavaScript function that is returned in an AJAX response

I am facing an issue with executing a function after a successful Ajax request in my jQuery code. Here is the snippet of my code: $.ajax({ type: "POST", url: "https://www.example.com/create_chat.php", data: dataString, beforeSe ...

Utilizing jQuery to attach events to dynamically generated elements

I have a scenario where I am uploading multiple images and inserting them into specific div elements. These divs should toggle a class when clicked. Should I include the part of code that adds the onclick event inside the ajax success function? Your help i ...

Is it optimal to count negative indexes in JavaScript arrays towards the total array length?

When working in JavaScript, I typically define an array like this: var arr = [1,2,3]; It's also possible to do something like: arr[-1] = 4; However, if I were to then set arr to undefined using: arr = undefined; I lose reference to the value at ...

Using the id from a foreach loop to trigger a jQuery modal

I would like to trigger the modal opening when the user clicks on the create asset button. After filling in the modal fields and clicking the save button, I also need to retrieve the asset group ID along with the modal data using a foreach loop and send it ...

Using Yii2, create a button with an onclick event that executes a JsExpression

I need to submit a form with an array of elements whose number is unknown. class DynamicForm extends Model { /** var string[] */ public elements[]; } In the view where the form submission takes place, I want to include a button that triggers a Ja ...

It seems that React JS with Redux may not be triggering a re-render

I am currently delving into the world of React JS with Redux and have what I believe is a straightforward query. Here's the code snippet I'm working with: import React from 'react'; import ReactDOM from 'react-dom'; import { ...

What causes the "node: bad option" error to occur when I include a custom flag in the nodejs command line within an Angular 9 application?

Seeking assistance with adding a custom flag to the npm start command in an Angular 9 project. The goal is to intercept proxy requests within the local server and manipulate data. However, encountering the "node: bad option" error consistently. Looking for ...

Using AJAX to submit a form and retrieve response data in Javascript

After successfully getting everything to post correctly, I encountered a problem with this script. It keeps loading the content into a new page. Could it be related to the way my php file returns it using "echo(json_encode($return_receipt));"? <s ...

Searching in Django utilizing jQuery keyup

When implementing a search functionality using the jQuery keyup function, I have set up my views to display the searched contacts in a template. Here is how my views are structured: def contacts_profile(request, search_id=None): contact = Invitation.o ...

Is there a method to ascertain the relative position of a point on a polygon?

Apologies in advance as I might have a hard time wording this question properly, so I'll start by explaining my objective. I'm currently working with JavaScript and Raphael. My goal is to save the position of a point in relation to the four cor ...

I'm torn between sticking to my original code using pure JavaScript with jQuery AJAX calls or scrapping all client-side scripts and starting fresh by rewriting everything in .NET only

My website, built using jQuery and .NET/C#, is nearly complete - about 90% ready to be published. Taking a moment to reassess, I've come to the realization that my code isn't as secure as I thought. In fact, it's quite vulnerable due to some ...

Comparing form submission with a button click to pass data using Ajax - success in one method but failure in the other

I am facing an issue with two pieces of jquery code in my Flask application. While one works perfectly, the other is not functioning as expected. Both the form and a button trigger the same function through ajax calls. Currently, for troubleshooting purpos ...