0

I am storing all child Images src in Array ,i have created sample template and in array loop i am changing src and them want to convert them in image . but only last 4 array value is saved as an image . is this ajax issue or what??

HTML code:

<div id="present_sample" style="display:">
<img id="one" src="img/Tulips.jpg" /> 
<img id="two" class="alignright" src="img/Tulips.jpg" /> 
<br/>
<img id="three" src="img/Tulips.jpg" /> 
<img id="four" class="alignright" src="img/Tulips.jpg" /> 

JQuery code :

 $('#convert').click(function()
 {
 var images = $('#links a').children('img').map(function(){
 return $(this).attr('src') }).get();
    console.log(images);

    //$('#gallery_pic').append(images);
     var side=1;
      var data;
     for (i = 0; i < images.length; i++) {


        console.log('Top i is '+i);
        console.log('Group*******');
        console.log(i+','+images[i]);
        $('#one').attr("src", images[i++]);
        console.log(i+','+images[i]);
        $('#two').attr("src", images[i++]);
        console.log(i+','+images[i]);
        $('#three').attr("src", images[i++]);
        console.log(i+','+images[i]);
        $('#four').attr("src", images[i]);
        console.log('Group Ends');
        html2canvas([document.getElementById('present_sample')], {
    onrendered: function (canvas) {
        $('canvas').html(canvas);
        var data = canvas.toDataURL('image/png');
        // AJAX call to send `data` to a PHP file that creates an image from the dataURI string and saves it to a directory on the server

        $.ajax({
          type: "POST",
          url: 'download.php',
          data: {
          image: data},
           success:function(data)   { 
          alert('Ajax return is'+data); 

            }
            });

        }

       });

});

PHP code :

<?php 
if ( isset($_POST["image"]) && !empty($_POST["image"]) ) { 

    // get the image data
    $data = $_POST['image'];

    list($type, $data) = explode(';', $data);
    list(, $data)      = explode(',', $data);
    $data = base64_decode($data);

    //Image name
    //$filename ="image". md5(uniqid()) . '.png';
    $filename ="image". md5(uniqid()) . '.jpg';

    $file = "download/".$filename;

  // decode the image data and save it to file
    file_put_contents($file,$data);

    echo "successfully downloaded in folder";


}
?>  
anam
  • 3,905
  • 16
  • 45
  • 85

1 Answers1

0

you can very well avoid the problem by using only one ajax request, i.e. , make your ajax call after the for loop ends, till then append all the data to your data variable, and at the end of the loop , make only one ajax call.

NOTE: this issue with ajax calls inside for loops has been discussed in many threads, take a look if it helps:

http://www.ravenglass.com/blog/index.cfm/2013/3/5/FOR-Loops-Overwriting-Ajax-Responses-and-how-to-fix

Ajax call within jquery each loop

jQuery AJAX solution inside each() loop

Community
  • 1
  • 1
gaurav5430
  • 12,934
  • 6
  • 54
  • 111