jQuery Ajax: set dataUrl beforeSend

247 views Asked by At

This AJAX request doesn't return any 64-Value-String in the beforeSend handler like it should. But as alert in the function it does! I don't know how to do this async. What is the Issue?

$imageMaps[0] = '1.jpeg';
$imageMaps[1] = '2.jpeg';

for (var k in $imageMaps) {
    $file = $imageMaps[k];
    $.ajax({
        type: "POST",
        async: 0,
        beforeSend: function (xhr, settings) {
            $base64 = convertImgToBase64($file);
            alert($base64)
            settings.data.img = $base64;
            settings.data.url = $file;
        },
        url: '/request.php?imagePost=1',
        data: {
            img: '',
            url: $file
        },
        success: function () {}
    });
}

function convertImgToBase64(url) {
    var img = new Image();
    img.src = url;
    img.onload = function () {
        var canvas = document.createElement("canvas");
        canvas.width = this.width;
        canvas.height = this.height;
        var ctx = canvas.getContext("2d");
        ctx.drawImage(this, 0, 0);
        dataurl = canvas.toDataURL("image/png");
        alert(dataurl)
        return dataurl;
    }
}
2

There are 2 answers

0
dazzafact On

Here is the Solution:

    $imageMaps[0] = '1.jpeg';
    $imageMaps[1] = '2.jpeg';

    for (var k in $imageMaps) {
        $file=$imageMaps[k];
         convertImgToBase64($url, function($base64Img,$url2){
                     $.ajax({
                      type: "POST", 
                      async : 1,
                      url: '/request.php?imagePost=1',
                      data: {img:$base64Img,url:$url2},
                      xhr: function() {},
                      success: function(){}
                        });
            }) 
    }

function convertImgToBase64(url, callback, outputFormat){
var img = new Image();
img.crossOrigin = 'Anonymous';
img.onload = function(){
    var canvas = document.createElement('CANVAS');
    var ctx = canvas.getContext('2d');
    canvas.height = this.height;
    canvas.width = this.width;
    ctx.drawImage(this,0,0);
    var dataURL = canvas.toDataURL(outputFormat || 'image/png');
    callback(dataURL,url);
    canvas = null; 
};
img.src = url;

}

0
iamawebgeek On

You are actually returning nothing from that func. Try to do like this:

function convertImgToBase64(url) {
    var img = new Image();
    img.src = url;
    return img.onload = function () {
        var canvas = document.createElement("canvas");
        canvas.width = this.width;
        canvas.height = this.height;
        var ctx = canvas.getContext("2d");
        ctx.drawImage(this, 0, 0);
        dataurl = canvas.toDataURL("image/png");
        alert(dataurl)
        return dataurl;
    }
}

I may be wrong, so if does not work, do comment it.