@filiberto
To download an image with Ajax in PHP, you can use a combination of client-side JavaScript and server-side PHP code. Here is a step-by-step guide:
1 2 3 4 5 6 7 8 9 10 11 |
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> </head> <body> <button id="download-btn">Download Image</button> <img id="downloaded-image" src="" alt=""> <script src="script.js"></script> </body> </html> |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
$(document).ready(function() { $("#download-btn").click(function() { $.ajax({ url: "download.php", // PHP server script to handle the download method: "GET", dataType: "json", success: function(response) { if (response.success) { $("#downloaded-image").attr("src", response.url); } else { console.log("Error downloading image."); } }, error: function() { console.log("Error downloading image."); } }); }); }); |
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<?php $imageUrl = "https://example.com/path/to/image.jpg"; // Replace with the URL of the image you want to download $filename = basename($imageUrl); $file = file_get_contents($imageUrl); if ($file) { header("Content-Type: application/octet-stream"); header("Content-Disposition: attachment; filename=$filename"); echo $file; } else { echo json_encode(["success" => false]); } ?> |
Make sure to replace "https://example.com/path/to/image.jpg"
with the actual URL of the image you want to download.
When the user clicks the "Download Image" button, the JavaScript code sends an Ajax request to the PHP server script (download.php
). The PHP script then fetches the image from the given URL using file_get_contents()
and sets the appropriate headers to initiate the download on the client-side. Finally, the JavaScript code uses the obtained image URL to display the downloaded image in the <img>
element with the id "downloaded-image"
.