skip to Main Content

I have this javascript code which is supposed to create a screenshot of the image-container div and send it to a new php script:

html2canvas(image-container).then(function (canvas) {
    canvas.toBlob(function (blob) {
        jQuery.ajax({
            url:"//domain.com/wp-admin/admin-ajax.php",
            type: "POST",
            data: {action: "addblobtodb", image: blob},
            success: function(id) {
                console.log("Succesfully inserted into DB: " + id);
            }
        });

The php code that is called in the admin-ajax.php file is shown below. It tries to insert the image blob in the test_images table, which I created myself. It is asimple MySql table with an ID and image_data:

function add_poster_to_db() {
    global $wpdb;
    $image = $_POST['image'];
    ob_start();

    // Insert een nieuwe rij aan de test_poster_images db
    $wpdb->insert('test_images', array(
        'image_data' => $image,
    ));
    $db_id = $wpdb->insert_id;

    wp_send_json( $db_id );

    die();
}

When calling this javascript code, the following errors are shown:
error

How can I insert the blob in the WordPress table?

2

Answers


  1. Aren’t you meant to be passing a blob-URL for the image instead of just blob-data?

    Because it doesn’t look like you’re converting the blob to a URL with this…

    canvas.toBlob(function (blob){
    
      jQuery.ajax({
    
        url:"//domain.com/wp-admin/admin-ajax.php",
        type: "POST",
        data: {action: "addblobtodb", image: blob},
        success: function(id) {console.log("Succesfully inserted into DB: " + id);
    
       }
    
    });
    

    So I would try this…

    canvas.toBlob((blob)=>{
    
     let Url=URL.createObjectURL(blob);
    
       jQuery.ajax({
    
        url:"//domain.com/wp-admin/admin-ajax.php",
    
        type: "POST",
    
        data: {action: "addblobtodb", image: Url},    // <-- Image blob url passed here
    
        success: function(id) {console.log("Succesfully inserted into DB: " + id);}
    
       });
    
     },'image/png',1); // <--- specify the type & quality of image here
    
    Login or Signup to reply.
  2. OK then, let the DB have the blob in raw format…

    canvas.toBlob((blob)=>{
    
       jQuery.ajax({
    
        url:"//domain.com/wp-admin/admin-ajax.php",
    
        type: "POST",
    
        data: {action: "addblobtodb", image: blob},
    
        success: function(id) {console.log("Succesfully inserted into DB: " + id);}
    
       });
    
     },'image/png',1); // <--- specify the type & quality of image here
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search