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 functio
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
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"];
?>
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 theXMLHttpRequest.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.
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.
<form>
tagAssuming 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.
<form>
tagIf 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);
}
});
});
});