I am trying to upload an image to database from html page in a form in a modal through php & ajax,but it doesn't work i don't know why,anyone can help me?
HTML Page
<form method="post" enctype="multipart/form-data">
<div class="row">
<div class="col-sm-4">
<label class="Modallabel">Photo:</label>
</div>
<div class="col-sm-8">
<div class="input-group input-group-sm" style="margin-top: -5px;">
<input type="file" id="fileUpload" name="fileUpload" style="color: #ffffff;"/>
</div><br>
</div>
</div>
</form>
<button type="button" class="btn btn-success btn-md" style="margin:0;width: 75px;" onclick="AddNewCustomer()">Add</button>
Javascript Function
function AddNewCustomer()
{
//Image upload
$(document).ready(function()
{
$(document).on('change', '#fileUpload', function() //NOT WORKING HERE
{
var property = document.getElementById("fileUpload").files[0];
var image_name = property.name;
var image_extension = image_name.split('.').pop().toLowerCase();
if (jQuery.inArray(image_extension, ['gif','png','jpg','jpeg']) == -1)
{
alert("invalid Image File");
}
var image_size = property.size;
if(image_size > 2000000)
{
alert("Image File Size is very big");
}
else
{
var form_data = new FormData();
form_data.append("fileUpload", property);
$.ajax
({
type:"POST",
url:"addNewCustomer.php",
processData: false,
cache: false,
contentType: false,
data:
{
'form_data':form_data
},
success: function(data){
if (data == "Success!")
{
sweetAlert("Data entered successfully!");
}
else if(data == "Exist")
{
sweetAlert("","Customer already exists!","error");
return false;
}
},
error: function(jqXHR, textStatus, errorThrown) {
console.log('ERROR', textStatus, errorThrown);
}
})
}
})
})
}
change event would be attached after click at <button> at onclick="AddNewCustomer().
You can remove AddNewCustomer function and call change on #fileUpload element at click of .btn element.
$(document).ready(function() {
$(document).on('change', '#fileUpload', function() {//do stuff})
$(".btn").on("click", function() {
$("#fileUpload").trigger("change");
});
});
You want to upload the image immediately after it's chosen, but you only run the function when the 'Add' button is clicked.
You need to take your change code out of the function, or invoke the function when the page is loaded to add the listeners to the form.
Related
have a button click in a form and have required validation when clicking on that button. I put in
if (!formHandle.valid()) { return; }
in the global site.js file where I want that event to fire first before the event for the actual button. Currently the jquery for the actual button fires first before the global jquery. How can I make sure that the global jquery fires first or is this even possible?
html
<p id="vote-status" class="card-text forum-blue">
#{if (#Model.VoteId != 0)
{
<text>
<br /Text.
<br />Text
</text>
}
else
{
<text><br />Text.</text>
}
}
</p>
#{
if (Model.AvailableVotingOptions != null)
{
#Html.DropDownListFor(m => m.VotingOptionId,
Model.AvailableVotingOptions,
"- Please select -",
new { #class = "form-control", #id = "voting-options" })
}
}
<div class="card-footer">
<div class="row">
<div class="col-sm-12 col-md-3 col-lg-3">
<button type="button"
class="btn btn-success btn-sm col-sm-12"
id="button"
data-action="submit">
<i class="fas fa-vote-yea fa-fw"></i>
#if (#Model.VoteId != 0)
{
<text>Re-Cast Vote</text>
}
else
{
<text>Vote</text>
}
</button>
</div>
</div>
</div>
Site.js (event I want to hit first)
$(document).on("click",
'[data-action="submit"]',
function (e) {
var formHandle = $(this).closest('form');
if (!formHandle.valid()) {
return;
}
if (formHandle.valid()) {
blockUI();
}
});
Document.js
$(document).on("click",
'#button',
function (e) {
e.preventDefault();
var post_url = $("#form-vote").attr("action"); //get form action url
var request_method = $("#form-vote").attr("method"); //get form GET/POST method
var form_data = $("#form-vote");
$.ajax({
url: post_url,
type: request_method,
data: form_data.serialize(),
processData: false,
async: true
}).done(function (objOperations) {
if ($("#validation-error")[0].textContent.trim() === "") {
ShowVoteStatus(true, "Your document is submitted successfully.");
}).fail(function (error) {
ShowVoteStatus(false,
"Your document was not submitted successfully.");
}).always(function (jqXHR, textStatus) {
$.unblockUI();
});;
});
https://codepen.io/bootsy1974/pen/ExggoQg
why do different functions? you can make a check before sending in the second function.
if its possible and this same one button
if its not possible to try after validation use
$("#button").trigger("click");
$(document).on("click",
'[data-action="submit"]',
function (e) {
e.preventDefault();
var formHandle = $(this).closest('form');
if (!formHandle.valid()) {
return;
}
if (formHandle.valid()) {
blockUI();
$("#button").trigger("click");
}
});
but formHandle.valid is not a function
need changed '#button' from button and created another element to binding this function. in another to try sending without validation. need do dependeces sending from validating. but you have to parallel working.
<div class="col-sm-12 col-md-3 col-lg-3">
<div id="button"></div>
<button type="button"
class="btn btn-success btn-sm col-sm-12"
data-action="submit">
<i class="fas fa-vote-yea fa-fw"></i>
#if (#Model.VoteId != 0)
{
<text>Re-Cast Vote</text>
}
else
{
<text>Vote</text>
}
</button>
</div>
and this have not '}'
$(document).on("click",
'#button',
function (e) {
e.preventDefault();
var post_url = $("#form-vote").attr("action"); //get form action url
var request_method = $("#form-vote").attr("method"); //get form GET/POST method
var form_data = $("#form-vote");
$.ajax({
url: post_url,
type: request_method,
data: form_data.serialize(),
processData: false,
async: true
}).done(function (objOperations) {
if ($("#validation-error")[0].textContent.trim() === "") {
ShowVoteStatus(true, "Your document is submitted successfully.");
}}).fail(function (error) {
ShowVoteStatus(false,
"Your document was not submitted successfully.");
}).always(function (jqXHR, textStatus) {
$.unblockUI();
});;
});
https://codepen.io/romanown/pen/QWKKERZ
deleted not worked validating
https://codepen.io/romanown/pen/zYKKKqv
I have an input field and "Add" button to store. While clicking the Add button another input field with the same class name should be created. But before creating there is a validation check. But the validation is only hitting first time. There is no validation check in the second time.
Below is my Code.
$('#add').click(function (e) {
e.preventDefault();
if ($('.js-user-email').val()) {
debugger;
$("#divSpecificToUserError span").text("");
$('#divSpecificToUserError').addClass("d-none");
if (ValidateEmailformat($('.js-user-email').val())) {
//debugger;
$.ajax({
type: "POST",
url: "Stepup.aspx/Exists",
data: JSON.stringify({ emailId: $('.js-user-email').val() }),
cache: false,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (response) {
debugger;
if (response != null && response.d != null) {
var data = response.d;
if (data > 0) {
addDynamicTextboxes();
}
else {
$("#divSpecificToUserError span").text("not a valid user");
$('#divSpecificToUserError').removeClass("d-none");
}
}
},
failure: function (response) {
alert(response.d);
}
});
}
else {
$("#divSpecificToUserError span").text("Please enter email id in valid format");
$('#divSpecificToUserError').removeClass("d-none");
}
}
else {
$("#divSpecificToUserError span").text("No E-mail has been entered ");
$('#divSpecificToUserError').removeClass("d-none");
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="field form-group form-group-padding">
<label class="col-form-label">User E-mail(s) to Notify:</label>
<input type="text" id="field1" name="userEmail1" class="input form-control js-user-email" placeholder="example#domain.com" autofocus />
<button id="add" class="btn-sm btn-secondary add-more-specific pull-right btn-user-email" title="Add" type="button">+</button>
<div class="col-md-3 d-none alert-danger" id="divSpecificToUserError" style="margin-top: 6px">
<span></span>
</div>
</div>
$('.btn-user-email') if this is multiple elements you need to loop it and add click events to all elements in the jQuery list.
Oh, I see what your problem is.
// Your Add Button Function
// to insert another input here
function add(){
// Your Add Button Code Here
refreshValidate();
}
// Validate Function
function refreshValidate(){
$('.btn-user-email').each(function() {
$(this).unbind();
$(this).click(function (e) {
e.preventDefault();
// Your Validate Code HERE ...
});
});
}
I get form page through Ajax.
The following is a form of code:
enter code here
<form method="post" enctype="multipart/form-data" class="form-horizontal">
<div class="form-group" style="margin-left:0px;">
<label for="file">注:选择头像文件尽量小于2M</label>
<input id="headPortraitFile" type="file" name="portrait">
</div>
<button id="headPortraitSubmit" type="button" class="btn-sm btn-primary">上传头像</button>
</form>
But the form of the input type = "file" in the browser cannot selected file directly, not to mention the submitted documents. I do not know what reason be? This two days have not been solved, for a great god!!!!!!
here is the Ajax code:
1.I get the form page by this:
$(Document).on("click", '#headPortrait', function() {
$.get("/headPortrait", function(data) {
$(".bodyPart").children().remove();
$(".bodyPart").html(data);
})
})
2.and then I post the form by this:
$(Document).on("click", '#headPortraitSubmit', function() {
var formData = new FormData();
formData.append("portrait", $('#headPortraitFile').get(0).files[0])
$.ajax({
url : "/headPortraitSubmit",
type : 'POST',
data : formData,
processData : false,
contentType : false,
beforeSend:function(){
console.log("正在进行,请稍候");
},
success : function(data) {
if (data = "success") {
$(".bodyPart").children().remove();
$(".bodyPart").load('/coding');
}
},
});
})
for attribute value should match id of <input type="file"> if expected result is for change event to be called for <input type="file"> element when <label> element is clicked. Substitute "submit" for "button" at type attribute of <button>.
Document is a function, not html document. Substitute document for Document at parameter passed to jQuery() : $().
if condition within success should use == or === to compare value of data to "success", instead of assigning "success" to data identifier.
$(document).on(/* event, selector, eventHandler */)
$(document).on("click", '#headPortraitSubmit', function() {
var formData = new FormData();
formData.append("portrait", $('#headPortraitFile').get(0).files[0]);
console.log(formData.get("portrait"));
/*
$.ajax({
url : "/headPortraitSubmit",
type : 'POST',
data : formData,
processData : false,
contentType : false,
beforeSend:function(){
console.log("正在进行,请稍候");
},
success : function(data) {
if (data === "success") {
$(".bodyPart").children().remove();
$(".bodyPart").load('/coding');
}
},
});
*/
});
document.querySelector("form")
.onsubmit = function(event) {
event.preventDefault();
}
document.querySelector("input[id=headPortraitFile]")
.onchange = function(event) {
console.log(this.files[0])
}
input[type=file] {
display: none;
}
[for=headPortraitFile]:before {
content: 'Label for #headPortraitFile ';
}
#headPortraitSubmit:before {
content: 'Sumbit form .form-horizontal ';
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post" enctype="multipart/form-data" class="form-horizontal">
<div class="form-group" style="margin-left:0px;">
<label for="headPortraitFile">注:选择头像文件尽量小于2M</label>
<input id="headPortraitFile" type="file" name="portrait">
</div>
<button id="headPortraitSubmit" type="submit" class="btn-sm btn-primary">上传头像</button>
</form>
Submit button onclick calling a function.( onClick="mandatoryNotes()" ).
Its taking a bit time to loading. So added a preloader script. Now the pre loader is working but not calling the function.
Requesting help.
Thank you
function mandatoryNotes()
{
document.getElementById("formsubmitbutton").style.display = "none"; // to undisplay
document.getElementById("buttonreplacement").style.display = ""; // to display
return true;
}
var FirstLoading = true;
function RestoreSubmitButton()
{
if( FirstLoading )
{
FirstLoading = false;
return;
}
document.getElementById("formsubmitbutton").style.display = ""; // to display
document.getElementById("buttonreplacement").style.display = "none"; // to undisplay
}
//code for calling page
{
var formvalue="invoiceAttributesDetailsFORM";
validateInput(document.invoiceAttributesDetailsFORM);
var queryString;
if(checkValidation=="true"){
//added by Nilanjana for 184932g
//alert("entered");
submitSpecialBidDetails(document.invoiceAttributesDetailsFORM);
queryString = "&EUAM_SELECTED_FORM=" + formvalue;
var legendURL = "/EUAM/ADRGateway?jadeAction=MANDATORY_NOTES_ACTION_HANDLER";
var winData = 'scrollbars=yes,resizable=yes,status=yes,width=500,height=500';
window.open("MandatoryNotes.jsp", "ADDVIEWNOTES",winData);
window.close();
}
}
<div class="em" id="formsubmitbutton">
<input type="button" name="Submit" value="Submit" class="buttonEm" onClick="mandatoryNotes()">
</div>
<div id="buttonreplacement" style="margin-left:30px; padding-top:15px; display:none;">
<img src="loadingSubmit.gif"alt="loading...">
</div>
Aren't you using any asynchronous technique like AJAX with XHR request to post the form. As your request would take time to run the pre-loader should be shown until the result appears .
I would recommend you to see JQuery ajax
You can write your submission code and start preloader before sending the request and stop it after the response is received.
$(document).ready(function(){
$('#submitbutton').on('click',function(){
var mydata = [];
var jqxhr = $.ajax({
url: '',
type: 'POST',
data: mydata ,
dataType: 'json',
contentType: 'application/json',
beforeSend: mandatoryNotes()
})
.done(function (ajax_data) {
RestoreSubmitButton();
})
.fail(function (jqXHR, textStatus) {
RestoreSubmitButton();
});
return false;
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="em" id="formsubmitbutton">
<input type="button" name="Submit" value="Submit" id='submitbutton' class="buttonEm" onClick="mandatoryNotes()">
</div>
<div id="buttonreplacement" style="margin-left:30px; padding-top:15px; display:none;">
<img src="loadingSubmit.gif"alt="loading...">
</div>
I use this plugin to upload multifile fyneworks. My problem is like this :
- Select one or more e:g 2 files on browse button, then I get those files
- I clicked again, and choose a lot of file e/g 1 file, on preview I got three.
- But when uploaaded, I just got the two image which is the first select.
This is my code :
I have a div to display menu upload like this:
$(document).on("click", '#menu_container', function () {
var this_url = $(this).attr("href");
$.post(this_url, {}, function (data) {
$('#content').html(data);
$('#file').addClass("multi with-preview");
$('#file').MultiFile({
list: "#log",
max: 10,
accept: 'jpg|png|gif|jpeg',
STRING: {
file: '<p>$file</p>',
remove: '<button type="button" class="btn btn-sm btn-danger">Hapus </button>'
}
});
});
return false;
});
Now, this is the html page :
<?php echo form_open_multipart('', array('id' => 'upload', 'enctype' => "multipart/form-data")); ?>
<div class="form-group col-sm-12 ">
<label for="file">Upload Foto</label>
<input name="file[]" id="file" class=" btn" type="file" multiple >
<div class="col-sm-6" id="log"> </div>
</div>
<button type="submit" class="btn btn-primary btn-block">Submit</button>
<?php echo form_close(); ?>
I use ajax to submit this photo like this :
$('#upload').submit(function () {
$.blockUI();
var form = $('#upload');
var inputFile = $('input#file');
var filesToUpload = inputFile[0].files;
// make sure there is file(s) to upload
if (filesToUpload.length > 0) {
// provide the form data that would be sent to sever through ajax
var formData = new FormData();
for (var i = 0; i < filesToUpload.length; i++) {
var file = filesToUpload[i];
formData.append("file[]", file, file.name);
}
$.ajax({
url: "<?php echo base_url('surveyor/c_surveyor/add_file_image/'); ?>/" + response.Nama_file + response.No_inspection,
type: 'post',
data: formData,
processData: false,
contentType: false,
success: function (obj) {
$.unblockUI();
$(":file").val('');
$(":text").val('');
$("#comments").val('');
$(".MultiFile-label").empty();
$('#pilih_isotank').before('<div class="callout callout-success lead" id="div_error"><p id="pesan_error">Data Berhasil Terupload dengan Nomor : ' + response.No_inspection + '</p></div>');
$('#pilih_isotank').after('<div class="callout callout-success lead" id="div_error"><p id="pesan_error">Data Berhasil Terupload dengan Nomor : ' + response.No_inspection + '</p></div>');
$('#div_error').fadeIn("fast");
$('#pesan_error').html(obj.Message);
$('#div_error').fadeOut(7000);
$('input:file').MultiFile('reset');
console.log("Update succcess");
},
error: function () {
alert('Ada yang salah, press ctrl + r');
}
});
} else {
$('#file').after('<div class="callout callout-danger lead" id="div_error"><p id="pesan_error"></p></div>');
$('#div_error').fadeIn("fast");
$('#pesan_error').html("Please Choose your Photo...");
$('#div_error').fadeOut(7000);
$.unblockUI();
}
return false;
});
I have read on doc :there is event :
onFileAppend
afterFileAppend
onFileSelect
afterFileSelect
onFileRemove
afterFileRemove
What should I do. Any help it so appreciated.