Ajax-Request in a Callback-Function (with loop)

134 views Asked by At

My AJAX request always sends the same data. How can I use the convertImgToBase64 function without this issue?

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

request.php

<?php
    echo $_POST['file'];    //output always "2.jpeg" 
?>
2

There are 2 answers

0
dazzafact On

Now i got it. Only problem now is the base64 encoding returning String, which doesnt return the Value.

        $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);
                        settings.data.img =$base64;
                        settings.data.url= $file;
                      },
                      url: '/request.php?imagePost=1',
                      data: {img:'',url:$file},
                      processData: 1,
                      cache: 1,
                      //uploadProgress:progress, 
                      xhr: function() { },
                      success: function(){}
                    });
            }
0
Alexey Rytikov On

You send

     data: $file

but you want to send

    data: base64Img

that is first argument from callback function

convertImgToBase64($url, function(base64Img){