I am trying to upload some form data using ajax and php but for some reason my data is not being catch or passed.
Here is what I have:
form.html ( basic form with 3 text inputs and 1 file)
<form class="form" id="superform" action="nada.php" method="post" enctype="multipart/form-data">
<div class="form-group">
<label for="tituloQuiz">Resultado:</label>
<input type="text" class="form-control resultado" id="titulo" name="titulo" placeholder="Ex: Paris">
</div>
<div class="form-group">
<label for="desc">Descrição do Site:</label>
<textarea class="form-control" id="desc" name="descricao" placeholder="Ex:"></textarea>
</div>
<div class="form-group">
<label for="desc">OG FB DESC:</label>
<textarea class="form-control" id="facedes" name="descricao" placeholder="facebook description"></textarea>
</div>
<div class="form-group">
<label for="imggrande">Imagem</label>
<input type="file" id="imggrande" name="imgres">
<p class="help-block">Imagem usada na página de resultado e Facebook 600 x 400.</p>
</div>
<button type="button" class="btn btn-primary btn-lg addres">Adicionar Resultado</button>
<button type="button" class="btn btn-danger btn-lg">Próxima Etapa</button>
</form>
And here is the JS that makes the ajax call:
myjs.js
$("document").ready(function(){
$('.row').on('click','.addres',function(){
console.log('Click Detectado');
var formulario = $('#superform');
var formData = new FormData(formulario);
$.ajax({
type: "POST",
url: "addres.php",
data: formData,
async: false,
success: function(data) {
console.log('Funcionou');
},
error: function(data) {
console.log('Erro no formulario');
},
cache: false,
contetType: false,
processData: false
});
});
});
Nothing is being passed and the POST call is empty (See screenshots below).
**addres.php**
<?php
var_dump($_FILES);
var_dump($_POST);
?>
$.ajax({
url: 'address.php',
type: 'POST',
data: new FormData($('#superform')[0]), // The form with the file inputs.
processData: false, // Using FormData, no need to process data.
contentType:false
}).done(function(){
console.log("Success: Files sent!");
}).fail(function(){
console.log("An error occurred, the files couldn't be sent!");
});
When one sets the contentType option to false, it forces jQuery not to add a Content-Type header, otherwise, the boundary string will be missing from it. Also, when submitting files via multi-part/form one must leave the processData flag set to false, otherwise, jQuery will try to convert your FormData into a string, which will fail.
read from php using
$_FILES['file-0']
(There is only one file, file-0, unless you specified the multiple attribute on your file input, in which case, the numbers will increment with each file.)
Additional info:
See for yourself the difference of how your formData is passed to your php page by using console.log().
var formData = new FormData($('#superform')[0]);
console.log(formData);
var formDataSerialized = $('#superform').serialize();
console.log(formDataSerialized);
Hope this helps.
extra information read this upload files asynchronously
Note : formData doesn't work in IE 9
You can use .serializeArray() to get the data in array format and then convert it into an object. like this:
function getFormData(formId) {
let formData = {};
let inputs = $('#'+formId).serializeArray();
$.each(inputs, function (i, input) {
formData[input.name] = input.value;
});
return formData;
}
Related
I am trying send my form fields along with an array of file objects through ajax call. I used the answer from this question to add/choose multiple files. This answer stores files in an array and sends the files as FormData Object, But in my code i have other forms fields also. I am sending those data from ajax using form.serialize() method. Now i have to send the array of file object together with my all the old data.
let files = []
this above array is array of file objects
So i tried this,
$('#myform').submit(function () {
var formData = new FormData();
files.forEach(file => {
formData.append('file', file);
});
$.ajax({
type: "POST",
url: url,
data: form.serialize() + "&filedata=" + formData,
...
...
})
}
I am using django in the backend, i receive like this,
request.POST.get('filedata')
But using this i receive filedata field as a string "[object FormData]".My question is how to send FormData together with form.serialize()
This is my html:
<form method="POST" action="/" id="myform">
<input type="text" name="name"/>
...
<input type="checkbox" id="option1"/>
<label for="option1">Option 1</label>
...
<select>
<option>Option 1</option>
<option>Option 2</option>
</select>
...
<!--like above checkbox and select elements i have so many other form fields-->
<!--i want to send files array with all the data from above form elements-->
<input id="myInput" type="file" name="files" multiple style="display:none" />
<button id="myButton" type="button">Add Files</button>
<!-- <button id="mySubmitButton" type="button">Upload Files</button> this button is not
required as i want upload files on clicking submit -->
<div id="myFiles"></div>
<input type="submit" />
</form>
I don't want to upload files on clicking upload files button,I want to upload files on clicking submit button together with my text field and files array
If this is not possible how can i send my form fields along with files array to backend?
$('#myform').submit(function () {
var formData = new FormData();
$.each($('#myform')[0].files, function(i, file) {
formData.append('file-'+i, file);
});
$.ajax({
type: "POST",
url: url,
data: formData,
cache: false,
contentType: false,
processData: false,
method: 'POST',
type: 'POST' // jQuery < 1.9
})
}
I have an image upload form which is submitted by a javascript but the file data is not being submitted. I have looked at examples of how to fix this with ajax but cannot find any examples that address it with the javascript submit that I am using.
<td>New Photo<br>
<div id="editphoto">
<form id="editphoto" enctype="multipart/form-data" method="post" action="editphoto.php">
<input type="hidden" name="employeeid" value="<?php echo $listing[$k]["employeeid"] ?>">
<input type="file" name="file2">
<input type="submit" value="Submit">
</form></div></td>
<script>
$('#editphoto form').submit(function(){
var data=$(this).serialize();
$.post('editphoto.php', data , function(returnData){
$('#editphoto').html( returnData)
})
return false; // stops browser from doing default submit process
});
</script>
Files cannot be serialized. You can use FormData To submit a file using jQuery.
$('#editphoto form').submit(function(){
var formData = new FormData();
formData.append('file2', $('input[type=file]')[0].files[0]);
// append other form-data to formData object
var otherData = $(this).serialize();
$.each( otherData , function(key, field){
formData.append(field.name, field.value);
});
// post form
$.ajax({
url: 'editphoto.php',
data: formData,
processData: false,
contentType: false,
type: 'POST',
success: function( returnData ) {
$('#editphoto').html( returnData)
}
});
return false; // stops browser from doing default submit process
})
When submitting forms, I ran across problems in getting POST data in my server-side PHP script. I narrowed it down to a little bit of JQuery/JavaScript that loads JSON data via AJAX into a DataTable.
The form is as follows:
<form class="form-horizontal" action="./scripts/lookup.php" method="post" role="form" id="lookupForm">
<div class ="form-group">
<label for="inputLookup" class="col-sm-2 control-label">Username</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="inputLookup" name="lookup_name" placeholder="John.Doe" required/>
</div>
</div>
<div class="form-group">
<div class="col-sm-10 col-sm-offset-2">
<input id="submitUserLookupBtn" name="submitUserLookup" type="submit" value="Lookup" class="btn btn-primary"/>
</div>
</div>
</form>
And then the script:
$("#lookupForm").submit(function (e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: './scripts/lookup.php',
dataType: 'json',
success: function(s) {
LUUTable.fnClearTable();
for(var i = 0; i < s.length; i++) {
LUUTable.fnAddData([
s[i][0],
s[i][1],
s[i][2],
s[i][3],
s[i][4],
s[i][5],
s[i][6],
s[i][7]
]);
}
},
error: function(e) {
if (e.responseText != '') {
console.log("Error: " + e.responseText);
} else {
console.log("Warning: No data to return.");
}
}
});
});
Whenever that code snippet is run, the PHP does not get POST data, however once I comment the script out, POST data is sent to the server. The problem, however, is that this code snippet is where I handle the JSON data returned by the server.
What could be the reason for this causing data not to POST, and how might I either further troubleshoot or mitigate this issue?
Much appreciated!
You are sending the data twice to the ./script/lookup.php
<form class="form-horizontal" action="./scripts/lookup.php" method="post" role="form" id="lookupForm">
and in the Ajax script. Change the above line to
<form class="form-horizontal" role="form" id="lookupForm">
Just keep the url, and type: post in the ajax call in the javascript.
Serialize your form data and send the values in your AJAX:
$("#lookupForm").submit(function (e) {
e.preventDefault();
var formValues = $(this).serialize(); // serialize the form data
$.ajax({
type: 'POST',
url: './scripts/lookup.php',
data: formValues, // send serailized form data here
dataType: 'json',
I'm trying to upload multiple images for an image upload system using AJAX on Jquery.
However, I'm having trouble getting the FormData object to take in the data from the file input. Here is my code:
HTML:
<form id="multiform" role="form" action="process.php" method="post" enctype="multipart/form-data">
<div class="form-group">
<div class="">
<label for="picture">Upload Pictures</label>
<input type="file" id="pic_upload_file" name="pics[]" multiple>
<input type="button" id="pic_upload" name="pic_upload" value="Upload">
</div>
</div>
</form>
JQuery
$('#pic_upload').click(function(e) {
var formData = new FormData();
formData.append("pics", file);
});
This object is created and I can see it in the console, but I dont know how to get the user file input data into it to send to a php script.
Can anyone help?
You have a file input that takes multiple files, so you have to get those files and append each one to the formData object
$('#pic_upload').on('click', function(e) {
var formData = new FormData(),
files = $('#pic_upload_file').get(0).files;
$.each(files, function(i, file) {
formData.append("pics_" + i, file);
});
$.ajax({
url : 'test.php',
data : formData,
contentType : false,
processData : false,
type : 'POST'
});
});
All I am trying to do is upload files using ajax to my CodeIgniter based website.But i cannot get file field value in controller.I am getting message like "Undefined index: 'file_1'"
How to solve this issue?
Form
<form method="post" enctype="multipart/form-data">
<input type="file" id="file_1" name="file_1" value="" class="field1" />
<input type="button" onclick="up_img()" value="Upload" />
</form>
Javascript:
<script type="text/javascript">
function up_img()
{
formdata = false;
var imgfile = document.getElementById("file_1");
formdata = new FormData();
formdata.append("file_1",imgfile.files[0]);
$.ajax({
url: "<?php echo base_url(); ?>index.php/save_project_upload/",
type: 'POST',
data: formdata,
processData: false,
contentType: false,
success: function (data) {
alert(data);
}
});
}
Controller:
function save_project_upload()
{
echo $upfile_name = $_FILES['file_1']['name'];
}
If you do a print_r( $_FILES ) are you getting any content?
Also, be aware that this is not supported by IE8 and earlier.
You could also try to do:
var formData = new FormData($('#yourformID')[0]);
EDIT:
formData.append('file_1', $('input[id="file_1"]')[0].files[0]);
Might also solve your problem, by adding [0] to the DOM element.