PHP AJAX Image Uploading with FormData - php

I am relatively new to jQuery and Ajax functions, but have been working with Ajax forms over the past few days. I have come to a problem with file uploads however when trying to upload images. Whilst looking for resources, I couldn't find anything useful because they seem to be over-complicated with pointless extras or have no explanation whatsoever, which doesn't help me to learn any further.
I have wrote this code to handle the image upload in Ajax:
$(function() {
$('.input_photo').on("change",function() {
var formData = new FormData($('form.upload-form'));
$.ajax({
url: "upload.php",
type: "POST",
data: formData,
success: function (msg) {
alert(msg)
}
});
});
});
This sends a request to the upload.php file, however no data is sent, basically my form is literally this:
<form class="upload-form">
<input type="file" name="input_photo" class="input_photo" />
</form>
No data seems to be passed in the headers whatsoever and I assume I would access it through PHP with $_POST['data'] array or $_FILES? Someone with better knowledge please help to explain this, it'd be great to understand this further.
Thanks.

This will work for one or multiple files.
$('input:file').on('change', function () {
var data = new FormData();
//Append files infos
jQuery.each($(this)[0].files, function(i, file) {
data.append('file-'+i, file);
});
$.ajax({
url: "my_path",
type: "POST",
data: data,
cache: false,
processData: false,
contentType: false,
context: this,
success: function (msg) {
alert(msg);
}
});
});
Then
$_FILES['file-0']
$_FILES['file-1']
[...]
But be careful that using FormData doesn't work on IE before IE10

You need to set processData and contentType in your ajax call ( also added id to your input element in order to fetch the file contents).
HTML
<form class="upload-form">
<input type="file" id="photo" name="input_photo" class="input_photo" />
</form>
JS
$(function() {
$('.input_photo').on("change",function() {
var file = document.getElementById("photo").files[0]; //fetch file
var formData = new FormData();
formData.append('file', file); //append file to formData object
$.ajax({
url: "upload.php",
type: "POST",
data: formData,
processData: false, //prevent jQuery from converting your FormData into a string
contentType: false, //jQuery does not add a Content-Type header for you
success: function (msg) {
alert(msg)
}
});
});
});

Try with this:
var formData = $('form.upload-form').serialize();

Related

Add custom $_POST before submitting form with jquery

