Is this js form valid? - javascript

I have a js code which asks the user to input a code. I want to check if it is valid or it is programmed to say : code invalid! And if possible what happens when the code is valid.
Js Code:
myApp.prompt('Please enter your code, function (password) {
myApp.showPreloader('Checking Code...')
setTimeout(function () {
myApp.hidePreloader();
form.onsubmit = function(event) {
event.preventDefault();
var files = fileSelect.files;
var formData = new FormData();
for (var i = 0; i < files.length; i++) {
var file = files[i];
if (!file.type.match('bac.*')) {
continue;
}
formData.append('bac[]', file, file.name);
}
formData.append(name, file, filename);
formData.append(name, blob, filename);
formData.append(name, value);
var xhr = new XMLHttpRequest();
xhr.open('POST', 'bachandler.php', true);
xhr.onload = function () {
if (xhr.status === true) {
} else {
AlertBac();
}
};
}
xhr.send(formData);
}, 4000);
myApp.alert('code invalid ');
});
}, 5123)
}
},
]
})
});

You're missing the closing quote in the first line.
myApp.prompt('Please enter your code, function (password) {
should be
myApp.prompt('Please enter your code', function (password) {

Related

Can not send file from Controller Action to browser for download

I am sending a XMLHttpRequest to a MVC Controller and i am expecting to receive a file as a result.
When debugging with the browser i am getting a response that is ok , but i do not know why it is not as a file:
JS
window.submit=function () {
return new Promise((resolve, reject) => {
var form = document.getElementById("newTestForm");
var data = new FormData(form);
var xhr = new XMLHttpRequest();
var method = form.getAttribute('method');
var action = form.getAttribute('action');
xhr.open(method, action);
xhr.onload = function () {
if (this.status >= 200 && this.status < 300) {
resolve(xhr.response); //response looks ok...but no file starts downloading
}
else if (xhr.status != 200) {
reject("Failed to submit form with status" + xhr.status);
}
}
xhr.send(data);
});
}
Controller
[HttpPost]
[Route([Some Route])]
public async Task BenchAsync(object request)
{
try
{
string fileName = "results.txt";
object result = await service.RunAsync(request);
byte[] data = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(result));
this.Response.ContentType = "application/octet-stream";
this.Response.ContentLength = data.Length;
using(MemoryStream stream=new MemoryStream(data))
{
await stream.CopyToAsync(this.Response.Body);
}
}
catch (Exception ex)
{
throw;
}
}
I have solved it thanks to this Post
It seems i had to transform the response into a BLOB , create a download link and point it towards this blob and the created link in order to download the file.
So the function looks like :
window.submit= function () {
return new Promise((resolve, reject) => {
var form = document.getElementById("newTestForm");
var data = new FormData(form);
var xhr = new XMLHttpRequest();
var method = form.getAttribute('method');
var action = form.getAttribute('action');
xhr.open(method, action);
xhr.onload = function () {
if (this.status >= 200 && this.status < 300) {
var blob = new Blob([this.response], { type: 'image/pdf' });
let a = document.createElement("a");
a.style = "display: none";
document.body.appendChild(a);
let url = window.URL.createObjectURL(blob);
a.href = url;
a.download = 'mytext.txt';
a.click();
window.URL.revokeObjectURL(url);
}
else if (xhr.status != 200) {
reject("Failed to submit form with status" + xhr.status);
}
}
xhr.send(data);
});
}
P.S i do not know what the type of the blob is named for txt but it works as well , given the right extension.

How to create zip file after looping all the files?

I' using JSzip to create zipfile which contain all the images files. I got the images from external links within a loop using XMLHttpRequest. According to my code zipfile create before complete the XMLHttpRequest. So it returns empty zip file. How to create zip file after looping all the files?
$(document).on('click', '.download', function(){
var path = $(this).attr("data-id");
var count = $(this).attr("value");
var storageRef = firebase.storage().ref();
var zip = new JSZip();
console.log(count);
for (i = 1; i <= count; i++) {
console.log(path+i+".png");
var imagePath = path+i+".png";
// Create a reference to the file we want to download
var starsRef = storageRef.child(imagePath);
starsRef.getDownloadURL().then(function(url) {
// Insert url into an <img> tag to "download"
ImageUrl = url;
var xhr = new XMLHttpRequest();
xhr.open('GET', ImageUrl, true);
xhr.responseType = "arraybuffer";
xhr.onreadystatechange = function(evt) {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
zip.file(i+".png", xhr.response);
}
}
};
xhr.send();
})
}
zip.generateAsync({type:"blob"})
.then(function(content) {
// see FileSaver.js
saveAs(content, "my.zip");
});
});
JSZip supports promises as content: you can wrap each HTTP calls into promises and not explicitly wait.
The first function, downloadUrlAsPromise, wraps the xhr call into a Promise. The second function, downloadFirebaseImage, chains the promise from getDownloadURL with the promise of the first function. The result is a promise of the xhr content.
Once you have that, you can give directly the promise to JSZip like that:
zip.file(i+".png", downloadFirebaseImage(imagePath));
Full methods:
function downloadUrlAsPromise (url) {
return new Promise(function (resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = "arraybuffer";
xhr.onreadystatechange = function(evt) {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
resolve(xhr.response);
} else {
reject(new Error("Ajax error for " + url + ": " + xhr.status));
}
}
});
xhr.send();
});
}
function downloadFirebaseImage(storageRef, path) {
var starsRef = storageRef.child(imagePath);
return starsRef.getDownloadURL().then(function(url) {
return downloadUrlAsPromise(url);
});
}
// ...
for (i = 1; i <= count; i++) {
console.log(path+i+".png");
var imagePath = path+i+".png";
zip.file(i+".png", downloadFirebaseImage(imagePath));
}
zip.generateAsync({type:"blob"})
.then(function(content) {
// see FileSaver.js
saveAs(content, "my.zip");
});

