3

My code is a form where it picks a file from the user, then send the data using jQuery to a PHP file where it gets the image content and displays it and in a success function: it alerts the data received from the PHP file. For example, the image received from the HTML page.

Actually, the code inserts the image into the database, but I plucked the code out and inserted a direct view of image in PHP file without inserting in the database because I wanted to make it short(database insertion code has no error: it inserts other variables provided with image and image stays blank)

Also am using my script on XAMPP localhost. So do not worry about that i am running it like file://... . All is that i can't figure out why the data aren't being passed to php file.

HTML:

<input style="border:none" type="file" id="photo" />  <br>

JavaScript:

$("#submit-form").click(function() {
  var formadata = {
    "photo": $("#photo").val(),
  };
  $.ajax({
    url: './enter-registration-form.php',
    data: formadata,
    cache: false,
    contentType: false,
    processData: false,
    method: 'POST',
    success: function(val) {
      if (val == "done") {
        alert("Data Accepted");
      } else {
        alert(val);
      }
    }
  });
});

PHP:

$i = $_FILES['photo']['name'];

//get the content of the image and then add slashes to it
$imagetmp=addslashes (file_get_contents($_FILES['photo']['tmp_name']));

echo '<img src="data:image/jpeg;base64,'.base64_encode($imagetmp).'" style="width:100px;height:autoborder:none">';

Now I am getting this error message:

Notice: Undefined index: photo in /opt/lampp/htdocs/SSNC/exam/enter-registration-form.php on line 5

Notice: Undefined index: photo in /opt/lampp/htdocs/SSNC/exam/enter-registration-form.php on line 8

Warning: file_get_contents(): Filename cannot be empty in /opt/lampp/htdocs/SSNC/exam/enter-registration-form.php on line 8

I can't figure out why this error is thrown.