First of all, sorry if this is a duplicate. I've looked and seen some solutions but none worked. I've been trying to do this simple thing for like 3 hours with no result.
I'd have this html:
<form method="post" action="?c=Logo&action=save" id="form">
<!-- some inputs -->
<img src="" data-filename="new-logo.png">
<input type="submit" value="submit">
</form>
Here I'd like to modify the form so my php file will recognise $_POST['new-logo'].
// $_POST['new-logo'] = $('img').data('filename')
$logo = new Logo($_POST['new-logo']);
$logo->save();
I guess I should use the jQuery function $.post() but somehow I can't manage. Thank you all for your help :-)
SOLUTION
Finally since I found a very simple solution. Since I want my data to be processed in my php file, I simply added an <input type="hidden"> and modified its value with JS :-)
You could also make the data array from scratch like this:
$('#form').on('submit', function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: $(this).attr('action'),
data: {key1:"value", key2:"value2"},
dataType: "json",
success: function(data) {
//do success stuff here
},
error: function() {
//do error stuff here.
}
});
});
You can add it as a hidden input.
$("#form").submit(function() {
$(this).append($("<input>", {
type: "hidden",
name: "new-logo",
value: $(this).find("img").data("filename")
});
});
you can add this to you're post request like this :
$('#form').on('submit', function(e){
e.preventDefault();
var $form = $(this);
var datastring = $form.serializeArray();
datastring.push({name:'new-logo', value:$form.find('img').data('filename')});
$.ajax({
type: "POST",
url: $form.attr('action'),
data: datastring,
dataType: "json",
success: function(data) {
//var obj = jQuery.parseJSON(data); if the dataType is not specified as json uncomment this
// do what ever you want with the server response
},
error: function() {
alert('error handing here');
}
});
});
$logo = new Logo($_POST['new-logo']);
Is "new Logo" a function or something? Pretty sure that can't have a space.

Laravel Route - Unable to fetch file upload post parameter [duplicate]

So I have a form and I'm submitting the form through ajax using jquery serialization function
serialized = $(Forms).serialize();
$.ajax({
type : "POST",
cache : false,
url : "blah",
data : serialized,
success: function(data) {
}
but then what if the form has an <input type="file"> field....how do I pass the file into the form using this ajax serialization method...printing $_FILES doesn't output anything
Use FormData object.It works for any type of form
$(document).on("submit", "form", function(event)
{
event.preventDefault();
$.ajax({
url: $(this).attr("action"),
type: $(this).attr("method"),
dataType: "JSON",
data: new FormData(this),
processData: false,
contentType: false,
success: function (data, status)
{
},
error: function (xhr, desc, err)
{
}
});
});
A file cannot be uploaded using AJAX because you cannot access the contents of a file stored on the client computer and send it in the request using javascript. One of the techniques to achieve this is to use hidden iframes. There's a nice jquery form plugin which allows you to AJAXify your forms and it supports file uploads as well. So using this plugin your code will simply look like this:
$(function() {
$('#ifoftheform').ajaxForm(function(result) {
alert('the form was successfully processed');
});
});
The plugin automatically takes care of subscribing to the submit event of the form, canceling the default submission, serializing the values, using the proper method and handle file upload fields, ...
var form = $('#job-request-form')[0];
var formData = new FormData(form);
event.preventDefault();
$.ajax({
url: "/send_resume/", // the endpoint
type: "POST", // http method
processData: false,
contentType: false,
data: formData,
It worked for me! just set processData and contentType False.
HTML
<form name="my_form" id="my_form" accept-charset="multipart/form-data" onsubmit="return false">
<input id="name" name="name" placeholder="Enter Name" type="text" value="">
<textarea id="detail" name="detail" placeholder="Enter Detail"></textarea>
<select name="gender" id="gender">
<option value="male" selected="selected">Male</option>
<option value="female">Female</option>
</select>
<input type="file" id="my_images" name="my_images" multiple="" accept="image/x-png,image/gif,image/jpeg"/>
</form>
JavaScript
var data = new FormData();
//Form data
var form_data = $('#my_form').serializeArray();
$.each(form_data, function (key, input) {
data.append(input.name, input.value);
});
//File data
var file_data = $('input[name="my_images"]')[0].files;
for (var i = 0; i < file_data.length; i++) {
data.append("my_images[]", file_data[i]);
}
//Custom data
data.append('key', 'value');
$.ajax({
url: "URL",
method: "post",
processData: false,
contentType: false,
data: data,
success: function (data) {
//success
},
error: function (e) {
//error
}
});
PHP
<?php
echo '<pre>';
print_r($_POST);
print_r($_FILES);
echo '</pre>';
die();
?>
You can upload files via AJAX by using the FormData method. Although IE7,8 and 9 do not support FormData functionality.
$.ajax({
url: "ajax.php",
type: "POST",
data: new FormData('form'),
contentType: false,
cache: false,
processData:false,
success: function(data) {
$("#response").html(data);
}
});
$(document).on('click', '#submitBtn', function(e){
e.preventDefault();
e.stopImmediatePropagation();
var form = $("#myForm").closest("form");
var formData = new FormData(form[0]);
$.ajax({
type: "POST",
data: formData,
dataType: "json",
url: form.attr('action'),
processData: false,
contentType: false,
success: function(data) {
alert('Sucess! Form data posted with file type of input also!');
}
)};});
By making use of new FormData() and setting processData: false, contentType:false in ajax call submission of form with file input worked for me
Using above code I am able to submit form data with file field also through Ajax
HTML5 introduces FormData class that can be used to file upload with ajax.
FormData support starts from following desktop browsers versions. IE 10+, Firefox 4.0+, Chrome 7+, Safari 5+, Opera 12+
FormData - Mozilla.org

PHP ajax uploading images

I'm trying to do a file upload through ajax and php. The PHP works fine when called directly, but each time I call it through ajax it is failing. I'm not getting any errors (annoying) it just does not want to upload.
My JQUERY looks like
$('.fileUpload').on('click', function(){
var file_data = $('#medical').prop('files')[0];
console.log(file_data);
var form_data = new FormData();
form_data.file = file_data;
console.log(form_data);
var fileType = $(this).parent().find('input[type="hidden"]').val()
console.log(fileType);
$.ajax({
url: '/docs/upload.php', // point to server-side PHP script
dataType: 'text', // what to expect back from the PHP script, if anything
cache: false,
fileType:fileType,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(data){
$('.message').html(data) // display response from the PHP script, if any
}
});
});
and my PHP looks like
$file_upload="true";
$file_up_size=$_FILES['file_up'][size];
print_r($_FILES[file_up]);
if ($_FILES[file_up][size]>250000){$msg=$msg."Your uploaded file size is more than 250KB
so please reduce the file size and then upload.<BR>";
$file_upload="false";}
$file_name=$_FILES[file_up][name];
$add="medicalPaperwork/$file_name"; // the path with the file name where the file will be stored
if($file_upload=="true"){
if(move_uploaded_file ($_FILES[file_up][tmp_name], $add)){
echo "Thank god!";
}else{echo "Fuck you.";}
}else{
echo $msg;
}
What am I doing wrong? I'm going crazy trying to figure this out.
edit: the content of the form_data
You are using FormData incorrectly, use append to set the fields you want to upload
$('.fileUpload').on('click', function(){
var file_data = $('#medical').prop('files')[0];
console.log(file_data);
var form_data = new FormData();
var fileType = $(this).parent().find('input[type="hidden"]').val()
form_data.append('file_up', file_data);
form_data.append('fileType', fileType);
console.log(form_data);
console.log(fileType);
$.ajax({
url: '/docs/upload.php', // point to server-side PHP script
dataType: 'text', // what to expect back from the PHP script, if anything
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(data){
$('.message').html(data) // display response from the PHP script, if any
}
});
});

File submission using ajax and jquery not working

I have to submit the form using ajax. The form contain a text field and a file upload field.But in ajax page(formaction.php) the the file details are not getting.
HTML
<form method="post" id="newform" enctype="multipart/form-data">
Name:<input type="text" id="txt" name="txt"><br>
File:<input type="file" id="image" name="image"><br>
<input type="submit" id="btn" value='Proceed'>
</form>
jQuery
$(document).ready(function(){
$("#btn").click(function(event){
event.preventDefault();
var formdata = $('form#newform').serialize();
$.post("formaction.php",{formdata:formdata},function(data){
alert(data);
});
});
});
formaction.php
print_r($_REQUEST['formdata']);
input type file details are not getting in ajax page. The formdata only contain the value of text field.
your jquery must be change same as this:
<script type="text/javascript">
function submitForm() {
console.log("submit event");
var fd = new FormData(document.getElementById("fileinfo"));
fd.append("label", "WEBUPLOAD");
$.ajax({
url: "formaction.php",
type: "POST",
data: fd,
enctype: 'multipart/form-data',
processData: false, // tell jQuery not to process the data
contentType: false // tell jQuery not to set contentType
}).done(function( data ) {
console.log("PHP Output:");
console.log( data );
});
return false;
}
</script>
To get file details,
instead of this,
print_r($_REQUEST['formdata']);
add this
print_r($_FILES['image']);
The serialize() won't include the file input in the form data. You have to do it manually.
$("#btn").click(function(event) {
event.preventDefault();
var form_data = new FormData(document.getElementById('newform'));
// Now you have your DataObject setup.
$.ajax({
url: 'formaction.php',
type: 'POST',
cache : false,
contentType: false, // Important.
processData: false, // Important.
data: form_data
})
.done(function(data) {
console.log(data);
})
.fail(function(data) {
console.log(data);
});
return false;
});
Using $.ajax() you can achieve this very easily.
Now in formaction.php: You can pick up the values like normal form submission.
$txt = $_POST['txt'];
$image = $_FILES['image'];
Note: Do keep in mind those contentType: false and processData: false
If you don't give processData: false then ajax will return an error in the console "Illegal invocation."
If you don't give contentType: false then the file will be submitted in encoded and raw with content-disposition and content-type: 'application/pdf' or whatever mime type you are uploading.

how to do file upload using jquery serialization

So I have a form and I'm submitting the form through ajax using jquery serialization function
serialized = $(Forms).serialize();
$.ajax({
type : "POST",
cache : false,
url : "blah",
data : serialized,
success: function(data) {
}
but then what if the form has an <input type="file"> field....how do I pass the file into the form using this ajax serialization method...printing $_FILES doesn't output anything
Use FormData object.It works for any type of form
$(document).on("submit", "form", function(event)
{
event.preventDefault();
$.ajax({
url: $(this).attr("action"),
type: $(this).attr("method"),
dataType: "JSON",
data: new FormData(this),
processData: false,
contentType: false,
success: function (data, status)
{
},
error: function (xhr, desc, err)
{
}
});
});
A file cannot be uploaded using AJAX because you cannot access the contents of a file stored on the client computer and send it in the request using javascript. One of the techniques to achieve this is to use hidden iframes. There's a nice jquery form plugin which allows you to AJAXify your forms and it supports file uploads as well. So using this plugin your code will simply look like this:
$(function() {
$('#ifoftheform').ajaxForm(function(result) {
alert('the form was successfully processed');
});
});
The plugin automatically takes care of subscribing to the submit event of the form, canceling the default submission, serializing the values, using the proper method and handle file upload fields, ...
var form = $('#job-request-form')[0];
var formData = new FormData(form);
event.preventDefault();
$.ajax({
url: "/send_resume/", // the endpoint
type: "POST", // http method
processData: false,
contentType: false,
data: formData,
It worked for me! just set processData and contentType False.
HTML
<form name="my_form" id="my_form" accept-charset="multipart/form-data" onsubmit="return false">
<input id="name" name="name" placeholder="Enter Name" type="text" value="">
<textarea id="detail" name="detail" placeholder="Enter Detail"></textarea>
<select name="gender" id="gender">
<option value="male" selected="selected">Male</option>
<option value="female">Female</option>
</select>
<input type="file" id="my_images" name="my_images" multiple="" accept="image/x-png,image/gif,image/jpeg"/>
</form>
JavaScript
var data = new FormData();
//Form data
var form_data = $('#my_form').serializeArray();
$.each(form_data, function (key, input) {
data.append(input.name, input.value);
});
//File data
var file_data = $('input[name="my_images"]')[0].files;
for (var i = 0; i < file_data.length; i++) {
data.append("my_images[]", file_data[i]);
}
//Custom data
data.append('key', 'value');
$.ajax({
url: "URL",
method: "post",
processData: false,
contentType: false,
data: data,
success: function (data) {
//success
},
error: function (e) {
//error
}
});
PHP
<?php
echo '<pre>';
print_r($_POST);
print_r($_FILES);
echo '</pre>';
die();
?>
You can upload files via AJAX by using the FormData method. Although IE7,8 and 9 do not support FormData functionality.
$.ajax({
url: "ajax.php",
type: "POST",
data: new FormData('form'),
contentType: false,
cache: false,
processData:false,
success: function(data) {
$("#response").html(data);
}
});
$(document).on('click', '#submitBtn', function(e){
e.preventDefault();
e.stopImmediatePropagation();
var form = $("#myForm").closest("form");
var formData = new FormData(form[0]);
$.ajax({
type: "POST",
data: formData,
dataType: "json",
url: form.attr('action'),
processData: false,
contentType: false,
success: function(data) {
alert('Sucess! Form data posted with file type of input also!');
}
)};});
By making use of new FormData() and setting processData: false, contentType:false in ajax call submission of form with file input worked for me
Using above code I am able to submit form data with file field also through Ajax
HTML5 introduces FormData class that can be used to file upload with ajax.
FormData support starts from following desktop browsers versions. IE 10+, Firefox 4.0+, Chrome 7+, Safari 5+, Opera 12+
FormData - Mozilla.org

Categories