This may be duplicate but I can't solve it.
I can send multiple images by JQuery/Ajax to my server (Asp.Net Core) and save them successfully. But the problem is when I want to add the second batch files, the first batch will not append to form data. I add images with a button and not by input type="file" field.
HTML:
<form asp-area="User" asp-controller="Item" asp-action="Create" id="createForm" method="post" enctype="multipart/form-data" >
<input asp-for="ImageUrl" id="myInput" type="file" name="inputFile[]" accept="image/*" multiple style="display:none" />
<button id="myButton" type="button">+ Add Files</button>
JS:
$(document).ready(function () {
var inputFile = $('#myInput');
$('#myButton').click(function () {
$('#myInput').click();
});
var files = [];
$('#myInput').change(function () {
var newFiles = [];
for (var index = 0; index < inputFile[0].files.length; index++)
{
let file = inputFile[0].files[index];
files.push(file);
}
});
});
$("#createForm").submit(function (e) {
e.preventDefault();
var formData = new FormData(document.getElementById('createForm'));
//var formData = new FormData(this);
files.forEach(file => {
formData.append('file[]', file);
});
for (var pair of formData.entries()) {
console.log(pair[0] + ', ' + pair[1]);
}
$.ajax({
type: "POST",
cache: false,
processData: false,
contentType: false,
url: $("#createForm").attr('action'),
enctype: 'multipart/form-data',
data: new FormData(this),
});
});
});
Suppose I choose pictures 1,2,3 and submit my form and all 3 pictures save to server side successfully. Now let's try a new record: I add pictures 1,2,3, after that I choose pictures 4,5,6 so I expect to 6 images to be appended to form data. But only the last selection 4,5,6 are saved to server !
This is my console report in below.As you can see I have input-File[]=3 !! Something like I have no jquery and no ajax and just using pure HTML/Input Multiple file and I can upload only my last selections !!
But when I refresh my page and choose just 1,2,3 images (one selection only), I have input-File[]=3 and file[], [object File]=3 and every thing is good.
I tried data: new FormData() and data: formData and many other options on data parameter but no one could solve my problem :(
Update : ******************************:
Case 1:
var formData = new FormData(document.getElementById('createForm'));
. . .
data: formData,
Results: No image save in server and ImageUrl is null in database.
Case 2:
var formData = new FormData()
. . .
data: formData,
Results in error in console : XML Parsing Error: no root element found
Case 3:
var formData = new FormData(this)
. . .
data: formData,
Results : suppose I select images 1,2,3 at first and then select images 4,5,6. I have images 1,2,3,4,5,6 saved on server and 4,5,6 save twice !! I'm getting near but still can't manage it.
.
I think there might be an error in the way that you copied your code. There is an extra }); after $('#myInput').change(function () { ... });
I'm assuming that is not part of the issue and was just a mistake in pasting it over.
The issue I think is that you were trying to send the files over separately from the inputFiles. Updating the for loop in the submit event handler should give you what you are wanting.
$("#createForm").submit(function (e) {
e.preventDefault();
var formData = new FormData();
files.forEach((file) => {
formData.append('inputFile[]', file);
});
for (var pair of formData.entries()) {
console.log(pair[0] + ', ' + pair[1]);
}
$.ajax({
type: "POST",
cache: false,
processData: false,
contentType: false,
url: $("#createForm").attr('action'),
enctype: 'multipart/form-data',
data: formData,
});
});
Related
I have a form with id: formC, on submit i call ajax:
var datiForm = new FormData();
var pos = [];
var i = 0;
posizioni.each(function () {
if($(this).find("input[type=checkbox]").is(":checked")){
pos[i] = $(this).find("input[type=checkbox]").data("id");
i++;
}
});
datiForm.append("nome",nome.val());
datiForm.append("cognome",cognome.val());
datiForm.append("email",email.val());
datiForm.append("telefono",telefono.val());
datiForm.append("dataNascita",dataNascita.val());
datiForm.append("titolo",titolo.val());
datiForm.append("ruolo",ruolo.find(":selected").data("ruolo"));
datiForm.append("sede",sede.find(":selected").data("sede"));
datiForm.append("posizione",pos);
datiForm.append("cvFile",$("#cvFile")[0].files[0]);
$.ajax({
type: "POST",
data: {datiForm: datiForm},
url: "saveCandidate.php",
processData: false,
contentType: false,
success: function (data) {
console.log(data);
},
error: function (data) {
var position = data;
}
});
I have a problem, on server $datiForm = $_POST["datiForm"]; is null why?
Moreover i have input file where i can select file pdf. I put it in FormData:
datiForm.append("cvFile",$("#cvFile")[0].files[0]);
Now on server i want to take file from $datiForm and save it into mysql as Blob is possible?
You specified the data field incorrectly, it should be just the form data object
data: datiForm,
also the way you add posizione is not going to work, each entry in yrh array has to be added individually
posizioni.each(function () {
if($(this).find("input[type=checkbox]").is(":checked")){
datiForm.append("posizione["+i+"]", $(this).find("input[type=checkbox]").data("id"));
i++;
}
});
Now on server i want to take file from $datiForm and save it into mysql as Blob is possible?
Yes
You'll need to specify the 'contentType' attribute to 'multipart/form-data' in order to upload files.
I have a form inside a modal box of a bootstrap theme. The form contains few input fields and a Dropzone field, all of which sends the data across to the server through ajax. After filling the form, I, obviously need to reset the form for next set of inputs. I have managed to successfully reset the form fields, EXCEPT the Dropzone image.
So now when I click submit, after filling the form, the data is entered. On clicking the button to open the modal again to add a new set, the previous image is still shown there. I need that also to be gone.
I kept searching for a solution on S.O and many other places. I couldn't get a solution. Any guidance is appreciated.
HTML:
<form enctype="multipart/form-data" id="addProductImageForm" class="dropzone dz-clickable" action="#">
<div class="dz-default dz-message" ><span>Click here to upload Product Image</span></div>
</form>
JS:
Dropzone.options.addProductImageForm = {
paramName: "productImage",
maxFilesize: 2,
maxFiles: 1,
uploadMultiple: false,
acceptedFiles: "image/*",
dictDefaultMessage: "Click to Upload",
addRemoveLinks: true,
accept: function(file, done) {
if (file.name == "bg.png") {
done("Naha, you don't.");
}
else {
done();
}
},
success: function(d, response, test) {
var value = response.replace("int(0)", "");
var value2 = value.replace(/(\r\n|\n|\r)/gm, "");
$('#product_imageName').val(value2);
},
init: function() {
this.on("maxfilesexceeded", function(file) {
alert("No more files please!");
});
}
};
$("#addProductImageForm").dropzone({url: "/path/to/upload_product_image.php"});
.
.
.
.
var formData = {
(input values here)
};
$.ajax({
type: 'POST',
url: 'path/to/projectsAction.php',
data: formData,
encode: true
})
.done(function(data) {
var value3 = data.replace(/(\r\n|\n|\r)/gm, "");
$('#project_productId').append('<option value="' + value3 + '" selected="selected">' + formData.product_name + '</option>');
$("#addProductForm").find("input[type=text], textarea, select").val("");
$("#addProductImageForm").html("");// THIS IS THE LINE THAT REMOVES THE THUMBNAIL. (From the answer given by xrcwrn)
$('.close').click();
});
event.preventDefault();
If you are using dropzone like
<form action="/file-upload"
class="dropzone"
id="my-awesome-dropzone"></form>
after posting your data reset your dropzone container like
$("#my-awesome-dropzone").html("");
I'm trying to remove an element from the database.
I don't know why, but the data is not getting to the url i inserted.
this is the code (the obj is indeed faded - only in the client side):
$(document).on("click", "#deleteAdmin", function(e) {
$.ajax({
url: "admin/adminProccess.php",
type: "get",
data: $('#idPriv:checked').serialize() + '&str=' + 'deleteAdmin',
success: function(data) {
$('#idPriv:checked').each(function(){
$(this).parent().parent().remove();
});
var item = $(deleteAdmin);
item.fadeOut();
}
});
});
is there something wrong in my code?
when i'm trying to access manually to the url i can see some results - but with my code its not sending the data.
any ideas?
edit: this is my idPriv:
<input type = "checkbox" name="idPriv[]" id="idPriv" onclick="evaluateIT(this)" data-related-item="adminPanelShow" value ="<?php echo $value["id"].':'. $count; ?>" />
Try to change:
$('#idPriv:checked').serialize() + '&str=' + 'deleteAdmin'
to:
$('#idPriv:checked').val() + '&str=' + 'deleteAdmin'
Trying to send (with ajax,json) data from file No1 to file No2 and then from file No2 send data to file No1
Here is code in file No1
HTML
<div id="first_var">1 one</div>
<div id="second_var">2 two</div>
<div id="load"></div>
Ajax
$(document).ready(function(){
var one = $("#first_var").val();
var two = $("#second_var").val();
var dataString = 'one='+first_var+'&two='+second_var;
$.ajax({
type: "POST",
url: 'fileNo2.php',
data: dataString,
dataType: "json",
success: function(data) {
$('#load').html(data);
}
});
Here is file No2
$p_one = $_POST['p_one'];
$p_two = $_POST['p_two'];
$test = $p_one. '<br>test<br>'. $p_two;
echo json_encode($test);
As a result in <div id="load"></div> see only word test
If instead of data: dataString, use data : { p_one: 'test 1', p_two: 'test 2' }, then everything works.
Possibly incorrectly definied var one etc? Seems var one = $("#first_var").val(); val() can be used if <div id="first_var">1 one</div> would be input field. But if it is not input field? Simply text inside id="first_var....
Please, advice.
You just need to name the keys correctly in the data string. The PHP script is expecting "p_one" and "p_two", not "one" and "two".
var dataString = 'p_one='+first_var+'&p_two='+second_var;
Also, you need .text(), not .val() to get the inner text:
var one = $("#first_var").text();
I am developing a mobile site using asp.net and jquery. no plugin. just simple jquery.I am using the
<input type="file"/>
of HTML5.
So few questions to get the big picture:
1.Can i load files without jquery plugin, but only simple jquery? Just picking the file, send it using ajax and catch it on server side?
2. I have noticed the Request.Files attribute of the Request object. Will it get filled only with post of the whole page or can i get my files there using Ajax?
3.In case the answer in 2 is "No!", how do i exclude the files data on the server side?
Thanks
This is the solution i have found:
JS:
<script type="text/javascript">
$(document).ready(function () {
$('#inputFile').on('change', function () {
var file = this.files[0];
var name = file.name;
var size = file.size;
var type = file.type;
var formData = new FormData();
formData.append(file.name, file)
$.ajax({
url: 'AjaxPage.aspx',
dataType: 'script',
cache: false,
contentType: false,
processData: false,
data: formData,
type: 'post',
success: function (response) {
alert(response);
},
error: function (e) {
alert(e);
}
});
});
});
</script>
CS: (On ajax page to catch the files and manipulate them as you will)
var files = Request.Files;
HTML:
<body>
<div>
<input type="file" id="inputFile" />
</div>
</body>