0

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?

Bryan Campbell
  • 285
  • 3
  • 9
  • At the top of your getPics() function you have `var u = usernameString`. Is usernameString defined anywhere? Your function takes the parameter `id`, but I don't see it used anywhere either. – Sgt AJ May 28 '16 at 00:51
  • _"The image is uploaded as a blob with seemingly no issues"_ Where is `Blob` created at `js`? What is expected result of `var f = $( "#imageFileField").val();`? – guest271314 May 28 '16 at 00:53
  • Sidenote: `$conn->close();` that should be `$db`, not `$conn`. – Funk Forty Niner May 28 '16 at 00:58
  • btw, if your images show up without the JS, then your JS is failing and you need to look at your console. So try it without the JS. Ping me when you get results, I'm leaving the question now. – Funk Forty Niner May 28 '16 at 01:02
  • @SgtAJ yes it is defined as a global at the top of my js file and is set when user signs in – Bryan Campbell May 28 '16 at 01:13
  • @guest271314 blob was created using phpmyadmin. Expected result for f is the selected image from form data – Bryan Campbell May 28 '16 at 01:15
  • @BryanCampbell Is `f` `File` object or `fakepath` to image? Try `console.log(f)` . No `Blob` appears to be created at `php`? Why do you call `base64_encode`? – guest271314 May 28 '16 at 01:16
  • It may be fakepath. At one point that was what was being returned instead of the image – Bryan Campbell May 28 '16 at 01:20
  • `fakepath` is not image file. `.val()` returns a string, not `File` object of `` element – guest271314 May 28 '16 at 01:20
  • @guest271314 ok maybe that was my main issue. If I am just uploading the fakepath and not the image itself I shouldn't expect to be able to get it out of the database – Bryan Campbell May 28 '16 at 01:23

1 Answers1

0

To retrieve File object from <input type="file"> element use .files property of element

var f = $("#imageFileField")[0].files[0];

One approach to retrieve file object at php is to use $_FILES

See Using files from web applications; see also Upload multiple image using AJAX, PHP and jQuery

Community
  • 1
  • 1
guest271314
  • 1
  • 15
  • 104
  • 177