title: JPG (Binary data) download as AJAX response
body: <p>I have a page where a user can download an image in the format he ask, the request is sent to a PHP script that produce the image and ... I want to serve to the user.
  This is the JQUERY code sourced here on StackOverflow</p>
  
  <pre><code>                    $('[name ="download_img_ajax"]').click(function(e){
                          e.preventDefault()
                          var element = this
                          var formdata = new FormData(element.closest(".form_downIMG"))
                          formdata.append('download_img_ajax','true')
                          $(this).next("span.down_response").html('Preparazione file in corso...'),
                          $('.emailadr').hide(),
                            $.ajax({
                                 type: 'POST',
                                 url: '$target_post',
                                 data:  formdata,
                                 cache: false,
                                 contentType: false,
                                 processData: false,
                              success: function(tornato) {
                                const blob = new Blob([tornato], {type: 'image/jpeg'});
                                const downloadUrl = URL.createObjectURL(blob);
                                const a = document.createElement("a");
                                a.href = downloadUrl;
                                a.download = "file.jpg";
                                document.body.appendChild(a);
                                a.click();
                                },
                          })
                        })
  </code></pre>
  
  <p>The PHP script generate the file as a tmp file ($img), but I don't understand how return it as a correct AJAX response.</p>
  
  <p><code>echo fread($img,filesize($img_path));</code></p>
  
  <p>isn't working (the file isn't recognized as JPG file) even if the size is correct.</p>
  
  <p>In a normal form I return the file this way:</p>
  
  <pre><code>      header('Content-Transfer-Encoding: binary');  // For Gecko browsers mainly
        header('Accept-Ranges: bytes');  // For download resume
        header('Content-Length: ' . filesize($img_path));  // File size
        header('Content-Encoding: none');
        header('Content-Type: image/jpeg');  // Change this mime type if the file is not PDF
        header('Content-Disposition: attachment; filename=' . $imgID);  // Make the browser display the Save As dialog
        readfile($img_path);
      fclose($img);
  </code></pre>
  
  <p>PS: In JQ I use next, closest, etc. because I have many forms in the same dynamically generated by PHP.</p>
  
  <p>I will use this kind of download only for file of ~700KB, leaving the bigger file on the old method of a submit form with target="_blank" and readfile in the PHP. Is safe?</p>
  
  <p>If I want manage also error (example the PHP script can't serve the file) how I can handle it?</p>
  
  <p>Thanks.</p>