I have an image in my mysql DB, in type longblob. I have an ajax call that requests the image and on success, changes my html image src to be the received image. My ajax post response is the image name (114046.png) but it will trigger the ajax error section, not success. Can someone look through my code and tell me where im going wrong?
Saving image in DB
public function UploadImage($imageData) {
global $dbCon;
$imgFile = $imageData['file']['name'];
$imgSize = $imageData['file']['size'];
if(empty($imgFile)){
error_log("image file empty");
}
$imgExt = strtolower(pathinfo($imgFile,PATHINFO_EXTENSION)); // get image extension
// valid image extensions
$valid_extensions = array('jpeg', 'jpg', 'png', 'gif'); // valid extensions
if(!in_array($imgExt, $valid_extensions)) {
error_log("Sorry, only JPG, JPEG, PNG & GIF files are allowed.");
}
// Check file size '5MB'
if($imgSize > 5000000) {
error_log("Sorry, your file is too large.");
}
// rename uploading image
$userpic = rand(1000,1000000).".".$imgExt;
$sql = 'UPDATE userinfo SET image=(:image) WHERE username="'.$this->currentUsername.'"';
$stmt = $dbCon->prepare($sql);
$stmt->bindParam(':image', $userpic);
$stmt->execute();
if($stmt == false) {
error_log("Failed to put image info in DB");
} else {
//image uploaded
}
}
Getting the image from the DB
public function GetImage() {
global $dbCon;
$stmt = $dbCon->query("SELECT image FROM userinfo WHERE username='".$this->currentUsername."'");
$fetchResult = $stmt->fetch();
$data = $fetchResult["image"];
if($stmt == false) {
error_log("Failed to put image info in DB");
} else {
$this->LatestUpdate = "Get Image";
$this->image = $data;
}
}
public function GetTheImage() {
return $this->image;
}
Responding to ajax
if($this->model->LatestUpdate() == "Get Image") {
header("Content-type: image/png");
echo $this->model->GetTheImage();
exit();
}
Ajax call (Set the HTML image to the received image)
window.onload = SetImage;
function SetImage() {
data = "action=" + "getImage";
$.ajax({
url: '../index.php', // point to server-side PHP script
dataType: 'image/png', // what to expect back from the PHP script, if anything
data: data,
type: 'post',
success: function(image) {
console.log("success");
$("#profileImage").attr("src", image);
}, error: function(xhr, status, error) {
alert("Error" + xhr.responseText);
}
});
}