Adern Nerk
  • 45
  • 8
  • Try changing $_FILES to $_POST (as your Ajax is sending to php via post method) failing that var_dump($_FILES) to see what it contains – Adam Brinded Jun 30 '18 at 10:14
  • Where are you actually handling the upload? – brombeer Jun 30 '18 at 10:23
  • kerbholz can you elaborate ? – Adern Nerk Jun 30 '18 at 10:26
  • adam when $_POST['photo'] used it says undefined variable, and when i remove mimetype, cache:false, contenttype:false from jquery code and run the scripting then it shows the path name of the file selected saved in $_POST['photo']. – Adern Nerk Jun 30 '18 at 10:29
  • i think `cache: false, contentType: false, processData: false` i need to change this with respect to my need, i just copied this from internet because so of the solutions say using these solved their problem . – Adern Nerk Jun 30 '18 at 10:33
  • Possible duplicate of [jQuery AJAX file upload PHP](https://stackoverflow.com/questions/23980733/jquery-ajax-file-upload-php) – Nigel Ren Jun 30 '18 at 10:44
  • kerbholz am using it on localhost (XAMPP) – Adern Nerk Jun 30 '18 at 10:47
  • nigel i already have tried searching for issue for 2 days , none of them worked for me , so better you can help instead of providing already answered links. – Adern Nerk Jun 30 '18 at 10:48
  • are you only uploading the file or does your form has other entities as well? – saibbyweb Jun 30 '18 at 11:34
  • it has other entries too , a few with type="text" and one field with type="file" – Adern Nerk Jun 30 '18 at 15:19

3 Answers3

2

Approach

You need to use new FormData() object.

The FormData interface provides a way to easily construct a set of key/value pairs representing form fields and their values, which can then be easily sent using the XMLHttpRequest.send() method. It uses the same format a form would use if the encoding type were set to "multipart/form-data".

So you don't actually have to declare a form tag and add inputs inside, yes it makes it easier if you have let us make a call assuming that you do not have a form tag.

Problem

The problem in your script is that your formdata is a json rather than a FormData() interface object, which uses formdataObject.append() which appends a new value onto an existing key inside a FormData object, or adds the key if it does not already exist.

See code below which posts email, file label and a file to a PHP page without using form tag for the inputs.

Without <form> tag

Assuming that your html looks like below without a form

<label>Your email address:</label>
<input type="email" autocomplete="on" autofocus name="userid" placeholder="email" required size="32" maxlength="64" />
<br />
<label>Custom file label:</label>
<input type="text" name="filelabel" size="12" maxlength="32" />
<br />
<label>File to stash:</label>
<input type="file" name="file" required />
<input type="button" name="submit" value="Stash the file!" />

Your javascript code will look like below

$(document).ready(function () {
    $("input[name='submit']").on('click', function (event) {

        event.preventDefault();

        //START Append form data
        var data = new FormData();
        data.append(
            'userid', $("input[name='userid']").val());
        data.append(
            'label', $("input[name='filelabel']").val()
        );
        data.append('file', $("input[name='file']")[0].files[0], 'somename.jpg');
        //END append form data

        $.ajax({
            type: "POST",
            url: "file.php",
            data: data,
            processData: false,
            contentType: false,

            success: function (data) {
                console.log("SUCCESS : ", data);
            },
            error: function (e) {
                console.log("ERROR : ", e);
            }
        });

    });

});

And your file.php will look like below

<?php

print_r($_POST);
print_r($_FILES);

This should show you the file inputs and file both of them in the console when you hit the stash file button.

With <form> tag

If you have the inputs wrapped inside the form tag then your code will be changed on the following sections

  • Change binding of click event to form submit event.

  • Change button type to submit in the HTML.

  • Get the form object.

  • Use form object to initialize the FormData().

See below How your HTML will look like

<form enctype="multipart/form-data" method="post" name="fileinfo">
    <label>Your email address:</label>
    <input type="email" autocomplete="on" autofocus name="userid" placeholder="email" required size="32" maxlength="64" />
    <br />
    <label>Custom file label:</label>
    <input type="text" name="filelabel" size="12" maxlength="32" />
    <br />
    <label>File to stash:</label>
    <input type="file" name="file" required />
    <input type="submit" value="Stash the file!" />
</form>

And your javascript will look like below

$(document).ready(function () {
    $("form").on('submit', function (event) {

        event.preventDefault();
        var form = this;
        var data = new FormData(form);

        $.ajax({
            type: "POST",
            url: "file.php",
            data: data,
            processData: false,
            contentType: false,

            success: function (data) {
                console.log("SUCCESS : ", data);
            },
            error: function (e) {
                console.log("ERROR : ", e);
            }
        });

    });

});
Muhammad Omer Aslam
  • 22,976
  • 9
  • 42
  • 68
1

This should work!

HTML:

<form id="my-upload-form" method="post" enctype="multipart/form-data">
<input type="file" name="required-image" />
<button> Upload </button>
</form>

JS:

$("button").click(function(e) {
/* prevent default form action */
e.preventDefault();
/* get form element */
var formElement = document.getElementById("my-upload-form");
/* collect all form data from Form element */
var formData = new FormData(formElement);

$.ajax({
url: '/path-to-form-handler.php',
data: formData,
cache: false,
contentType: false,
processData: false,
method: 'POST',
success: function(response) {
    console.log(response);
}
});
});

PHP:

<?php

/* for this example, $_FILES["required-image"] would be an array having image details */
echo $_FILES["required-image"]["name"];
echo $_FILES["required-image"]["type"];
echo $_FILES["required-image"]["tmp_name"];
echo $_FILES["required-image"]["size"];

?>
saibbyweb
  • 2,864
  • 2
  • 27
  • 48
  • so if i have to use the image to insert into database then how should i proceed in php further ? like `$sql="INSERT INTO data VALES($_POST['a'],$_POST['b'],$_POST['c'],$_FILES['required-image']['temp_name'])";` – Adern Nerk Jun 30 '18 at 15:25
  • also saibbyweb can you explain your answer for learning purpose , please that would be very helpful . – Adern Nerk Jun 30 '18 at 15:30
  • also i would like to add that i have to save this image as base64 in database , and when the insertion is success then i have to print/display the image – Adern Nerk Jun 30 '18 at 15:35
  • well i tried `$imagetmp=addslashes (file_get_contents($_FILES["required-image"]["tmp_name"]));` to convert the file into base64 code so as for the purpose of storing in databse , but didn't worked . – Adern Nerk Jun 30 '18 at 16:06
  • the error is :You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near line 1 – Adern Nerk Jun 30 '18 at 16:08
  • I don't think its a good idea to store the image in database, instead we can upload the image on server and store its path in the database. It would be easier that way. – saibbyweb Jun 30 '18 at 17:34
  • in short borther , i am told to be strictly restricted to database only – Adern Nerk Jun 30 '18 at 17:43
  • also i am having more fields with image (type=text, some select fields, file type) so using jquery & the above method you provided , maybe i need to do something more and i am not doing it thats why the sql error ? (and i echo'ed all the $_POST[''] values the variables do have the values , and i copies the sql into phpmyadmin sql and run the query the query also seemed fine, cause it worked there) – Adern Nerk Jun 30 '18 at 17:46
  • https://stackoverflow.com/questions/1636877/how-can-i-store-and-retrieve-images-from-a-mysql-database-using-php This might help. – saibbyweb Jun 30 '18 at 18:17
0

First of all insert your input file tag in a form and use enctype="multipart/formdata" to send an image otherwise you will not able to send image

  • so the form tag with enctype attribut is must ? and then i have to change jquery to $(#form).submit(..) .? – Adern Nerk Jun 30 '18 at 15:28
  • this is wrong , using `FormData()` object to submit form and files along with it has nothing to do with the form tag or the `enctype` attribute , you can still upload files using ajax without having even the form tag defined – Muhammad Omer Aslam Jul 01 '18 at 00:41