Resumable file upload customize name and add additional parametrs - javascript

I'm using http://resumablejs.com/ and can't understand how I can change filename after upload.
Describe a little more my situation:
I have file UploadFile.php with default code:
include 'vendor/autoload.php';
use Dilab\Network\SimpleRequest;
use Dilab\Network\SimpleResponse;
use Dilab\Resumable;
$request = new SimpleRequest();
$response = new SimpleResponse();
$resumable = new Resumable($request, $response);
$resumable->tempFolder = 'tmps';
$resumable->uploadFolder = 'upload/video';
$resumable->process();
I know that if I will use following:
$originalName = $resumable->getOriginalFilename(Resumable::WITHOUT_EXTENSION);
$slugifiedname = 'custom_prefix_'.$originalName;
$resumable->setFilename($slugifiedname);
It's will add 'custom_prefix_' to my filename.
But! I need use for prefix some additional information from form (Firstname and Lastname), how I can add this information to my request?
In frontend my file looks like:
<script type="text/javascript">
window.onload = (function () {
var r = new Resumable({
target: '/UploadFile.php',
maxChunkRetries: 2,
maxFiles: 1,
prioritizeFirstAndLastChunk: true,
simultaneousUploads: 4,
chunkSize: 5 * 1024 * 1024,
uploadMethod: 'POST',
maxFileSize: 550 * 1024 * 1024
});
...
uploadFile.on('click', function () {
$('.valid').html('');
if (results.children().length > 0) {
$.ajax({
url: '/Validate.php',
type: "POST",
data: $('#upload_form').serialize()+'&fileType='+fType+'&fileName='+fName,
dataType: "json",
success: function (data) {
if (results.children().length > 0) {
if(data[0]==true && data[1]==true){
$.ajax({
url: '/FormUpload.php',
type: "POST",
data: $('#upload_form').serialize()+'&fileType='+fType+'&fileName='+fName,
success: function (data) {
if (results.children().length > 0) {
r.upload();
} else {
nothingToUpload.fadeIn();
setTimeout(function () {
nothingToUpload.fadeOut();
}, 3000);
}
}
});
}else{
if(data[0]==false){
valid.text('Please complete all required fields!');
}
if(data[1]==false){
valid.text('Please complete all exeption fields!');
}
}
} else {
nothingToUpload.fadeIn();
setTimeout(function () {
nothingToUpload.fadeOut();
}, 3000);
}
}
});
} else {
nothingToUpload.css('opacity', 1);
setTimeout(function () {
nothingToUpload.css('opacity', 0);
}, 3000);
}
});

Try this code:
$resumable->process();
// you can get file information after the upload is complete
if (true === $resumable->isUploadComplete()) { // true when the final file has been uploaded and chunks reunited.
$extension = $resumable->getExtension();
$filename = $resumable->getFilename();
}

I found solution in my file FormUpload.php I return necessary information and send it like this:
uploadFile.on('click', function () {
$('.valid').html('');
if (results.children().length > 0) {
$.ajax({
url: '/Validate.php',
type: "POST",
data: $('#upload_form').serialize()+'&fileType='+fType+'&fileName='+fName,
dataType: "json",
success: function (data) {
if (results.children().length > 0) {
if(data[0]==true && data[1]==true){
$.ajax({
url: '/FormUpload.php',
type: "POST",
data: $('#upload_form').serialize()+'&fileType='+fType+'&fileName='+fName,
success: function (data) {
var data = jQuery.parseJSON(data);
if (results.children().length > 0) {
r.files[0].fileName = data.new_file_name;
r.upload();
} else {
nothingToUpload.fadeIn();
setTimeout(function () {
nothingToUpload.fadeOut();
}, 3000);
}
}
});
}else{
if(data[0]==false){
valid.text('Please complete all required fields!');
}
if(data[1]==false){
valid.text('Please complete all exeption fields!');
}
}
} else {
nothingToUpload.fadeIn();
setTimeout(function () {
nothingToUpload.fadeOut();
}, 3000);
}
}
});
} else {
nothingToUpload.css('opacity', 1);
setTimeout(function () {
nothingToUpload.css('opacity', 0);
}, 3000);
}
});

Related

function not run again if status === false

iam trying to run my function again if the status of my json false but its not working
$(document).ready(function(){
function checkIfCompleted(){
$('.btn').click( function(e) {
e.preventDefault();
var url = "https://localhost/check/1";
$.ajax({
url: url,
success: function(response) {
if(response.status === false){
checkIfCompleted();
}else{
alert(done);
}
},
});
});
}
checkIfCompleted();
});
You are adding click multiple times to the button, you are not rerunning the Ajax call
$(document).ready(function() {
function checkIfCompleted(cnt) {
var url = "https://localhost/check/1";
$.ajax({
url: url,
success: function(response) {
if (response.status === false) {
if (cnt >= 5) {
throw new Error('too many retries');
} else {
checkIfCompleted(++cnt);
}
} else {
alert(done);
}
},
});
}
$('.btn').click(function(e) {
e.preventDefault();
checkIfCompleted(0);
});
});

Only one alert for multiple execution in Ajax

I am working rails application.i need to get status of the each selected device.I am able to achieve this but after executing i am putting alert "Successfully created execution record".For every mac selection it is showing alert message.I need to give one alert in end of execution.I am calling display_result in call_endpoint method.Since it is an Ajax call,it is giving alert for every execution.i don't how to limit to single alert for this.
function display_result() {
$('#http_status').html("");
$('#http_status').append(result["response"].status);
if (result["response"].status == "404") {
console.log("HTTP 404");
$('#response_div').addClass("bs-callout-warning");
} else if (result["response"].status == "520") {
console.log("HTTP 502");
$('#response_div').addClass("bs-callout-danger");
} else {
console.log("HTTP 200");
$('#response_div').addClass("bs-callout-success");
if (result["response"].status == "200") {
// $('.loader').show();
$('#cover-spin').show();
$.ajax({
method: "GET",
dataType: "text",
url: "create_execution",
data: {
http_status: result["response"].status,
mac_address: mac,
},
success: function (execution_record_id) {
$('#cover-spin').hide();
alert('Successfully created execution record");
}
});
}
function call_endpoint() {
var values = new Array();
webpa = $('#Device-PA').is(":visible");
rpil = $('#Device-SN').is(":visible");
groupselect = $('#Group-Select').is(":visible");
parameter_name = $('#tr_object').val();
if (webpa) {
$.each($("input[name='checkBox[]']:checked").closest("td").next("td"), function () {
values.push($(this).text().trim())
});
m = values.length
} else {
$.each($("input[name='checkBox[]']:checked").closest("td").next("td"), function () {
values.push($(this).text().trim())
});
m = values.length
}
serialnumber = $('#pa_serialnumber').val();
oid = $('#sn_serialnumber').val();
protocol = {
pa: pa,
sn: sn,
}
if (pa) {
for (var i = 0; i < m; i++) {
(function () {
var macAdd = values[i];
$.ajax({
method: "GET",
url: "get_object",
dataType: "json",
data: {
parameter: parameter_name,
mac: macAdd,
protocol: protocol,
serialnumber: serialnumber,
},
success: function (result) {
console.log(result);
NProgress.done();
console.log("result for webpa");
display_result();
},
statusCode: {
404: function () {
console.log("Call failed");
}
}
});
})();
}
}
Below is changed code..
Copy below code as it is.
function display_result(total,current) {
$('#http_status').html("");
$('#http_status').append(result["response"].status);
if (result["response"].status == "404") {
console.log("HTTP 404");
$('#response_div').addClass("bs-callout-warning");
} else if (result["response"].status == "520") {
console.log("HTTP 502");
$('#response_div').addClass("bs-callout-danger");
} else {
console.log("HTTP 200");
$('#response_div').addClass("bs-callout-success");
if (result["response"].status == "200") {
// $('.loader').show();
$('#cover-spin').show();
$.ajax({
method: "GET",
dataType: "text",
url: "create_execution",
data: {
http_status: result["response"].status,
mac_address: mac,
},
success: function (execution_record_id) {
$('#cover-spin').hide();
if(total == current)
{
alert('Successfully created execution record");
}
}
});
}
}
}
function call_endpoint() {
var values = new Array();
webpa = $('#Device-PA').is(":visible");
rpil = $('#Device-SN').is(":visible");
groupselect = $('#Group-Select').is(":visible");
parameter_name = $('#tr_object').val();
if (webpa) {
$.each($("input[name='checkBox[]']:checked").closest("td").next("td"), function () {
values.push($(this).text().trim())
});
m = values.length
} else {
$.each($("input[name='checkBox[]']:checked").closest("td").next("td"), function () {
values.push($(this).text().trim())
});
m = values.length
}
serialnumber = $('#pa_serialnumber').val();
oid = $('#sn_serialnumber').val();
protocol = {
pa: pa,
sn: sn,
}
if (pa) {
for (var i = 1; i <= m; i++) {
(function () {
var macAdd = values[i];
$.ajax({
method: "GET",
url: "get_object",
dataType: "json",
data: {
parameter: parameter_name,
mac: macAdd,
protocol: protocol,
serialnumber: serialnumber,
},
success: function (result) {
console.log(result);
NProgress.done();
console.log("result for webpa");
display_result(m,i);
},
statusCode: {
404: function () {
console.log("Call failed");
}
}
});
})();
}
}
}
result and mac is not defined in display_result function. result appears intended to be the resulting value of jQuery promise object returned from $.ajax(). Am not certain what mac is indented to be.
You can substitute $.when() and $.map() for for loop, return a jQuery promise object from call_endpoint(), include error handling, chain .then() to call_endpoint() call to execute alert() once.
function call_endpoint() {
return $.when.apply($, $.map(values, function(macAdd) {
return $.ajax().then(display_result)
}))
}
callEnpoint()
.then(function() {
alert('Successfully created execution record');
}, function(jqxhr, textStatus, errorThrown) {
console.error(errorThrown)
});
function display_result(reuslt) {
..
if (if (result["response"].status == "200")) {
return $.ajax() // remove `alert()` from `success`
}
return;
}

How to wait untill for (append) finished and then show result javascirpt / jquery

I have a function that renders 5 images, and pagination. This function used ajax for getting data.
It works well, but when I using the pagination, I can see the process of 'creating' HTML.
I want to add a loading.gif, until all the HTML finished loading, and show all the results
function getImages(init, buttonPaging) {
var data = {};
if (init) {
data["int"] = "1";
} else {
data["int"] = $(buttonPaging).text();
}
$.ajax({
type: "POST",
url: '#Url.Action("GetImages", "Image")',
data: JSON.stringify(data),
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN", $('input:hidden[name="__RequestVerificationToken"]').val());
},
contentType: "application/json",
dataType: "json",
success: function (data) {
if (data.success) {
$('#imgList').children().remove();
for (var i = 0; i < data.imageList.length; i++) {
(function (img) {
$('#imgList').append(drawList(img, data.baseUrl));
})(data.imageList[i]);
}
$('#pagingList').children().remove();
for (var i = 0; i < data.pagingInfo.totalPages; i++) {
(function (paging) {
var isCurrentPage = false,
index = i;
index++;
if (paging.currentPage == index) {
isCurrentPage = true;
}
$('#pagingList').append(drawPaging(index, isCurrentPage));
})(data.pagingInfo);
}
} else {
errors += data.error;
}
},
error: function () {
errors += 'Please contact with administrator - img list at edit product';
alert(errors);
}
});
}
I saw tutorials about promises and callbacks, but I'm not good at it and I don't know how to rewrite my code for those. Is there another way to solve the issue ?
solution: It may come in handy for other:
function hideLoader() { setTimeout(function () { $('.loader-sm').hide(); }, 750); }
function showLoader() { $('.loader-sm').show(); }
function hideList() { $('#imgList').hide(); }
function showList() { setTimeout(function () { $('#imgList').show(200); }, 750); }
success: function () {
if (data.success) {
//do something
} else {
showList();
hideLoader();
}
},
error: function () {
showList();
hideLoader();
},
complete: function () {
showList();
hideLoader();
}
have a class for show loading image icon and place it in the block itself and hide it once completed. have a look at the below sample. it may helpful to you.
beforeSend: function() {
$('#imgList').addClass('loading');
},
success: function(data) {
$("#imgList").removeClass('loading');
},
error: function(xhr) { // if error occured
$("#imgList").removeClass('loading');
},
complete: function() {
$("#imgList").removeClass('loading');
}
otherwise you can have a loader div block show the block on beforesend() and hide it in success / complete.
You can do like this i am not sure about but it will help you
function getImages(init, buttonPaging) {
var data = {};
if (init) {
data["int"] = "1";
} else {
data["int"] = $(buttonPaging).text();
}
let promise = new Promise(function(resolve, reject) {
//add your code for add loading.gif
$.ajax({
type: "POST",
url: '#Url.Action("GetImages", "Image")',
data: JSON.stringify(data),
beforeSend: function (xhr) { xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val()); },
contentType: "application/json",
dataType: "json",
success: function (data) {
if (data.success) {
$('#imgList').children().remove();
for (var i = 0; i < data.imageList.length; i++) {
(function (img) {
$('#imgList').append(drawList(img, data.baseUrl));
})(data.imageList[i]);
}
$('#pagingList').children().remove();
for (var i = 0; i < data.pagingInfo.totalPages; i++) {
(function (paging) {
var isCurrentPage = false,
index = i;
index++;
if (paging.currentPage == index) { isCurrentPage = true; }
$('#pagingList').append(drawPaging(index, isCurrentPage));
})(data.pagingInfo);
}
resolve();
} else {
errors += data.error;
resolve();
}
},
error: function () {
errors += 'Please contact with administrator - img list at edit product';
alert(errors);
resolve();
}
});
}
promise.then(
result => alert("done"), // remove loading.gif
);
}

Ajax callback is firing after function call

Hi Have a ajax call in a function thats called on date input change event to check if a date is already in use for User. the success in the Ajax call fires after the click function is finished.
How do I get the success results and continue on with the #datepicker change funtion as I need the json results for rest of function.
controller
public ActionResult IsDateAvailable(DateTime date, int Id) {
var dateAvailable = !(_context.Trading.Any(t => t.uId == Id && t.TradingDate == date));
if (!(dateAvailable)) {
return Json(new {
status = false, msg = "This date already exists."
});
}
return Json(new {
status = true
});
}
JavaScript
$(document).ready(function() {
var message;
var isDateValid;
function CheckDate(para) {
var dateValid;
var mesg;
return $.ajax({
url: '#Url.Action("IsDateAvailable", "Trading")',
type: "GET",
data: para,
dataType: "json",
success: function(data) {
if (!(data.status)) {
message = data.msg;
} else {
isDateValid = true;
}
},
error: function(xhr, httpStatusMessage) {
alert(xhr + httpStatusMessage);
}
});
}
$("#datePicker").change(function() {
$("#alert").css({
'display': 'none'
});
if (Id == 0) {
$("#alert").attr('class', 'alert alert-danger');
$("#alert").text('Please select a User.');
$("#alert").show();
return false;
}
var date = $(this).val();
var para = {
date: date,
Id: Id
};
CheckDate(para);
if (isDateValid) {
$("#btnAdd").show();
} else {
$("#btnAdd").css({
'display': 'none'
});
$("#alert").attr('class', 'alert alert-danger');
$("#alert").text(message);
$("#alert").show();
}
});
});
You should turn to being asynchronous. change your code to match with these:
.
.
.
function CheckDate(para) {
return new Promise((resolve, reject) => {
return $.ajax({
url: '#Url.Action("IsDateAvailable", "Trading")',
type: "GET",
data: para,
dataType: "json",
success: function(data) {
if (!(data.status)) {
message = data.msg;
} else {
isDateValid = true;
}
resolve();
},
error: function(xhr, httpStatusMessage) {
alert(xhr + httpStatusMessage);
reject();
}
});
}
.
.
.
checkDate(para).then(res => {
if (isDateValid) {
$("#btnAdd").show();
} else {
$("#btnAdd").css({
'display': 'none'
});
$("#alert").attr('class', 'alert alert-danger');
$("#alert").text(message);
$("#alert").show();
}
}).catch(err => { /* do something */ });
You just need to set async: false inside your ajax request. You can also remove the word return from the CheckDate, because of it's redundant:
function CheckDate(para) {
var dateValid;
var mesg;
$.ajax({
url: '#Url.Action("IsDateAvailable", "Trading")',
async: false,
type: "GET",
data: para,
dataType: "json",
success: function(data) {
if (!(data.status)) {
message = data.msg;
} else {
isDateValid = true;
}
},
error: function(xhr, httpStatusMessage) {
alert(xhr + httpStatusMessage);
}
});
}

Ajax post to controller not found

I have the following JavaScript:
function saveAvatar() {
var img = $('#preview-pane .preview-container img');
$('#avatar-crop-box button').addClass('disabled');
$.ajax({
type: "POST",
url: App.url + "/Save",
traditional: true,
data: {
width: img.css('width'),
height: img.css('height'),
marginLeft: img.css('marginLeft'),
marginTop: img.css('marginTop'),
fileName: img.attr('src'),
userId: this.userId
}
}).done(function (data) {
if (data.success === true) {
if (!keepCropBox) {
$('#avatar-crop-box').addClass('hidden');
location.reload();
}
} else {
alert(data.errorMessage)
}
}).fail(function (e) {
alert('Cannot upload avatar at this time');
});
}
Here is my save method:
[HttpPost]
public async Task<ActionResult> Save(string marginTop, string marginLeft, string height, string width, string fileName, int userId)
{
var image = ImageHelper.Save(marginTop, marginLeft, height, width, fileName);
if(image != "error")
{
var savedProfilePicture = await userService.SaveProfilePicture(image, userId);
if (savedProfilePicture > 0)
{
return Json(new { success = true, avatarFileLocation = image });
}
}
return Json(new { success = false, errorMessage = "Could not save profile picture" });
}
This works fine when I run the project on my local machine and when the App.url is set to http://localhost:1234/Home
But when I deploy the project to a server, and the App.url becomes: http://project-on-another-machine.com/Home. It's not working with the Save-method. I'm always getting a 404 not found.
I have other method that works fine, but not this particular Save-method. Why is this?
In your view add the value of URL in a global variable like this
<script>
var params["saveUrl"] = "#Action("Save","Home")";
</script>
and then use this variable in your js file to access the action method.
$.ajax({
type: "POST",
url: params["saveUrl"],
...
The Url should be url: "/Home/Save/"
function saveAvatar() {
var img = $('#preview-pane .preview-container img');
$('#avatar-crop-box button').addClass('disabled');
$.ajax({
type: "POST",
url: "/Home/Save",
traditional: true,
data: {
width: img.css('width'),
height: img.css('height'),
marginLeft: img.css('marginLeft'),
marginTop: img.css('marginTop'),
fileName: img.attr('src'),
userId: this.userId
}
}).done(function (data) {
if (data.success === true) {
if (!keepCropBox) {
$('#avatar-crop-box').addClass('hidden');
location.reload();
}
} else {
alert(data.errorMessage)
}
}).fail(function (e) {
alert('Cannot upload avatar at this time');
});
}

Categories

Resources