$_FILES[] is empty in jQuery generated form - php

I generated the next form in jQuery:
$('.content').append('
<form name="make_new_model_release" enctype="multipart/form-data">
<input data-validate="validate" type="text" name="new_model_release_title" placeholder="Enter new model release title" />
<input type="file" name="newModelReleaseFile" id="newModelReleaseFile" />
<input type="submit" value="Create new model release" />
</form>');
Server side simple:
var_dump($_FILES);
AJAX code:
var data = form.serialize();
$.ajax({
type: 'POST',
dataType: 'json',
url: formurl,
data: data,
beforeSend: function(data) {
form.find('input[type="submit"]').attr('disabled', 'disabled');
},
success: function(data) {
console.log(data);
},
complete: function(data) {
form.find('input[type="submit"]').prop('disabled', false);
}
});
after submitting the $_FILES array is empty.
I checked php.ini
file_uploads=On |
upload_max_filesize=128M | post_max_size=128M
Temp folder is allowed for read and write
I tried to make data: new FormData(formId) - nothing changed, $_FILES array is empty.

If you used jQuery('#dailyActivity').serialize(),
It it is not working for <input type'file'>
Have look at this jsFiddle Does not works
and this one .serialize()
Data from file select elements is not serialized.
Have look at this https://stackoverflow.com/a/8758614/3425489
In you case try this
To send <input type'file'> you may want to try this
var formData = new FormData($('form')[0]);
or specify exact data for formdata
var formData = new FormData();
// Append your other Data
formData.append('newModelReleaseFile', $('input[type=file]')[0].files[0]);
And you ajax call will be
$.ajax({
type: 'POST',
url: formurl,
data: formData,
// THIS MUST BE DONE FOR FILE UPLOADING
contentType: false,
processData: false,
beforeSend: function(data) {
form.find('input[type="submit"]').attr('disabled', 'disabled');
},
success: function(data){
console.log(data);
},
complete: function(data) {
form.find('input[type="submit"]').prop('disabled', false);
}
});

Related

Multiple forms with file input on same page

I'm newby with jquery and have a problem with dealing multiple multipart forms on same page. I'm trying to add some data to mysql via php also uploading mp3 files at same time. Each form uses samename+PHPID. There is no problem with first form but im not getting file data when i use other forms. Can anyone help me?
JS:
$(".msc_send_button").click(function(e) { // changed
var a = this.id; // Button id
var form = $('#'+a).parents('form').attr('id'); // Get buttons parent form id
e.preventDefault();
var formData = new FormData($('#'+form)[0]); // Form Data
$.ajax({
url: '/formposts',
type: 'POST',
cache: false,
contentType: false,
processData: false,
data: formData,
beforeSend: function(){
// change submit button value text
$('#'+a).html('Sending...');
},
success: function(data) {
if(data) {
// Message
$('#info').html(data);
//Button Reset
$('#'+a).html('Send');
}
},
error: function(e){
alert(e);
}
});
return false;
});
PHP Form:
<form name="music-form" id="music-form<?php echo $cont['id']; ?>" enctype="multipart/form-data" novalidate>
<input type="text" name="songno" id="songno" value="<?php echo $cont['song_no']; ?>">
<input type="file" id="mp3" name="mp3" class="inputfile" accept="audio/*" multiple>
<button type="submit" class="msc_send_button" id="msc_send_button<?php echo $cont['id']; ?>">Send</button>
</form>
I think you should change your jquery selector. I didn't see your html codes but you may have created nested forms. Maybe you can use closest('from') instead of parents('form')
$(".msc_send_button").click(function(e) { // changed
var buttonEl = $(this);
var form = buttonEl.closest('form');
e.preventDefault();
var formData = new FormData(form[0]); // Form Data
$.ajax({
url: '/formposts',
type: 'POST',
cache: false,
contentType: false,
processData: false,
data: formData,
beforeSend: function(){
// change submit button value text
buttonEl.html('Sending...');
},
success: function(data) {
if(data) {
// Message
$('#info').html(data);
//Button Reset
buttonEl.html('Send');
}
},
error: function(e){
alert(e);
}
});
return false;
});

Ajax form sending null data to php

I am trying to send the form data to PHP with AJAX but when dumping data on PHP page it is returning null values.
Actually, I want a program where I can upload an image than in pop up crop it and then save the cropped image in the database.
My code is given below:
$('#fileinput').on('change', function() {
var formD = new FormData();
var file = $('#fileinput')[0].files[0];
// var nfile = file.serializeArray();
// console.log(file);
formD.append('file', file);
formD.append("clientID", 2993);
console.log(formD);
$.ajax({
url: 'croped.php',
type: 'POST',
data: {
'ff': formD
},
processData: false,
contentType: true,
// dataType: 'json',
success: function(data) {
console.log(data);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="" method="POST" enctype="multipart/form-data">
<input type="file" name="image" id="fileinput" />
<input type="submit" name="upld" id="upldbtn" />
</form>
croped.php
<?php
var_dump($_POST);
echo "ll";
?>
Please let me know what I am missing or doing wrong.
Try this, it works for me :)
contentType: false,
data: formD,
For example
$.ajax({
url: "croped.php",
type: "POST",
data: formD,
processData: false,
contentType: false,
// dataType: 'json',
success: function (data) {
console.log(data);
},
});
For the php code
<?php
echo "<pre>";
print_r($_FILES);
<form action = "" method = "POST" enctype = "multipart/form-data"
id="formdata">
<input type = "file" name = "image" id="fileinput" />
<input type = "submit" name="upld" id="upldbtn" />
</form>
$("#formdata").submit(function(e) {
e.preventDefault();
var formData = new FormData(this);
$.ajax({
url: window.location.pathname,
type: 'POST',
data: formData,
success: function (data) {
alert(data)
},
cache: false,
contentType: false,
processData: false
});
});

How to use FormData in jquery for uploading files?

I have html form:
<form enctype="multipart/form-data" id="formUpload">
<input type="file" name="file" />
<button type="submit" id="sub">Click</button>
</form>
My script:
$(function() {
$("#sub").on("click",function () {
var form = $("#formUpload")[0];
var formData = new FormData(form);
$.ajax({
url: 'upload.php',
data: formData,
type: 'POST',
contentType: false,
processData: false,
dataType: 'html',
success: function(data) {
$("#res").html(data);
}
});
});
});
I try to upload file in upload.php, but all is wrong.
How can I get $_FILES variable?
Every time you click on submit button, your page will get refreshed and you won't see any output from this statement $("#res").html(data);. Use event.preventDefault() method to prevent your form from being submitted in the first place. So your Javascript code should be like this:
$(function() {
$("#sub").on("click",function (event){
event.preventDefault();
var form = $("#formUpload")[0];
var formData = new FormData(form);
$.ajax({
url: 'upload.php',
data: formData,
type: 'POST',
contentType: false,
processData: false,
dataType: 'html',
success: function(data) {
$("#res").html(data);
}
});
});
});
And in the backend upload.php page, you can access the uploaded file data using $_FILES, like this:
<?php
if(is_uploaded_file($_FILES['file']['tmp_name'])){
$name = $_FILES['file']['name'];
$type = $_FILES['file']['type'];
$size = $_FILES['file']['size'];
// ...
}
?>

How to upload image through jQuery Steps

I know how to upload images by ajax but I want to upload images via jQuery steps. I've tried multiple ways but its not not working. If anyone has ever done that please help me. Thanks.
HTML
<input type="file" style="background-color: #2184b3; color: #fff;" class="btn btn-default" name="upload_doc" id="upload_doc" title="Search for a file to add">
jQuery
if(currentIndex == 0)
{
var upload_doc = $("#upload_doc").val();
event.preventDefault();
$.ajax({
async: false,
url: myUrl,
dataType: 'json',
type: 'POST',
cache: false,
contentType: false,
processData: false,
data : { upload_doc : upload_doc, step1 : step1},
success: function(response) {
console.log(response);
}
});
}
Follow this way for upload an image, In this way you don't want HTML form.
Add this code to your mainpage.php
<input type="file" name="upload_doc" id="upload_doc" title="Search for a file to add"/>
<input id="uploadImage" type="button" value="Upload Image" name="upload"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script type="text/javascript">
jQuery.noConflict();
jQuery('#uploadImage').on("click", function (e) {
var uploadedFile = new FormData();
uploadedFile.append('upload_doc', upload_doc.files[0]);
jQuery.ajax({
url: 'lab1.php',
type: 'POST',
processData: false, // important
contentType: false, // important
dataType : 'json',
data: uploadedFile
});
});
</script>
Then add this for upload.php
<?php
// check record array
print_r($_FILES);
move_uploaded_file($_FILES['upload_doc']['tmp_name'], $_FILES['upload_doc']['name']);
?>
first in your ajax call include success & error function and then check if it gives you error or what?You can use jquery.form.js plugin to upload image via ajax to the server.
<form action="" name="imageUploadForm" id="imageUploadForm" method="post" enctype="multipart/form-data">
<input type="file" style="background-color: #2184b3; color: #fff;" class="btn btn-default" name="upload_doc" id="upload_doc" title="Search for a file to add">
</form>
<script type="text/javascript">
$(document).ready(function (e) {
$('#imageUploadForm').on('submit',(function(e) {
e.preventDefault();
var formData = new FormData(this);
$.ajax({
type:'POST',
url: $(this).attr('action'),
data:formData,
cache:false,
contentType: false,
processData: false,
success:function(data){
console.log("success");
console.log(data);
},
error: function(data){
console.log("error");
console.log(data);
}
});
}));
$("#upload_doc").on("change", function() {
$("#imageUploadForm").submit();
});
});
</script>
From your comment,
actually the thing is that I'm submitting many values also when uploading the image. so one click of next i sends so many data including image. rest data goes well except image only.
If you're uploading file, along with other input values, through AJAX, use FormData object. But keep in mind that old browsers don't support FormData object, FormData support starts from the following desktop browsers versions: IE 10+, Firefox 4.0+, Chrome 7+, Safari 5+, Opera 12+.
So your jQuery should be like this:
if(currentIndex == 0){
event.preventDefault();
var formData = new FormData($('form')[0]);
$.ajax({
async: false,
url: myUrl,
dataType: 'json',
type: 'POST',
cache: false,
contentType: false,
processData: false,
data : formData,
success: function(response) {
console.log(response);
}
});
}
first in your ajax call include success & error function and then check if it gives you error or what?You can use jquery.form.js plugin to upload image via ajax to the server.
$(document).ready(function (e) {
$('#imageUploadForm').on('submit',(function(e) {
e.preventDefault();
var formData = new FormData(this);
$.ajax({
type:'POST',
url: $(this).attr('action'),
data:formData,
cache:false,
contentType: false,
processData: false,
success:function(data){
console.log("success");
console.log(data);
},
error: function(data){
console.log("error");
console.log(data);
}
});
}));
$("#ImageBrowse").on("change", function() {
$("#imageUploadForm").submit();
});
});

How to get the uploaded image using PHP via AJAX

I need to get the uploaded image using PHP via Ajax
My form fields are,
<form action="#" method="post" id="rent_details" name="rent_details" enctype="multipart/form-data">
Upload Image :<input type="file" name="fileToUpload" id="fileToUpload">
type:- <select name="spottype" id="spottype">
<option value="xxx">xxx</option>
<option value="yyy">yyy</option>
<option value="zzz">zzz</option>
</select>
<input type="button" id="bidm" name="bidm" value="Next"/>
</form>
In ajax call I have following code :-
$.ajax({
url: './api/addspot.php',
data: $('#rent_details').serialize(),
type: 'POST',
contentType: false,
success: function(data) {
alert(data);
},
error: function(xhr, status, error) {
alert(xhr.responseText);
}
});
Here I got only spottype value in Ajax success function .But I need to get
all form fields value.
<form action="#" method="post" id="rent_details" name="rent_details" enctype="multipart/form-data">
Upload Image :<input type="file" name="fileToUpload" id="fileToUpload">
type:- <select name="spottype" id="spottype">
<option value="xxx">xxx</option>
<option value="yyy">yyy</option>
<option value="zzz">zzz</option>
</select>
<input type="submit" id="bidm" name="bidm" value="Next"/>
</form>
$(document).ready(function(){
$("#rent_details").submit(function(e){
e.preventDefault();
$.ajax({
method:'POST',
url: "./api/addspot.php",
data: new FormData( this ),
processData: false,
contentType: false
}).done(function(data) {
console.log(data);
});
});
});
And get by name on your requested page. use $_FILES for upload files.
This will work.
$('#rent_details').on('submit',(function(e) {
e.preventDefault();
var formData = new FormData(this);
$.ajax({
url: './api/addspot.php',
data: formData,
type: 'POST',
contentType: false,
processData: false,
success: function(data) {
alert(data);
},
error: function(xhr, status, error) {
alert(xhr.responseText);
}
});
}));
Need to use the FormData() for the ajax data. It took all the form variables and passed it to the ajax. Then in the ajax function, you can retrieve the file name and the temp file name and save the image file to the folder where you required to save.
You need to use the FormData();
Know that this code will not work on IE9 and lower.
This is for multiple file upload.
$(document).on('click', '#bidm', function(e) {
e.preventDefault();
var request = new FormData(this);
var my_files = $(this).closest('form').find('#fileToUpload').files;
$.each(my_files, function(j,file) {
` request.append('fileToUpload['+j+']', file);
});
$.ajax({
url: './api/addspot.php',
data: request,
dataType: "json",
contentType: false,
processData: false,
enctype: 'multipart/form-data',
success: function(data) {
alert(data);
},
error: function(xhr, status, error) {
alert(xhr.responseText);
}
});
});
Try this to get file field value:
$('input[type=file]').val()
This code is worked

Categories