Uncaught TypeError: URL.createObjectURL: Argument 1 is not valid for any of the 1-argument overloads

Viewed 1356

I'm trying to provide the administrators with a CSV-download on button click. The ajax call used to do so, gets triggered by a button in the Wordpress Admin-Dashboard. For the AJAX-part I mostly copied the code from Jonathan Amend's answer on this question. With a few adjustments and the serverside set up, I've been trying to download the csv-file. The download window doesn't pop up and the console says:

Uncaught TypeError: URL.createObjectURL: Argument 1 is not valid for any of the 1-argument overloads.

By Argument 1 it can only mean the blob which gets sent from the serverside. The documentation for URL.createObjectURL says:

object: A File, Blob, or MediaSource object to create an object URL for.

Putting that together it can only mean, that the blob data received from the server has incorrect format. When I log the typeof blob to console, it says "string".

This is part of the code used on the serverside:

    // Reading arguments, sanitize and validate data
    // Query database and store in $results (as assoc_array)
    $delimiter = ";";
    $file = fopen("php://output","w");

    $cols_printed = false;
    foreach($results as $row) {

        if (!$cols_printed){

            // FPUT 1: Write Aliases of query to file once
            fputcsv($file, array_keys($row), $delimiter);
            $cols_printed = true;
        }

        // FPUT 2: Write values to file
        fputcsv($file, array_values($row), $delimiter);
    }
    // Close file, sending headers

If I comment out FPUT 2, then the csv can be downloaded (of course with only the column names and no data). The typeof blob changes to "object". I tried converting the whole blob explicitely before calling the URL.createObjectURL in JS, letting me successfully download the file without error, but the actual rows were nowhere to be seen. So what makes the 2nd FPUT diffrent?

EDIT 1: I've done some further testing. If I take the FPUT1 out of the if-statement, it throws the same error. Within the .php script there are no other var_dump, print_r or echo who could produce this output. Even when putting an echo "test"; at the very end of this file, the two newlines come still after. I could fix this by moving all code into the main plugin.php file. However, the client still thinks of the response as a string, despite changing my SELECTto a single INT column.

0 Answers
Related