I am trying to use XMLHttpRequest to submit an image query to a mysql database. The getPics() function is called before the gallery of pictures is to be loaded.
function getPics (id){
var u = usernameString;
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var showGalleryHtml;
showGalleryHtml = '<div id="galleryHeader">' +
'</div>' +
'<div id="thumbnailGalleryView">'+
+ xmlhttp.responseText +
'</div>'+
'<div id="addPicButton">'+
'<form>'+
'<input type="file" id="imageFileField" name="file">'+
'<button type="button" class="btn btn-success" onclick="submitPic(this)">Add Pic</button>'+
'</form>'+
'</div>';
var $jshowGalleryHtml = $(showGalleryHtml);
$("body").append($jshowGalleryHtml);
}
else{
//alert(xmlhttp.responseText);
}
};
xmlhttp.open("GET", "GetPics.php?u=" + u, true);
xmlhttp.send();
}
The PHP file GetPics.php that is triggered is shown below. And outputs an array of html image tags.
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "seemedb";
$db = new mysqli($servername, $username, $password, $dbname);
if($db->connect_errno > 0){
die('Unable to connect to database [' . $db->connect_error . ']');
}
$user = $_REQUEST["u"];
//create Array to hold data
$pictureArray = array();
$sql = "SELECT * FROM `imageTable` WHERE `user` = '".$user."'";
if(!$result = $db->query($sql)){
die('There was an error running the query [' . $db->error . ']');
}
while($row = $result->fetch_assoc()){
$pictureArray[] = '<img height="100" width="100" src="data:image;base64,'.$row['image'] .'">';
}
echo $pictureArray;
$conn->close();
?>
Finally, the image files are uploaded using the following function and php files.
function submitPic (id){
var f = $( "#imageFileField").val();
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
//prit output from php? Uncomment below
//alert(foundUser);
}
};
xmlhttp.open("POST", "seeMeAddPic.php?u=" + usernameString + "&f=" + f, true);
xmlhttp.send();
}
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "seemedb";
$db = new mysqli($servername, $username, $password, $dbname);
if($db->connect_errno > 0){
die('Unable to connect to database [' . $db->connect_error . ']');
}
$user = $_REQUEST["u"];
$imageFile = $_REQUEST["f"];
$imageFile = base64_encode($imageFile);
$sql = "INSERT INTO imageTable (user, image) VALUES ('".$user."', '".$imageFile."')";
if ($db->query($sql) === TRUE) {
echo "New record created successfully";
//echo $user;
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
The image is uploaded as a blob with seemingly no issues but the html will not load the pictures. Any thoughts?