jsZip - execute generateAsync after Ajax post success - jszip

I have number if files to be added in the zip file. some are optional (user choice). I like to execute the generateAsync once all required files Ajax post is successful.
I tried to place a check but its not working.
SAMPLE CODES:
var requestCSS;
var StyleFileData;
var requestAnimatedJS;
var AnimatedScriptData;
function getAllFiles(complileComplete){
requestCSS = $.ajax({
url: 'css/styles.css',
type: "GET",
contentType: "text/css",
mimeType:'text/plain; charset=x-user-defined',
success: function (data){
StyleFileData = data;
}
});
if(animatedBG){
requestAnimatedJS = $.ajax({
url: 'js/animated.js',
type: "GET",
contentType: "text/javascript",
mimeType:'text/plain; charset=x-user-defined',
//async: false,
success: function (data){
AnimatedScriptData = data;
}
});
} else {
requestAnimatedJS = '';
}
}
$('#saveProject').on('click', function(){
getAllFiles(complileComplete);
if(complileComplete === true) {
var zip = new JSZip();
var jsFiles;
var cssFiles;
zip.file("index.html", fullHTML);
jsFiles = zip.folder("js");
cssFiles = zip.folder("css");
requestCSS.done( function( data ) {
cssFiles.file("styles.css", data, { binary: true });
});
if(animatedBG){
requestAnimatedJS.done( function( data ) {
jsFiles.file("particles.js", data, { binary: true });
});
}
zip.generateAsync({type:"blob"})
.then(function(content) {
saveAs(content, "Sample.zip");
});
}
});
No server side or node.js is involved.

Related

JQuery-File-Upload using Signed_URL Google Storage, how to call super class function data.submit() within ajax callback?