How to return "finished" section of a javascript code

I want to upload an image file to server and then show it on browser editor on return.
For that, I have #fileInput form input (type file) to upload an image to server.
On change #fileInput, I trigger uploadAndReadURLfunction which calls app.uploader for upload.
When upload is finished, it returns to line commented "Coming here" below. However, I want it to return to the line commented "Not coming here". How can I make this happen.
var app = app || {};
(function(o) {
"use strict";
var ajax, getFormData;
ajax = function(data) {
var xmlhttp = new XMLHttpRequest(), uploaded;
xmlhttp.addEventListener('readystatechange', function() {
if(this.readyState === 4) {
if(this.status === 200) {
var res =this.response;
if(res == 1) {
console.log(res); // Coming here.
}
}
}
});
xmlhttp.open('post', o.options.processor);
xmlhttp.send(data);
};
getFormData = function(source) {
var data = new FormData(), i;
for(i = 0; i < source.files.files.length; i = i + 1) {
data.append('file[]', source.files.files[i]);
}
data.append('ajax', true);
return data;
};
o.uploader = function(options) {
o.options = options;
if(o.options.files !== undefined) {
ajax(getFormData(o.options));
}
}
}(app));
function uploadAndReadURL(input) {
if(input.files && input.files[0]) {
var f = document.getElementById('fileInput');
app.uploader({
files: f,
processor: "/geornal/image",
finished: function(data) {
console.log("burada2."); // Not coming here..
},
error: function() {
console.log('Not working');
}
});
}
}
$(document).ready(function(){
$("#icerik2").on("change", "#fileInput", function(){
uploadAndReadURL(this);
});
});
There is "finished:" section in uploadAndReadURL function. I don't
know how to call "finished" from app function.
Try calling o.options.finished() at if statement within readystatechange handler
if(res == 1) { o.options.finished(res); }

How can i change javascript script into a jquery functional code

Hey guys am new to jQuery,How can I change this javascript code into jQuery functional code so that I call it whenever I want at any object
LIKE: $("#profile_img").uploader();
Apparently this code works fine, but the problem I have is I have to populate the code every time I need to upload a file in a different file input upload.
var input = document.getElementById("choosen_feeds_image"),
formdata = false;
if (window.FormData) {
formdata = new FormData();
document.getElementById("feeds_upload_btn").style.display = "none";
}
if (input.addEventListener) {
input.addEventListener("change", function (evt) {
var i = 0, len = this.files.length, img, reader, file;
document.getElementById("response").innerHTML = ""
for (; i < len; i++) {
file = this.files[i];
if (!!file.type.match(/image.*/)) {
if (window.FileReader) {
reader = new FileReader();
reader.onloadend = function (e) {
showUploadedItem(e.target.result);
};
reader.readAsDataURL(file);
}
if (formdata) {
formdata.append("feeds_image", file);
}
if (formdata) {
$.ajax({
url: "member/feeds_image_upload",
type: "POST",
data: formdata,
processData: false,
contentType: false,
success: function (res) {
if (res.length <= 40) {
document.getElementById('feeds_image_response').innerHTML = res;
$("#feeds_image_response").css('display', 'none');
} else {
document.getElementById("response").innerHTML = res;
$("#response").css('display', 'none');
}
}
});
}
} else {
document.getElementById("response").innerHTML = "";
alert("Sorry, You choose unsupported file");
}
}
}), false
};
you can type all inside a function like this
function uploader(){
console.log('myFuntionUploader');
}
and then call the function like this
uploader();

Handle XMLHttpRequest data

How do I handle XMLHttpRequest data? I have a javascript/angular controller that takes some images and sends it to another page where I want to store the images to a database.
My code lokes like this:
modal.controller('UploadController', function ($scope) {
$scope.files = new Array();
$scope.getFiles = function (element){
$scope.$apply(function($scope){
for (var i = 0; i < element.files.length; i++) {
$scope.files.push(element.files[i])
}
console.log('files lenght : ' + $scope.files.length);
});
};
$scope.uploadFile = function () {
var data = new FormData();
var xhr = new XMLHttpRequest();
for(var i in $scope.files){
data.append("uploadedFile", $scope.files[i])
}
xhr.upload.addEventListener("progress", uploadProgress, false)
xhr.addEventListener("load", uploadComplete, false)
xhr.addEventListener("error", uploadFailed, false)
xhr.addEventListener("abort", uploadCanceled, false)
xhr.open("POST", "fileupload.html")
$scope.progressVisible = true
xhr.send(data);
}
function uploadProgress(evt) {
$scope.$apply(function(){
if (evt.lengthComputable) {
$scope.progress = Math.round(evt.loaded * 100 / evt.total);
} else {
$scope.progress = 'unable to compute';
}
})
}
function uploadComplete(evt) {
alert(evt.target.responseText);
}
function uploadFailed(evt) {
alert("There was an error attempting to upload the file.");
};
function uploadCanceled(evt) {
$scope.$apply(function(){
scope.progressVisible = false;
})
alert("The upload has been canceled by the user or the browser dropped the connection.");
};
});
In the the response text from the alert I get to see the html code from fileupload.html.
How can I recieve the data in fileupload.html so I can store the images in a database?

Categories

Resources