I am using an ajax call to pass a value. I have done that and I want to take that value and do a lookup on my tables for a particular image.
When I get to the image to download, it is not working for me. I looked on my php.ini file and my allow_furl_open is off. I think this may be the culprit. Please disregard the mysql bits as I know it should be updated, this is not my code so that will be changed.
Here is the code.
if (isset($_POST['download'])) {
$sql = "SELECT `imageURL` FROM `digital_materials` WHERE `digital_materials`.`id` = '$id'";
$record = mysql_query($sql);
$row = mysql_fetch_assoc($record);
$fileName = $row['imageURL'];
$fileURL = 'images/products/' . $fileName;
header('Content-Type: application/octet-stream');
header("Content-Transfer-Encoding: Binary");
header('Content-Disposition: attachment; filename=' . $row['imageURL']);
readfile($fileURL);
exit();
}
This should be working. Any problems?
As mentioned in the comments by Marc B, you can’t download a file through ajax. Ajax will just return the network request to the sender (i.e. jQuery ajax has a success handler function that contains the result of the request: http://api.jquery.com/jQuery.ajax/). One possible solution is to open a new window with the php url which will trigger the download request. A javascript solution is:
Another solution is using an anchor tag with the target=”_blank” attribute.
The following is a php solution for returning an image taken from php’s readfile documentation:
EDIT ** Added Form example which will post the variable
You would then reference the variable as $_POST[‘id’] because that is the value of the name attribute in the form.
Using a $_GET parameter, you would do it as below:
Use $_GET[‘id’] to reference the value in PHP as id is the name of the query string parameter.