I have a fileupload HTML element in my DOM and it currently gets multiple files and calls "add" function for each file. For each file, a signed url is received from an ajax call to the related api. After the succesful ajax call to api, I want to call the data.submit() method of the parent function which is the function in fileupload method as first argument.
How may I be able to access that just after "xhr.setRequestHeader('Content-Type', file.type);" ?
The primary inspiration is from this link :http://kevindhawkins.com/blog/django-javascript-uploading-to-google-cloud-storage/
$("#fileupload").fileupload({
dataType: 'json',
sequentialUploads: true,
add: function(e, data) {
$.each(data.files, function(index, file) {
// pack our data to get signature url
var formData = new FormData();
formData.append('filename', file.name);
formData.append('type', file.type);
formData.append('size', file.size);
// Step 3: get our signature URL
$.ajax({
url: '/api/getsignedurl/',
type: 'POST',
processData: false,
contentType: false,
dataType: 'json',
headers: {
'X-CSRFToken': Cookies.get('csrftoken'),
},
context: 'hello',
data: formData,
}).done(function (data) {
// Step 5: got our url, push to GCS
const xhr = new XMLHttpRequest();
if ('withCredentials' in xhr) {
xhr.open("PUT", data.signed_url, true);
}
else if (typeof XDomainRequest !== 'undefined') {
xhr = new XDomainRequest();
xhr.open("PUT", data.signed_url);
}
else {
xhr = null;
}
xhr.onload = () => {
const status = xhr.status;
if (status === 200) {
//alert("File is uploaded");
} else {
}
};
xhr.onerror = () => {
};
xhr.setRequestHeader('Content-Type', file.type);
//data.submit();
});
});
},
If the $this = $(this) is defined prior to the $.each loop :
submit: function(e, data) {
var $this = $(this);
$.each(data.files, function(index, file) { ...
Then the following can be used to access the data in the parent function
this.primary_data.headers={'Content-Type': file.type};
this.primary_data.jqXHR = $this.fileupload('send', this.primary_data);

Facing error in insertion while using webservices and ajax jquery

WHEN I FILL THE FORM IN HTML,I FACE ERROR OF 500. MY WEBSERVICE IS NOT WORKING. WHEN I COPYPASTE URL AND OPEN IN NEW TABLE THEN IT SHOWS BELOW ERROR.
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = true)]
public void addNewUser(string name,string address,string email, string phoneno, string pin)
{
JavaScriptSerializer ser = new JavaScriptSerializer();
string Message = "";
try
{
using (MySqlConnection connection = new MySqlConnection(DBconnect.ConnectionString))
{
MySqlCommand cmd = new MySqlCommand("INSERT INTO users(name,address,email,phoneno,pin) VALUES(#name,#address,#email,#phoneno,#pin)", connection);
cmd.Parameters.AddWithValue("#name", name);
cmd.Parameters.AddWithValue("#address", address);
cmd.Parameters.AddWithValue("#email", email);
cmd.Parameters.AddWithValue("#phoneno", phoneno);
cmd.Parameters.AddWithValue("#pin", pin);
connection.Open();
cmd.ExecuteNonQuery();
connection.Close();
}
Message = "New User is added Successfully.";
}
catch (Exception ex)
{
Message = "Not Added";
}
var JSonData = new
{
Message = Message
};
HttpContext.Current.Response.Write(ser.Serialize(JSonData));
}
<script type="text/javascript">
$(document).ready(function () {
$("#btnAdduser").on('click', function (e)
{
e.preventDefault();
var All_users = {};
All_users.name = $('#name').val();
All_users.address = $('#address').val();
All_users.email = $('#email').val();
All_users.phoneno = $('#phoneno').val();
All_users.pin = $('#pin').val();
var jsonData = JSON.stringify({
All_users: All_users
});
$.ajax({
type: "POST",
url: "http://localhost/WebApi/WebService.asmx?op=addNewUser",
data: jsonData,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
error: OnErrorCall
});
function OnSuccess(response) {
var result = response.d;
if (result == "success") {
$("#msg").html("New record addded successfully :)").css("color", "green");
}
$("#name").val("");
$("#address").val("");
$("#email").val("");
$("#phoneno").val("");
$("#pin").val("");
}
function OnErrorCall(response) {
$("#msg").html("Error occurs :(").css("color", "red");
}
});
});
</script>
*
System.InvalidOperationException: Missing parameter: name. at
System.Web.Services.Protocols.ValueCollectionParameterReader.Read(NameValueCollection
collection) at
System.Web.Services.Protocols.HttpServerProtocol.ReadParameters()
at
System.Web.Services.Protocols.WebServiceHandler.CoreProcessRequest()
*
I tried reproducing your case.
The problem is UseHttpGet = true, change to UseHttpGet = false and also check that attribute in class [System.Web.Script.Services.ScriptService]
and update your AJAX call by WebService.asmx/addNewUser like this, it worked
<script
src="https://code.jquery.com/jquery-3.3.1.js"
integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60="
crossorigin="anonymous"></script>
<button id="btnAdduser">Test</button>
<script type="text/javascript">
$(document).ready(function () {
$("#btnAdduser").on('click', function (e)
{
e.preventDefault();
var All_users = {};
All_users.name = "Hien";
All_users.address = "Test";
All_users.email = "Test";
All_users.phoneno = "Test";
All_users.pin = "123";
var jsonData = JSON.stringify({
data: All_users
});
$.ajax({
type: "POST",
url:
"http://localhost/WebApi/WebService.asmx/addNewUser",
data: JSON.stringify(All_users),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
error: OnErrorCall
});
function OnSuccess(response) {
var result = response.d;
if (result == "success") {
$("#msg").html("New record addded successfully :)").css("color", "green");
}
$("#name").val("");
$("#address").val("");
$("#email").val("");
$("#phoneno").val("");
$("#pin").val("");
}
function OnErrorCall(response) {
$("#msg").html("Error occurs :(").css("color", "red");
}
});
});
</script>

How to POST data for evaluation in middleware in loopback?

I want to use custom API to evaluate data which are posted by applications but remote methods are not accepted in middleware in loopback
module.exports = function () {
const http = require('https');
var request = require('request');
var { Lib } = require('Lib');
var lib = new Lib;
verification.checkID = function (ID, cb) {
cb(null, 'ID is :' + ID);
}
verification.remoteMethod('greet', {
accepts: {
arg: 'ID',
type: 'string'
},
returns: {
arg: 'OK',
type: 'string'
}
});
module.exports = function () {
const http = require('https');
var request = require('request');
var { Lib } = require('Lib');
var lib = new Lib;
verification.checkID = function (ID, cb) {
cb(null, 'ID is :' + ID);
}
verification.remoteMethod('greet', {
'http': { // add the verb here
'path': '/greet',
'verb': 'post'
},
accepts: {
arg: 'ID',
type: 'string'
},
returns: {
arg: 'OK',
type: 'string'
}
});
Update
module.exports = function(server) {
// Install a `/` route that returns server status
var router = server.loopback.Router();
router.get('/', server.loopback.status());
router.get('/ping', function(req, res) { // your middle ware function now you need to call the next() here
res.send('pong');
});
server.use(router);
};
To evaluate is something i am not getting please check this link too Intercepting error handling with loopback
Regarding to fallowing question How to make a simple API for post method?
I find my solution in fallowing way:
module.exports = function(server) {
const https = require('https');
var request = require('request');
return function verification(req, res, next) {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
res.setHeader('Access-Control-Allow-Credentials', true);
var request;
var response;
var body = '';
// When a chunk of data arrives.
req.on('data', function (chunk) {
// Append it.
body += chunk;
});
// When finished with data.
req.on('end', function () {
// Show what just arrived if POST.
if (req.method === 'POST') {
console.log(body);
}
// Which method?
switch (req.method) {
case 'GET':
Verify url and respond with appropriate data.
handleGet(req, res);
Response has already been sent.
response = '';
break;
case 'POST':
// Verify JSON request and respond with stringified JSON response.
response = handlePost(body);
break;
default:
response = JSON.stringify({ 'error': 'Not A POST' });
break;
}
// Send the response if not empty.
if (response.length !== 0) {
res.write(response);
res.end();
}
// Paranoid clear of the 'body'. Seems to work without
// this, but I don't trust it...
body = '';
});
// If error.
req.on('error', function (err) {
res.write(JSON.stringify({ 'error': err.message }));
res.end();
});
//
};
function handlePost(body) {
var response = '';
var obj = JSON.parse(body);
// Error if no 'fcn' property.
if (obj['fcn'] === 'undefined') {
return JSON.stringify({ 'error': 'Request method missing' });
}
// Which function.
switch (obj['fcn']) {
// Calculate() requres 3 arguments.
case 'verification':
// Error if no arguments.
if ((obj['arg'] === 'undefined') || (obj['arg'].length !== 3)) {
response = JSON.stringify({ 'error': 'Arguments missing' });
break;
}
// Return with response from method.
response = verification(obj['arg']);
break;
default:
response = JSON.stringify({ 'error': 'Unknown function' });
break;
}
return response;
};
function verification(arg) {
var n1 = Number(arg[0]);
var n2 = Number(arg[1]);
var n3 = Number(arg[2]);
var result;
// Addem up.
result = n1 + n2 + n3;
// Return with JSON string.
return JSON.stringify({ 'result': result });
};
};

AWS Lambda Get Image and Upload to S3

I am working in a AWS Lambda function. I am successfully making an API call to the NASA APOD and getting back the values. I want to take the url for the image and download that image and then upload into S3. I am getting an error when I try to access the "test.jpg" image, "Error: EACCES: permission denied, open 'test.jpg'". If I move the S3bucket.putObject outside the http.request, I get data is equal to null. I know I am missing something simple. Thought?
function GetAPOD(intent, session, callback) {
var nasa_api_key = 'demo-key'
, nasa_api_path = '/planetary/apod?api_key=' + nasa_api_key;
var options = {
host: 'api.nasa.gov',
port: 443,
path: nasa_api_path,
method: 'GET'
};
var req = https.request(options, function (res) {
res.setEncoding('utf-8');
var responseString = '';
res.on('data', function (data) {
responseString += data;
});
res.on('end', function () {
console.log('API Response: ' + responseString);
var responseObject = JSON.parse(responseString)
, image_date = responseObject['date']
, image_title = responseObject['title']
, image_url = responseObject['url']
, image_hdurl = responseObject['hdurl']
, image_desc = responseObject['explanation'];
var s3Bucket = new AWS.S3( { params: {Bucket: 'nasa-apod'} } );
var fs = require('fs');
var file = fs.createWriteStream("test.jpg");
var request = http.get(image_url, function(response) {
response.pipe(file);
var data = {Key: "test.jpg", Body: file};
s3Bucket.putObject(data, function(err, data) {
if (err) {
console.log('Error uploading data: ', data);
}
else {
console.log('succesfully uploaded the image!');
}
});
});
});
});
req.on('error', function (e) {
console.error('HTTP error: ' + e.message);
});
//req.write();
req.end();
}
You need to be writing the file to /tmp. That's the only directory in the Lambda environment that you will have write access to.
I got it!! Thank you Mark B for the help. I was able to get the data from the stream without saving it locally and then writing to the bucket. I did have to change my IAM role to allow the putObject for S3.
function GetAPOD(intent, session, callback) {
var nasa_api_key = 'demo-key'
, nasa_api_path = '/planetary/apod?api_key=' + nasa_api_key;
var options = {
host: 'api.nasa.gov',
port: 443,
path: nasa_api_path,
method: 'GET'
};
var req = https.request(options, function (res) {
res.setEncoding('utf-8');
var responseString = '';
res.on('data', function (data) {
responseString += data;
});
res.on('end', function () {
// console.log('API Response: ' + responseString);
var responseObject = JSON.parse(responseString)
, image_date = responseObject['date']
, image_title = responseObject['title']
, image_url = responseObject['url']
, image_hdurl = responseObject['hdurl']
, image_desc = responseObject['explanation'];
var image_name = image_date + '.jpg';
var s3 = new AWS.S3();
var s3Bucket = new AWS.S3( { params: {Bucket: 'nasa-apod'} } );
var request = http.get(image_url, function(response) {
var image_stream = null;
response.on('data', function (data) {
image_stream = data;
});
response.on('end', function () {
var param_data = {Key: image_name, Body: image_stream, ContentType: "image/jpeg", ContentLength: response.headers['content-length']};
s3Bucket.putObject(param_data, function(err, output_data) {
if (err) {
console.log('Error uploading data to S3: ' + err);
}
});
});
});
request.end();
});
});
req.on('error', function (e) {
console.error('HTTP error: ' + e.message);
});
req.end();
}

javascript combine two with IF

I am trying to combine two javascripts to one using IF.
I want IF script1 is True to run only script1.
And IF script1 is False to run script2.
Script1= Check all field with "required" if empty in a contact form.
Script2= Send email using ajax.
Script1
$('document').ready(function () {
$('form#contact-form').submit(function(e) {
var ref = $(this).find("[required]");
$(ref).each(function(){
if ( $(this).val() == '' )
{
alert("Required field should not be blank.");
$(this).focus();
e.preventDefault();
return false;
}
}); return true;
});
});
Script2
$('document').ready(function () {
$('form#contact-form').submit(function () {
var form = $(this);
var post_data = form.serialize(); //Serialized the form data for process.php
$('#loader').html('<img src="../spinner.gif" /> Please Wait...');
form.fadeOut(500, function () {
form.html("<h3>Thank you.").fadeIn();
$('#loader').html('');
});
// Normally would use this
$.ajax({
type: 'POST',
url: 'process.php', // Your form script
data: post_data,
success: function(msg) {
form.fadeOut(500, function(){
form.html(msg).fadeIn();
});
}
});
return false;
});
});
This script should work for you.
$('document').ready(function() {
$('form#contact-form').submit(function (e) {
var valid = true;
var ref = $(this).find("[required]");
$(ref).each(function(){
if ($(this).val() == '' )
{
alert("Required field should not be blank.");
$(this).focus();
e.preventDefault();
valid = false;
return false;
}
});
if (valid){
var form = $(this);
var post_data = form.serialize(); //Serialized the form data for process.php
$('#loader').html('<img src="../spinner.gif" /> Please Wait...');
form.fadeOut(500, function () {
form.html("<h3>Thank you.").fadeIn();
$('#loader').html('');
});
// Normally would use this
$.ajax({
type: 'POST',
url: 'process.php', // Your form script
data: post_data,
success: function(msg) {
form.fadeOut(500, function(){
form.html(msg).fadeIn();
});
}
});
}
});
});
Combined both script and added/ introduced "valid" variable to validate if 'required' fields are valid.