Ajax form sending file one after another - html

I have a form that I sending with ajax.
in this form there's x input file and each of them have 2 input text.
when i send the form all of the files are sent at the same times.
so what i want to do is sending one file at time with his 2 input text.
there's my code :
HTML
<div id="img_upload">
<form action="#" id="form" method="POST" enctype="multipart/form-data">
<div id="img_upload_head">
<?php
require MODULE.DS."galerie".DS."traitement".DS."galerie".DS."recup.php";
?>
<label for="nbImg">Selectionner le nombre d'image que vous voulez inserrer : </label>
<select name="nbImg">
<?php $nb = 10;
for ($i= 0; $i<=$nb; $i++){
?>
<option name="<?php echo $i;?>"><?php echo $i;?></option>
<?php
}
?>
</select>
</div>
<div id="img_upload_content">
<div id="content_head">
<div class="title_name">Selection fichier</div>
<div class="title_desc">Description</div>
<div class="title_price">Prix</div>
<div class="title_error">status</div>
</div>
<div id="content_list">
</div>
</div>
<div id="img_upload_foot">
<input type="submit" name="send" value="send" id="send" />
</div>
</form>
js
$(document).ready(function(){
$("select[name=nbImg]").hide();
$("#send").hide();
$("select[name=gal]").change(function(){
var galSelect = $(this).val();
if (galSelect != "none"){
$("select[name=nbImg]").fadeIn("fast");
$("select[name=nbImg]").change(function(){
var selfElem = $(this);
var nbImg = selfElem.val();
$("#content_list").empty();
for (var i = 1; i <= nbImg ; i++){
$("#content_list").append("<p id=\"file#"+i+"\"><span class=\"name\"><input type=\"file\" name=\"img[]\"id=\"img\" /></span><span class=\"desc\"><input type=\"text\" id=\"desc\" name=\"desc\" /></span><span class=\"price\"><input type=\"text\" id=\"price\" name=\"price\" /></span><span class=\"error\"></span></p>");
}
$("#send").fadeIn("fast");
$("#send").click(function(e){
e.preventDefault();
var form = $(this).parents("form");
var p = form.find("p");
var action = "/module/galerie/traitement/traitimg.php";
var desc = form.find("input[name=desc]").val();
var gal = $("select[name=gal]").val();
var price = form.find("input[name=price]").val();
var formData = new FormData();
jQuery.each($(p).find('input[name^="img"]')[0].files, function(i, file) {
formData.append('img-'+i, file);
formData.append('desc', desc);
formData.append('price', price);
formData.append('gal', gal);
jQuery.ajax({
url :action,
type : "POST",
processData: false,
contentType: false,
data: formData,
success: function(formData){
}
});
});
return false;
});
});
}else{$("select[name=nbImg]").fadeOut("fast");}
});
i don't really know if it's possible to do so.
Anyway thanks for the help you can provide me
EDIT
So i tried this
for (var i = 1; i <= nbImg; i++){
jQuery.each($(p).find('input[name^="img"]')[0].files, function(i, file) {
var formData = new FormData();
formData.append('img-'+i, file);
formData.append('desc', desc);
formData.append('price', price);
formData.append('gal', gal);
jQuery.ajax({
beforeSend : function(){
$(".error").empty().append("<img src=\"/media/design/img/loader.gif\"/>");
},
url :action,
type : "POST",
processData: false,
contentType: false,
data: formData,
success: function(formData){
$(".error").empty().append("<img src=\"/media/design/img/v.png\"/>");
}
});
});
}
It's sending all the file at the same time and when i remove the "for" loop it'll send just the first one
jQuery.each($(p).find('input[name^="img"]')[0].files, function(i, file) {
var formData = new FormData();
formData.append('img-'+i, file);
formData.append('desc', desc);
formData.append('price', price);
formData.append('gal', gal);
jQuery.ajax({
beforeSend : function(){
$(".error").empty().append("<img src=\"/media/design/img/loader.gif\"/>");
},
url :action,
type : "POST",
processData: false,
contentType: false,
data: formData,
success: function(formData){
$(".error").empty().append("<img src=\"/media/design/img/v.png\"/>");
}
});
});

Related

Trying to upload multiple images but its not uploading [duplicate]

I am using this following code, where user can upload one or multiple files and can delete those files. All the data is stored in form_data.
Untill now I am not able to make the file upload functionality working.
index.php
<input id="avatar" type="file" name="avatar[]" multiple />
<button id="upload" value="Upload" type="button">upload</button>
<div class="preview">
</div>
<div class="return_php"></div>
<script src="https://code.jquery.com/jquery-3.1.0.min.js"></script>
<script>
$(document).ready(function () {
var form_data = new FormData();
var number = 0;
/* WHEN YOU UPLOAD ONE OR MULTIPLE FILES */
$(document).on('change', '#avatar', function () {
console.log($("#avatar").prop("files").length);
len_files = $("#avatar").prop("files").length;
for (var i = 0; i < len_files; i++) {
var file_data = $("#avatar").prop("files")[i];
form_data.append(file_data.name, file_data);
number++;
var construc = '<img width="200px" height="200px" src="' +
window.URL.createObjectURL(file_data) + '" alt="' + file_data.name + '" />';
$('.preview').append(construc);
}
});
/* WHEN YOU CLICK ON THE IMG IN ORDER TO DELETE IT */
$(document).on('click', 'img', function () {
var filename = $(this).attr('alt');
var newfilename = filename.replace(/\./gi, "_");
form_data.delete($(this).attr('alt'))
$(this).remove()
});
/* UPLOAD CLICK */
$(document).on("click", "#upload", function () {
$.ajax({
url: "upload.php",
dataType: 'script',
cache: false,
contentType: false,
processData: false,
data: form_data, // Setting the data attribute of ajax with form_data
type: 'post',
success: function (data) {
$('.return_php').html(data);
}
})
})
});
</script>
upload.php
<?php
//upload.php
var_export($_FILES); // this final output that i want to upload
?>
HTML
<div class="col-md-6" align="right">
<label>Select Multiple Files</label>
</div>
<div class="col-md-6">
<input type="file" name="files" id="files" multiple />
</div>
<div style="clear:both"></div>
<br />
<br />
<div id="uploaded_images"></div>
JavaScript
$('#files').change(function(){
var files = $('#files')[0].files;
var error = '';
var form_data = new FormData();
for(var count = 0; count<files.length; count++)
{
var name = files[count].name;
var extension = name.split('.').pop().toLowerCase();
if(jQuery.inArray(extension, ['gif','png','jpg','jpeg']) == -1)
{
error += "Invalid " + count + " Image File"
}
else
{
form_data.append("files[]", files[count]);
}
}
if(error == '')
{
$.ajax({
url:"url",
method:"POST",
data:form_data,
contentType:false,
cache:false,
processData:false,
beforeSend:function()
{
$('#uploaded_images').html("<label class='text-success'>Uploading...</label>");
},
success:function(data)
{
$('#uploaded_images').html(data);
$('#files').val('');
}
})
}
else
{
alert(error);
}
});
Not same as your question but you can try like this.
Here is your working code.
There were several problem with your code
Incorrect brace closing in ajax call.
Your name field in form data was invalid
You were requesting form_data as index in the $_FILES array
No use of number variable
index.php
<input id="avatar" type="file" name="avatar[]" multiple="multiple"
/>
<button id="upload" value="Upload" type="button">upload</button>
<div class="preview">
</div>
<div class="return_php"></div>
<script src="https://code.jquery.com/jquery-3.1.0.min.js" ></script>
<script>
$(document).ready(function(){
var form_data = new FormData();
/* WHEN YOU UPLOAD ONE OR MULTIPLE FILES */
$(document).on('change','#avatar',function(){
$('.preview').html("");
len_files = $("#avatar").prop("files").length;
for (var i = 0; i < len_files; i++) {
var file_data = $("#avatar").prop("files")[i];
form_data.append("avatar[]", file_data);
var construc = '<img width="200px" height="200px" src="' + window.URL.createObjectURL(file_data) + '" alt="' + file_data.name + '" />';
$('.preview').append(construc);
}
});
/* WHEN YOU CLICK ON THE IMG IN ORDER TO DELETE IT */
$(document).on('click','img',function(){
var filename = $(this).attr('alt');
var newfilename = filename.replace(/\./gi, "_");
form_data.delete($(this).attr('alt'));
$(this).remove();
});
/* UPLOAD CLICK */
$(document).on("click", "#upload", function() {
$.ajax({
url: "upload.php",
dataType: 'image/png',
cache: false,
contentType: false,
processData: false,
data: form_data, // Setting the data attribute of ajax with form_data
type: 'post',
success: function(data) {
//console.log("data")'
}
});
});
});
</script>
upload.php
<?php
//upload.php
$output = '';
if(is_array($_FILES) && !empty($_FILES['avatar']))
{
foreach($_FILES['avatar']['name'] as $key => $filename)
{
$file_name = explode(".", $filename);
$allowed_extension = array("jpg", "jpeg", "png", "gif");
if(in_array($file_name[1], $allowed_extension))
{
$new_name = rand() . '.'. $file_name[1];
$sourcePath = $_FILES["avatar"]["tmp_name"][$key];
$targetPath = "uploads/".$new_name;
move_uploaded_file($sourcePath, $targetPath);
}
}
$images = glob("uploads/*.*");
foreach($images as $image)
{
$output .= '<div class="col-md-1" align="center" ><img src="' . $image .'" width="100px" height="100px" style="margin-top:15px; padding:8px; border:1px solid #ccc;" /></div>';
}
echo $output;
}
?>

How to count from 1 when remove a row ajax?

I have to make a functionality that users can add and remove rows with input fields. Problem is that I need a row index (number) in front of each row incorrect order(1., 2., 3. etc.) also when one or more rows are removed and then added again. I can add rows but I can`t get the counting right because If I remove them then the count starts with 4 but I need 1 or if the second row gets removed then I need 2 instead of 4.
I have made it with append() and so far so good but I also need row cont in front of each row. I have a counter but let's say I add 1 row and it gives numbers 1 and 2. If I remove the second row and add another again, now the count is 1 and 3
Note that the "add" button is only one and separated from append();
I have three lines that are 1, 2, and 3, respectively
Now I will delete one of them. For example, I delete row number 2. I see this demo,
This should not happen. It should show the numbers 1 and 2, respectively.
<script>
$(document).ready(function() {
$('#educationalForm').submit(function(event){
event.preventDefault();
var formData = new FormData($('#educationalForm')[0]);
$.ajax({
url:'{{ route('educational.store') }}',
method: 'POST',
data: formData,
cache:false,
contentType: false,
processData: false,
success:function(data){
const variables = ['grade', 'major', 'end'];
variables.forEach(variable => {
if(data[variable] === null) data[variable] = '';
});
const newRowNum = $('#educationalForm tr').length + 2;
let html = '' +
'<tr>'+
'<td class="fw-normal" id="demo">'+ (newRowNum) +'</td>'+
'<td class="fw-normal">'+data.grade+'</td>'+
'<td class="fw-normal">'+data.major+'</td>'+
'<td class="fw-normal">'+data.end+'</td>'+
'<td>'+
'<form method="post" id="educational-destroy">'+
'#csrf'+
'#method('DELETE')'+
'<div class="btn-group">'+
'<a data-id="'+data.id+'" class="btn btn-info btn-sm" id="educationalEdit" data-bs-toggle="modal" data-bs-target="#educationalModal">ویرایش</a>'+
'<button data-id="'+data.id+'" type="button" class="btn btn-danger btn-sm" id="educationalDestroy">حذف</button>'+
'</div>'+
'</form>'+
'</td>'+
'</tr>';
$('#educationalTable').append(html);
$('#educationalForm').trigger('reset');
},
});
});
showEducationals();
function showEducationals() {
$.get('{{ route('educational.index') }}', function (data) {
$('#educationalTable').html("");
$.each(data, function (key, val) {
const variables = ['grade', 'major', 'end'];
variables.forEach(variable => {
if(val[variable] === null) val[variable] = '';
});
$('#educationalTable').append('<tr>'+
'<td class="fw-normal">'+ (key+1) +'</td>'+
'<td class="fw-normal">'+val.grade+'</td>'+
'<td class="fw-normal">'+val.major+'</td>'+
'<td class="fw-normal">'+val.end+'</td>'+
'<td>'+
'<form method="post" id="educational-destroy">'+
'#csrf'+
'#method('DELETE')'+
'<div class="btn-group">'+
'<a data-id="'+val.id+'" class="btn btn-info btn-sm" id="educationalEdit" data-bs-toggle="modal" data-bs-target="#educationalModal">ویرایش</a>'+
'<button data-id="'+val.id+'" type="button" class="btn btn-danger btn-sm" id="educationalDestroy">حذف</button>'+
'</div>'+
'</form>'+
'</td>'+
'</tr>'
);
});
});
}
$(document).on('click', '#educationalEdit', function(event) {
event.preventDefault();
var id = $(this).data('id');
$.ajax({
type:'get',
url:'/educational/'+id+'/edit',
contentType: "application/json; charset=utf-8",
dataType: "json",
success:function (data) {
console.log(data);
$('#id').val(data.educational.id);
$('#edit_grade').val(data.educational.grade);
$('#edit_major').val(data.educational.major);
$('#edit_avg').val(data.educational.avg);
$("input[name='edit_start']").val(data.educational.start);
$("input[name='edit_end']").val(data.educational.end);
$('#edit_docPlaceName').val(data.educational.docPlaceName);
$('#edit_thesisTitle').val(data.educational.thesisTitle);
$('#edit_docPlaceCountry').val(data.educational.docPlaceCountry);
$('#edit_docPlaceCity').val(data.educational.docPlaceCity);
},
});
});
$(document).on('click', '#educationalUpdate', function(event) {
event.preventDefault();
var id = $('#id').val();
var file = $('#edit_upload_doc').prop('files')[0];
var formData = new FormData($('#educationalFormUpdate')[0]);
formData.append('file', file);
$.ajax({
type: 'POST',
url: '/educational/'+id,
dataType: 'JSON',
data: formData,
cache: false,
contentType: false,
processData: false,
success: function (response) {
console.log(response);
$('#educationalModal').modal('hide');
showEducationals();
},
});
});
$(document).on('click', '#educationalDestroy', function(event) {
event.preventDefault();
$.ajax({
url:'educational/'+$(this).data('id'),
type: 'DELETE',
dataType: 'json',
data: {
_token: '{{ csrf_token() }}'
},
success: function(response) {
$('#educationalsTable').html('');
showEducationals();
},
error: function(response) {
console.log(response);
},
});
});
});
</script>
So in general I can get counting right until elements are getting removed. If I got 3 rows I got a count of 1. 2. 3. but if I remove all of them and add again 3 rows I got 4. 5. 6. BUT I need 1. 2. 3. again
You should reset the counter every time you re-render the whole table.
You could move the count to inside your rendering function, but it is not strictly necessary, because jQuery's each function already provides an index (you are naming it key) which you could use instead of count.
Therefore, you can do:
function showEducationals() {
$.get('{{ route('educational.index') }}', function (data) {
$('#educationalTable').html("");
$.each(data, function (key, val) {
const variables = ['grade', 'major', 'end'];
variables.forEach(variable => {
if(val[variable] === null) val[variable] = '';
});
$('#educationalTable').append('<tr>'+
'<td class="fw-normal">'+ (key+1) +'</td>'+ // using key instead of count
Notice I also removed id=demo. This is because you are creating several cells with the id=demo (in '<td class="fw-normal" id="demo">'+count+++'</td>'+) and ideally ids should be unique.
About adding new rows use, instead of i, the number of rows the table actually has:
$('#educationalForm').submit(function(event){
event.preventDefault();
var formData = new FormData($('#educationalForm')[0]);
$.ajax({
url:'{{ route('educational.store') }}',
method: 'POST',
data: formData,
cache:false,
contentType: false,
processData: false,
success:function(data){
const variables = ['grade', 'major', 'end'];
variables.forEach(variable => {
if(data[variable] === null) data[variable] = '';
});
const newRowNum = $('#educationalTable tr').length + 1; // added this
let html = '' +
'<tr>'+
'<td class="fw-normal">'+ (newRowNum) +'</td>'+ // edited this
In addition, you should remove the i and count variables, as they are no longer necessary:
showEducationals();
let i; // remove this
let count = 1; // remove this
function showEducationals() {
// ...
);
i = count // remove this
});

How to Sort XML feed alphabetically

I'm trying to sort an XML feed alphabetically by "LastName" without creating an XSLT template, I have the below code, but it returns and error.
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$.ajax({
type: "GET",
url: "https://cors-anywhere.herokuapp.com/https://showcast.com.au/showcast/webservice/actors.aspx?agencyId=&Password=",
dataType: "xml",
success: parseXml
});
});
function parseXml(xml){
$(xml).find("artist").each(function(){
var nx_name = $(this).find("FirstName").text() + ' ' + $(this).find("LastName").text();
var nx_pic = '';
$(this).find("Photos SmallPhotos Photo").each(function(){
if( $(this).find("IsDefault").text() == "True" ){
nx_pic = $(this).find("Url").text();
return false;
}
});
var nxlink = $(this).find("URLlink").text();
var nxhtml = '<div class="nxitem"><div class="nxwrap"><div class="nximgwrap"><img src="'+nx_pic+'"></div></div><br/><span class="nxname">'+nx_name+'</span></div>';
$("#nxdisplay").append(nxhtml);
});
}
</script>

How to use 'TouchStart' events in Jquery Mobile

In Html5:- in footer it will store the data which is cuming dynamically and footer part should move by touch not whole window only footer should move with the data is present in footer left to right
<div data-role="page" id="page1">
<div data-role="footer" data-position="fixed" id="footer">
<div class="menu" id="menu_button1" id="scroll_menu" onmouseover='this.style["overflowX"]="scroll";' onmouseout='this.style["overflowX"]="visible";'></div>
</div>
</div>
In Jquery:- I am using Ajax calling to get the data dynamically in stored that data in footer part of Htm5 in there i want to use touch event how i can use plz help me out
function callMenuConnection() {
$.support.cors = true;
$.ajax({
type: "POST",
url: "one.html",
contentType: "text/xml",
dataType: "xml",
data: "",
cache:false,
processData:false,
crossDomain:true,
success: processSuccess,
error: processError
});
}
function processSuccess(data) {
$(data).find("category").each(function () {
var id = $(this).find('id').text();
var title = $(this).find('title').text();
var scripts = "<a href='#' data-role='button' data-theme='b' data-inline='true'>"+title+"</a>"
$("#menu_button1").append(scripts).trigger('create');
});
}
function processError(data)
{
alert("error");
}
$(document).unbind('pageinit').bind('pageinit', function () {
callMenuConnection();
});
Finally i got the answer of these
In HTML5:-
<div data-role="page" data-theme="b" id="jqm-home">
<div data-role="footer" data-position="fixed" data-theme="c">
<div class="categories" id="cat">
<ul id="cat_list" class="cat_list_class"></ul>
</div>
</div>
</div>
In jquery:-
var step = 1;
var current = 0;
var maximum = 0;
var visible = 2;
var speed = 500;
var liSize = 120;
var height = 60;
var ulSize = liSize * maximum;
var divSize = liSize * visible;
$(document).unbind('pageinit').bind('pageinit', function () {
callMenuConnection();
$('.categories').css("width", "auto").css("height", height+"px").css("visibility", "visible").css("overflow", "hidden").css("position", "relative");
$(".categories ul a").css("list-style","none").css("display","inline");
$(".categories ul").css("width", ulSize+"px").css("left", -(current * liSize)).css("position", "absolute").css("white-space","nowrap").css("margin","0px").css("padding","5px");
});
$(document).unbind('click').bind('click', function () {
scroll();
});
function callMenuConnection() {
$.support.cors = true;
$.ajax({
type: "GET",
url: "one.html",
contentType: "text/xml",
dataType: "xml",
data: "",
cache:false,
processData:false,
crossDomain:true,
success: processSuccess,
error: processError
});
}
var scripts ="";
function processSuccess(data) {
$(data).find("category").each(function () {
var id = $(this).find('id').text();
var title = $(this).find('title').text();
scripts = scripts+'<a class="ids_cat" data-role="button" data-transition="slide" data-inline="true" >' +title+ '</a>';
});
$('#cat_list').append(scripts);
$('#cat_list').trigger('create');
maximum = $(".categories ul a").size();
}
function processError(data)
{
alert("error");
}
function scroll(){
$(".categories").swipeleft(function(event){
if(current + step < 0 || current + step > maximum - visible) {return; }
else {
current = current + step;
$('.categories ul').animate({left: -(liSize * current)}, speed, null);
}
return false;
});
$(".categories").swiperight(function(event){
if(current - step < 0 || current - step > maximum - visible) {return; }
else {
current = current - step;
$('.categories ul').animate({left: -(liSize * current)}, speed, null);
}
return false;
});
}
Please use swipe event on the footer selector. Something like :
// Temp Id Card back page swipe event
$("#FooterId").on('swipe', function (e) {
// keep changing the data here in some div, it would give illusion that footer is changing...
});

jQuery POST refreshing the page

I have some jQuery that takes the value of a text input and puts it into a MySQL database. However, when the jQuery runs, the page refreshes and the variables in the form appear in the URL almost as GET variables. However, none of the variables are GET. Ideally, I would like the page not to refresh.
jQuery:
$('.commentBox').keypress(function(e) {
if(e.which == 13) {
if ($.trim($(this).val()) == ""){
$('#nocomment').modal('show');
}
else {
var form = $(this).siblings('.commentForm');
var commentbox = $(this).val();
$.ajax({
type: "POST",
url: "../comment",
data: form.serialize(),
success: function(){
commentbox.val('');
form.siblings('.commentContainer').append(response);
}
});
}
}
});
HTML (echoed from PHP):
<form class='commentForm'>
<input type='hidden' name='record_id' value='$answerid[$f]' />
<input type='hidden' name='question_id' value='$q' />";
<input type='text' class='commentBox' placeholder='...comment' name='comment' autocomplete='off' />";
</form>
You have to either return false or prevent default, which will stop the form from submitting:
$('.commentBox').keypress(function(e)
{
if(e.which == 13)
{
e.preventDefault(); // <-- This will stop the form from submitting.
if ($.trim($(this).val()) == "")
{
$('#nocomment').modal('show');
}
else
{
var form = $(this).closest('.commentForm');
var commentbox = $(this).val();
$.ajax({
type: "POST",
url: "../comment",
data: form.serialize(),
success: function(){
commentbox.val('');
form.siblings('.commentContainer').append(response);
}
});
}
}
});
You need to prevent the default action from taking place when hitting the enter key, which is form submission via GET.
e.preventDefault();
$( '.commentBox' ).keypress(function( e ) {
if( e.which === 13 ) {
// Prevent the default only when it's the enter key
e.preventDefault();
if ( $.trim($(this).val()) === '' ){
$('#nocomment').modal( 'show' );
}
else {
var form = $( this ).siblings( '.commentForm' );
var commentbox = $( this ).val();
$.ajax({
type: "POST",
url: "../comment",
data: form.serialize(),
success: function(){
commentbox.val( '' ;
form.siblings( '.commentContainer' ).append( response );
}
});
}
}
});