How to upload modified file without reloading website - javascript

I have a case as follow:
Step 1: Open pop-up, upload file -> Success.
Step 2: Edit file just uploaded.
Step 3: without reload website, reopen pop-up.
Step 4: select file just edited to upload.
Expected result: Upload success.
Actual result : upload error: Data format of the uploaded file is not EXCEL file.
How i can fix it??
This is my code
Code js
function handlerUploadFile() {
var form = $(‘'#uploadFile_action')[#];
var data = new FormData(form);
loading_ajax();
$.ajax({
type: "POST",
enctype: 'multipart / form - data ',
url: '../sac0#12/uploadFile.action',
data: data,
processData: false,
contentType: false,
cache: false,
timeout: 620000,
success: function(data, status, xhr) {
close_loading_ajax(
};
var messageld = "";
var ct = xhr.getResponseHeader('content - type ') || °";
if (ct.indexOf('html') > -1) {
showNotifyDialog("fileNotFormatExcel");
return; +
if (ct.indexOf('json') > -1) {
var obj = JSON.parse(data);
if (obj.result == "SUCCESS”) {
showNotifyDialog("fileUploadSuccess") $("#myModalUpload”).css("
display”, “none ")};
$('#itemDetails')
}.empty(); loadContent(limit, offset, transactionId, scrollTop);
}
else {
if (obj.code == "EA-0003") {
messageId = "EA-0003";
contentConfirm = mesSystem[messageId];
alert(contentConfirm);
} else if (obj.code == "ERROR_PLT_ID_LENGTH") {
messageId = "ERROR_PLT_ID_LENGTH";
contentConfirm = mesSystem[messageId];
alert(contentConfirm);
} else {
alert("Data format of the uploaded file is not correct.");
}
}
}
},
error: function(e) {
close_loading_ajax();
alert("Data format of the uploaded file is not EXCEL file.");
}
});
}
code jsp
<form id="uploadFile_action" name="uploadFile_action" method="post" enctype="multipart/form-data">
<div class="row" style="margin: 5px 0 0; border-bottom: 1px solid gray; height: 40px;">
<div class="col-md-12">
<div class="col-md-2 col-sm-2 col-xs-2 file" style="margin-top: 5px; width: auto;">
<b style="font-weight: 900;">Upload File:</b>
</div>
<div class="col-md-9 col-xs-9 col-sm-9 file-return" contentEditable=false data-text="File path"></div>
<div class="col-md-1 col-xs-1 col-sm-1 input-file-container">
<input type="hidden" name="confirm" value="false" id="uploadFile_action_confirm" />
<input type="file" name="file" accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel" class="input-file" value="" id="uploadFile_action_file" />
<button tabindex="0" for="my-file" class="input-file-trigger" value="Browse"><b style="font-weight: 800;">Browse</b></button>
</div>
</div>
<div class="col-md-12">
<p id="emptyFileUpload" style="display: none;"></p>
</div>
</div>
<div class="row">
<input type="submit" name="upload" class="btn btn-primary btn-danger textWhite" id="uploadFile_action_0" style="height: 34px" value="Upload" />
<input type="button" value="Back" class="cancelButton">
</div>
<s:hidden name="transactionId"></s:hidden>
</form>

Related

How to send ID of a row throught submit form / button?

I'm writing a code for the system administrator to be able to reset the users' passwords in their accounts in case they forget said password.
I'm currently having problems passing the target user's ID through Ajax to change said user's password, through debugging tool, the system returns an "undefined" response for "id:", although the "_token" and "password" fields were sent fine.
HTML code for the form
<form id="form-reset-password">
<div class="container my-2">
<div class="row">
<div class="col-md-12">
<div class="form-row">
<input type="hidden" id="token" name="_token" value="{{csrf_token()}}">
</div>
<div class="form-group">
<label>New Password</label>
<input type="text" class="form-control" id="reset-password" name="password" readonly>
</div>
<div class="form-group text-right mt-4">
<button type="button" class="btn btn-dark" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-success btn-confirmreset">Reset</button>
</div>
</div>
</div>
</div>
</form>
Javascript for generating the data-table where it shows the list of User accounts. On the side of the table, the admin can click a button to reset the password of said user.
$(document).ready(function() {
getRoles();
var accounts;
$('#account-management').addClass('active');
accounts = $("#table-accounts").DataTable({
ajax: {
url: "/users/get-all-users",
dataSrc: ''
},
responsive:true,
"order": [[ 7, "desc" ]],
columns: [
{ data: 'id'},
{ data: 'organization_name', defaultContent: 'n/a' },
{ data: 'first_name' },
{ data: 'last_name' },
{ data: 'email'},
{ data: 'student_number'},
{ data: 'role.name'},
{ data: 'created_at'},
{ data: null,
render: function ( data, type, row ) {
var html = "";
if (data.status == 1) {
html += '<span class="switch switch-sm"> <input type="checkbox" class="switch btn-change-status" id="'+data.id+'" data-id="'+data.id+'" data-status="'+data.status+'" checked> <label for="'+data.id+'"></label></span>';
} else {
html += '<span class="switch switch-sm"> <input type="checkbox" class="switch btn-change-status" id="'+data.id+'" data-id="'+data.id+'" data-status="'+data.status+'"> <label for="'+data.id+'"></label></span>';
}
html += "<button type='button' class='btn btn-primary btn-sm btn-edit-account mr-2' data-id='"+data.id+"' data-account='"+data.id+"'>Edit</button>";
html += "<button type='button' class='btn btn-secondary btn-sm btn-reset-password' data-id='"+data.id+"' data-account='"+data.id+"'><i class='fas fa-key'></i></button>";
return html;
}
},
],
columnDefs: [
{ className: "hidden", "targets": [0]},
{ "orderable": false, "targets": 7 }
]
});
Javascript for the random password generator and reset password
function resetPassword() {
$.ajax({
type: 'GET',
url: '/user/get-new-password',
processData: false,
success: function(data) {
$('#reset-password').val(data.password);
}
});
}
$(document).on('click', '.btn-reset-password', function() {
$('#reset-password-modal').modal('show');
resetPassword();
});
$(document).on('submit', '#form-reset-password', function() {
var confirm_alert = confirm("Are you sure you want to reset this account's password?");
if (confirm_alert == true) {
// var id = $(this).attr('data-id');
var id = $('.btn-confirmreset').attr('data-id');
$.ajax({
url: "/auth/reset-password",
type: "POST",
data: $(this).serialize()+"&id="+id,
success: function(data) {
if (data.success === true) {
alert("Password successfully reset!");
location.reload();
}
else {
alert("Something went wrong");
}
}
});
return false;
}
});
Thank you for your help!
<form id="form-reset-password">
<div class="container my-2">
<div class="row">
<div class="col-md-12">
<div class="form-row">
<input type="hidden" id="token" name="_token" value="{{csrf_token()}}">
<input type="hidden" id="user_id" name="user_id" value=""> // initiate the hidden input here
</div>
<div class="form-group">
<label>New Password</label>
<input type="text" class="form-control" id="reset-password" name="password" readonly>
</div>
<div class="form-group text-right mt-4">
<button type="button" class="btn btn-dark" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-success btn-confirmreset">Reset</button>
</div>
</div>
</div>
</div>
</form>
<script type="text/javascript">
$(document).on('click', '.btn-reset-password', function() {
var user_id_value = $(this).attr('data-id'); // Get the user id from attr
$('#user_id').val(user_id_value); // Assign the user id to hidden field.
$('#reset-password-modal').modal('show');
resetPassword();
});
$(document).on('submit', '#form-reset-password', function() {
var confirm_alert = confirm("Are you sure you want to reset this account's password?");
if (confirm_alert == true) {
// var id = $(this).attr('data-id');
//var id = $('.btn-confirmreset').attr('data-id'); // Remove this, it won't work , because this button doesn't contain the data-id
var id = $('#user_id').val(user_id_value); // You can get the value from hidden field
$.ajax({
url: "/auth/reset-password",
type: "POST",
data: $(this).serialize()+"&id="+id,
success: function(data) {
if (data.success === true) {
alert("Password successfully reset!");
location.reload();
}
else {
alert("Something went wrong");
}
}
});
return false;
}
});
</script>
Please refer the above code, You can pass the user id while modal pop up call and set that id to hidden value. then you can access that id from the hidden input. when you submit "form-reset-password" form.
Please look at comments on the above code
Maybe the attr() function is looking for native HTML attribute. So use the following snippet will help.
var id = $('.btn-confirmreset').data('id');

How to pass data to ajax with image and string

I'm having a problem of uploading a image with names in my database my code is working fine but it is only for image I can't add the name and other data in it
var formdata = new FormData(this);
formdata.append("movieprice", movieprice);
formdata.append("movietitle", movietitle);
formdata.append("moviecategory", moviecategory);
formdata.append("upload", upload);
formdata.append("image", image);
var upload ="upload";
$.ajax({
url:"uploadmovie.php",
method:"POST",
data:formdata,
contentType:false,
processData:false,
success:function(data){
if (data === "YES"){
alert(data)
swal("Successfully Uploaded", "", "success")
.then((value) => {
window.location.reload();
});
}else{
alert(data)
swal("Error", "", "warning")
}
}
});
}
Also this for the variables:
var movieprice = $('#movieprice').val();
var movietitle = $('#movietitle').val();
var moviecategory = $('#moviecategory').val();
How can I pass this value to ajax ?
here is the html for those looking for i didnt add the validation on javascript for the empty fields
<form method="POST" enctype="multipart/form-data" >
<div class="w3-col m12 02">
<div class="w3-rest w3-container w3-blue" style="width:100%;">
<label id="label"><i class="fa fa-tag" style="font-size:24px;"> Movie Category</i></label>
</div>
<select id="moviecategory" name="moviecategory">
<option>Romance</option>
<option>Comedy</option>
<option>Action</option>
<option>Drama</option>
<option>Horror</option>
<option>Sci-Fi</option>
</select>
</div>
<div class="w3-col m12 02">
<div class="w3-rest w3-container w3-blue" style="width:100%;">
<label id="label"><i class="fa fa-address-card" style="font-size:24px;"> Movie Title</i></label>
</div>
<input type="text" name="movietitle" id="movietitle">
</div>
<div class="w3-col m12 02">
<div class="w3-rest w3-container w3-blue" style="width:100%;">
<label id="label"><i class="fa fa-money" style="font-size:24px;"> Movie Price</i></label>
</div>
<input type="number" name="movieprice" id="movieprice">
</div>
<div class="w3-col m12 02">
<div class="w3-rest w3-container w3-blue" style="width:100%;">
<label id="label"><i class="fa fa-file" style="font-size:24px;">Movie Image</i></label>
</div>
<input type="file" name="image" id="image" /><br />
</div>
<footer class="w3-container">
<button class="w3-right btn btn-danger" id="close" style="float: right; width:90px; margin-left:10px;">close</button>
<button type="submit" class="btn btn-primary" name="upload" id="upload" value="Upload Image" style="float: right; width:90px;">Add</button>
</footer>
</form>
and for the uploadmovie.php i got the error that image is undefined
using this $image = $_FILES["image"]["tmp_name"];
if (move_uploaded_file($_FILES["image"]["tmp_name"], $target)) {
$target = "images/".basename($_FILES["image"]["tmp_name"]);
You could add custom data into the FormData instance using the method append() :
var movieprice = $('#movieprice').val();
var movietitle = $('#movietitle').val();
var moviecategory = $('#moviecategory').val();
// create FormData object
var formdata = new FormData(this);
// add custom data :
formdata.append("movieprice", movieprice);
formdata.append("movietitle", movietitle);
formdata.append("moviecategory", moviecategory);
// send data
$.ajax({
url:"uploadmovie.php",
method:"POST",
data:formdata,
contentType:false,
processData:false,
success:function(data){
// ...
}
});
The server-side will receive the data "movieprice","movietitle" and "moviecategory" in your $_POST array.

Uploading image using ajax to submit form taking a lot of time

Basically I am using html form for uploading image on server. Below is my code for form:
<div class="modal modal-fixed-footer" id="modal-image">
<div class="modal-content">
<h3>Upload Image</h3>
<form id="uploadimg" enctype="multipart/form-data">
<input type="hidden" name="entity" value="order">
<input type="hidden" name="orderId" value="<?php echo $orderId; ?>">
<input type="hidden" name="status" value="<?php echo $json->response->body->order->status; ?>" />
<input type="hidden" name="url" value="order-details.php?order=<?php echo $orderId; ?>&e=0">
<div class="form-inputs p-l-r-0">
<div class="row">
<div class="col s12">
<div class="file-field input-field" style="display:none">
<div class="btn accent-color">
<span>File</span>
<input type="file" id="fileToUpload" name="fileToUpload[]" multiple="multiple">
</div>
<div class="file-path-wrapper">
<input class="file-path validate" type="text" placeholder="Upload one or more images">
</div>
</div>
</div>
</div>
<div id="dvPreview" class="row"></div>
</div>
</form>
</div>
<div class="modal-footer">
<button class="btn-flat modal-action modal-close" id="uploadimg-submit">Submit</button>
<button class="btn-flat modal-action modal-close">Close</button>
</div>
Now when the #uploadimg-submit is clicked below jquery code is executed:
$('#uploadimg-submit').on('click', function(e) {
e.preventDefault();
$("form#uploadimg").submit();
});
and form submit function:
$("form#uploadimg").submit(function(e2) {
var smoothState = $('#main').smoothState().data('smoothState');
e2.preventDefault();
var formData = new FormData($(this)[0]);
// console.log(formData);
$.ajax({
url: 'processors/process-upload.php',
type: 'POST',
data: formData,
processData: false,
contentType: false,
beforeSend: function() {
ajaxindicatorstart();
},
success: function(rsp) {
if (rsp == '200') {
Materialize.toast('Image Uploaded Successfully', 2000, 'green');
smoothState.clear('/order-details.php');
smoothState.load('/order-details.php?order=' + $('#order_id').val());
} else {
Materialize.toast('Image Uploaded Failed', 2000, 'red');
smoothState.clear('/order-details.php');
smoothState.load('/order-details.php?order=' + $('#order_id').val());
}
},
error: function() {
Materialize.toast('Image Uploaded Failed', 2000, 'red');
smoothState.clear('/order-details.php');
smoothState.load('/order-details.php?order=' + $('#order_id').val());
}
});
return false;
});
The file process-upload.php takes less than a second to process the image which i debugged using microtime(true). But total time take by sending request and recieving response is nearly 11 secs, majority of which (about 9 secs) is taken in sending request. Below are timeline analytics from chrome dev tools.
I want to reduce this time else it will be unfeasible to wait so long for uploading image. Is there any way I can optimize it further?

I'm trying to upload a file using node and ajax but the ajax call isn't working?

I'm facing error on Upload xml and upload csv am a rookie so please can you provide me a elaborate answer
I've tried debugging the code on clicking upload button till upload function is working fine on jumping to uploadxml() function the data is not sent.
My HTML code
<div class="file-upload">
<form id="file-upload-form">
<div class="upload">
<div class="col-lg-6">
<div class="input-group" id="one">
<input type="text" class="form-control" id="t1" placeholder="Select an xml file.." >
<span class="input-group-btn">
<button class="btn btn-default" type="button" id="xmlbtn">Browse</button>
</span>
</div>
<input type="file" accept=".xml" class="hidden" id="xmlPicker" name="xmlFile"/>
</div>
<div class="col-lg-6">
<div class="input-group" id="two">
<input type="text" class="form-control" id="t2" placeholder="Select an csv file.." >
<span class="input-group-btn">
<button class="btn btn-default" type="button" id="csvbtn">Browse</button>
</span>
</div>
<input type="file" class="hidden" accept=".csv" id="csvPicker" name="csvFile"/>
</div>
</div>
<div class="uploadfooter">
<button class="btn btn-default center" type="button" id="upload">Upload</button>
</div>
</form>
</div>
My Js
$(document).ready(function () {
$(".ts-sidebar-menu li a").each(function () {
if ($(this).next().length > 0) {
$(this).addClass("parent");
};
})
var menux = $('.ts-sidebar-menu li a.parent');
$('<div class="more"><i class="fa fa-angle-down"></i></div>').insertBefore(menux);
$('.more').click(function () {
$(this).parent('li').toggleClass('open');
});
$('.parent').click(function (e) {
e.preventDefault();
$(this).parent('li').toggleClass('open');
});
$('.menu-btn').click(function () {
$('nav.ts-sidebar').toggleClass('menu-open');
});
$('#zctb').DataTable();
$("#input-43").fileinput({
showPreview: false,
allowedFileExtensions: ["zip", "rar", "gz", "tgz"],
elErrorContainer: "#errorBlock43"
// you can configure `msgErrorClass` and `msgInvalidFileExtension` as well
});
$("#xmlbtn").bind("click", function(){
$("#xmlPicker").trigger("click");
});
$("#xmlPicker").bind("change", function(e){
$("#t1").val($("#xmlPicker")[0].files[0].name);
})
$("#csvbtn").bind("click", function () {
$("#csvPicker").trigger("click");
});
$("#csvPicker").bind("change", function (e) {
$("#t2").val($("#csvPicker")[0].files[0].name)
})
$("#upload").on("click",function () {
var firstfile = $("#t1").val();
var secondfile = $("#t2").val();
if(!firstfile || firstfile != null){
updateXml();
}
if(!secondfile || secondfile != null){
updatecsv();
}
})
function updateXml(){
var form = $("#file-upload-form").val()
var data = new FormData(form);
$.ajax({
url: "/update",
data: data,
type: "put",
contentType: false,
processData: false,
cache: false,
success: function (response) {
console.log(response);
}
})
}
function updatecsv(){
var form = $("#file-upload-form").val()
var data = new FormData(form);
$.ajax({
url: "/update",
data: data,
type: "put",
contentType: false,
processData: false,
cache: false,
success: function (response) {
console.log(response);
}
})
}
});
This line here:
var form = $("#file-upload-form").val()
A form does not have a value, its inputs have one. FormData expects a form, so you need to give it a reference to it.
var form = $("#file-upload-form");
var data = new FormData(form[0]); //expects a DOM form

JQuery Ajax - File and Data Upload

I am trying to create a form which uploads data and an image in the same submission. I've look all over and I can only seem to find people that are having trouble to upload files alone with JQuery. If I make content-type false then the data dosen't go through only the file. Here is the code:
<form action="/secret/includes/add_listing.php" id="listingfrm" name="listingfrm" action="javascript:;" enctype="multipart/form-data" method="post" accept-charset="utf-8">
<div>
<label for="title">Title</label>
<div class="right">
<div class="row">
<div class="col-cst-1">
<input type="text" name="title">
</div>
</div>
</div>
</div>
<div>
<label for="content">Description</label>
<div class="right">
<div class="row">
<div class="col-cst-1">
<textarea name="content" rows="5"></textarea>
</div>
</div>
</div>
</div>
<div>
<label for="image">Upload a Thumbnail</label>
<!-- Browse to Upload Image (No more than 1MB) -->
<div class="right">
<div class="row">
<div class="col-cst-1">
<input type="file" name="listing_thumb" id="listing_thumb">
</div>
</div>
</div>
</div>
<input type="submit" value="Submit">
</form>
function ajax(url, type, data) {
var request
if (type != "none") {
request = $.ajax({
url: url,
type: type,
data: data,
});
} else {
request = $.ajax({
url: url
});
}
return request;
}
$(document).ready(function() {
$(document).on("submit", "#listingfrm", function(event) {
event.preventDefault();
var form = $(this);
var inputs = GetInputs(form);
var serializedForm = form.serialize();
inputs.prop("disabled", true);
var request = ajax("includes/add_post.php", "post", serializedForm)
request.done(function(response, textStatus, jqXHR) {
console.log(response)
})
request.fail = ajax(function(jqXHR, textStatus, errorThrown) {
console.error("Login Error: " + textStatus + " : " + errorThrown)
})
request.always(function() {
inputs.prop("disabled", false);
})
});
});
When using this the title and the description don't go through to the PHP file however if I don't then the image dosen't.

Categories