Flame of udun
Flame of udun

Reputation: 2237

Javascript AJAX upload of BLOB image using php. $_FILES is empty

Hi I am trying to upload a BLOB image onto my localhost wampserver through AJAX using Javascript and PHP.

I am trying to obtain the image in $_FILES but for some reason $_FILES is empty. I have set enctype and checked php.ini for file_uploads = On.

Here is my html form:

<h1>CREATE A NEW ENTRY</h1>
<form name="insertForm" method="post" enctype="multipart/form-data">
  Name: <input type="text"  id="insert_name" /> <br />
  Age: <input type="text" id="insert_age" /> <br />
  WPM: <input type="text" id="insert_wpm" /> <br />
  Sex: <select id="insert_sex">
            <option>M</option>
            <option>F</option>
       </select><br />
  Photo : <input type="file" name="photo" id="insert_photo" /> <br />
  <input type="button" onClick="insertFunction()" value="UPDATE LIST" />
</form>
<br>
<br>
<div id="preview"><img id="preview_img" src="images/placeholder.png"/></div>
<div id="message"></div>

Here is the javascript that runs the AJAX :

function insertFunction() 
{
    var ajaxRequest = createAjaxObject(); // checks for browser type and returns corres. ajax object    
    var name = document.getElementById('insert_name').value;
    var age = document.getElementById('insert_age').value;
    var wpm = document.getElementById('insert_wpm').value;
    var sex = document.getElementById('insert_sex').value;

    var image = document.getElementById('insert_photo').files[0];
    var imageType = image.type;
    alert(imageType);
    var match = ["image/jpeg", "image/png", "image/jpg"]

    if (!((imageType==match[0]) || (imageType==match[1]) || (imageType==match[2])))
    {
    document.getElementById('preview').innerHTML = '';
    document.getElementById('preview').innerHTML = '<img id="preview_img" src="images/noimage.png"/ alt="../images/noimage.png">';
    document.getElementById("message").innerHTML = "<p class='error'>Please Select A valid Image File</p>"+"<h4>Note</h4>"+"<span id='error_message'>Only jpeg, jpg and png Images type allowed</span>";
    }
    else
    {
    var reader =  new FileReader();
    reader.onload = function(e) {
        document.getElementById('preview').innerHTML = '';
        document.getElementById('preview').innerHTML = '<img id="preview_img" src="' + e.target.result + '" alt="' + e.target.result + '">';
    };
    reader.readAsDataURL(image);

    var dataString = "name=" + name + "&age=" + age + "&wpm=" + wpm + "&sex=" + sex + "&photo=" + image;

    ajaxRequest.open("POST", "insert-example.php", true);

    ajaxRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

    ajaxRequest.send(dataString);
    document.getElementById('insertDiv').innerHTML = "processing...";

    ajaxRequest.onreadystatechange = function() {

        if (ajaxRequest.readyState == 4)
        {
        var insertDiv = document.getElementById('insertDiv');
        insertDiv.innerHTML = ajaxRequest.responseText;
        }
    }
   } 
}

And here is the php that updates the localhost.

<?php

    if ($_SERVER["REQUEST_METHOD"] == "POST")
    {
        $dbhost = "localhost";
        $dbuser = "root";
        $dbpassword = "";
        $dbname = "ajaxtutorial";

        $link = mysqli_connect($dbhost, $dbuser, $dbpassword, $dbname);

        if (mysqli_connect_errno())
        {
            echo "Connection failed: %s" . mysqli_connect_error();
        }

        mysqli_connect($dbhost, $dbuser, $dbpassword) or die(mysql_error());
        mysqli_select_db($link, $dbname) or die("Cannot connect to database");

        $name = mysqli_real_escape_string($link, $_POST['name']);
        $age = mysqli_real_escape_string($link, $_POST['age']);
        $wpm = mysqli_real_escape_string($link, $_POST['wpm']);
        $sex = mysqli_real_escape_string($link, $_POST['sex']);

        // Image file code below

        if (false) 
        {
            $photo = $_FILES["photo"];
            echo $photo;
        }

        else
        {   
            echo var_dump($_FILES);
        }       
    }
?>

The output I get from the var_dump is :

array (size=0)
empty

Could someone please tell me what is going wrong with my code?

Upvotes: 0

Views: 1432

Answers (2)

Jonas Libbrecht
Jonas Libbrecht

Reputation: 787

Try to use jQuery, way more simple: (so replace everything in your js file with this script and keep the HTML and PHP)

      $.ajax({
        type: 'post',
        url: 'update.php', //php script
        data: new FormData($('form')[0]), //form data
        processData: false,
        contentType: false,
        success: function (result) {
          //do something cool when it is succesfully updated
      });

PS: don't forget to include this BEFORE the script because it is jQuery: <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.11.2.min.js">

Upvotes: 1

websky
websky

Reputation: 3172

try this

var imageData = new FormData(image);

var dataString = "name=" + name + "&age=" + age + "&wpm=" + wpm + "&sex=" + sex + "&photo=" + imageData;

Sending files using a FormData object

Upvotes: 0

Related Questions