Export selected columns to excel using Vue - javascript

I am newbie to Vue.js.I am trying to export some data to excel file but i don't want all of the data columns to be exported. Rather i need to select few columns.I tried using map function but no luck.Any help really appriciated.Here is my code
<button class="btn_form" #click="exportTo">Export to Excel</button>
exportTo() {
this.form.exportExcel = true
axios.post(route('report'), this.form,
{
responseType: 'blob',
})
.then((response) => {
console.log(response)
const result = response.data.data.map((item) => {
return {
Name: item.firstname + ' ' + item.middlename+ ' ' + item.lastname,
Address: item.table2.res_address+ ' ,' + item.table2.res_city+ ' ,' + item.table2.res_state+ ' ,' + item.table2.res_pincode,
Mobile : item.phone,
Email : item.email,
Place : item.table2.place,
Gender : item.gender,
DOB : item.birthdate
};
});
console.log(result);
const url = window.URL.createObjectURL(new Blob([result]));
const link = document.createElement('a');
link.href = url;
var datetime = new Date().getTime()
link.setAttribute('download',datetime+'reportdata.xlsx');
document.body.appendChild(link);
link.click();
this.form.exportExcel = false
})
.catch((error) => {
this.form= []
})
},
The response data is something like this
{
"data":{
"current_page":1,
"data":[
{
"id":17198,
"f_id":003,
"firstname":"ABC",
"middlename":"M",
"lastname":"XYZ",
"phone":"1234567899",
"email":"xyz#gmail.com",
"faxno":"",
"company_url":"",
"birthdate":"2012-03-06",
"gender":"FEMALE",
"mobile":"1234567899",
"created_at":"2022-01-28T18:05:11.000000Z",
"updated_at":"2022-07-21T11:33:14.000000Z",
"table2":{
"id":18845,
"f_id":003,
"vip_no":950,
"place":"Mumbai",
"res_address":"Q110 Madhav Heights\r\n Goregaon West",
"res_city":"Mumbai",
"res_state":"Goa",
"res_country":"",
"res_pincode":"4000",
"alt_address":"Test address223",
"alt_city":"Testcity",
"alt_state":"Kerala",
"alt_country":"",
"alt_pincode":"4000",
"f_email":"cde123#gmail.com",
"created_at":"2022-04-12T11:41:11.000000Z",
"updated_at":"2022-04-12T11:41:11.000000Z"
}
},
As you see in the code I am trying to export only name,address,mobile,email. Actually my response data is larger than what I have put.So direct export to excel doesn't work. It gives me "Excel cannot open the file because of the file format or file extension is invalid".

Related

Decode href URL link and Redirect Page with Vue.js after POST

I have an example Vue.js setup of two pages. A list of products and then an order form.
https://listorder.netlify.com
ISSUE 1 - The URL passed from products to order page input gets encoded. I have tried to decode with decodeURI() but it still outputs encoded.
<a class="btn btn-primary btn-pill" v-bind:href="'order.html?product=' + decodeURI(item.title) + '&' ?price=' + decodeURI(item.price)" style="color:white;">Buy Now</a>
ISSUE 2 - After POST has completed, I need to redirect to a Paypal page appending data from the "Price" field on the order page. Not sure whether Vue will be required here or to add into the existing javascript.
Paypal page to redirect to https://www.paypal.me/wereallcatshere/USD then append the "price" field
JAVASCRIPT
form.addEventListener('submit', e => {
e.preventDefault()
showLoadingIndicator()
fetch(scriptURL, { method: 'POST', body: new FormData(form) })
.then(response => showSuccessMessage(response))
.catch(error => showErrorMessage(error))
})
function showSuccessMessage(response) {
console.log('Success!', response)
setTimeout(() => {
successMessage.classList.remove('is-hidden')
loading.classList.add('is-hidden')
}, 500)
}
VUE
<script type="text/javascript">
const app = new Vue({
el: '#app',
data: {
items: []
},
created: function () {
fetch('listorder.json')
.then(resp => resp.json())
.then(items => {
this.items = items;
})
},
methods: {
redirect: function () {
window.location.href = "https://www.paypal.me/wereallcatshere/USD" + item.price;
}
}
});

File sharing in html from nodejs

I am making a Chatroom using nodejs. I am using express, socket.io and http for this purpose. I am looking for options to do file sharing over the http server. The preferred file formats are image files(.jpg or .png) and text files. But I am not able to do it. I tried using the input tag of html but it didn't upload any files to the server.
This is my server side code (server.js)
var express = require("express")
, app = express()
, http = require("http").createServer(app)
, bodyParser = require("body-parser")
, io = require("socket.io").listen(app.listen(3000))
, _ = require("underscore");
const file = require('express-fileupload');
app.use(file());
var participants = [];
app.set("ipaddr", "127.0.0.1");
app.set("port", 8080);
app.set("views", __dirname + "/views");
app.set("view engine", "jade");
app.use(express.static("public", __dirname + "/public"));
app.use(bodyParser.json());
app.get("/", function(request, response) {
response.render("index");
});
app.post("/message", function(request, response) {
var message = request.body.message;
if(_.isUndefined(message) || _.isEmpty(message.trim())) {
return response.json(400, {error: "Message is invalid"});
}
var name = request.body.name;
io.sockets.emit("incomingMessage", {message: message, name: name});
response.json(200, {message: "Message received"});
});
io.on("connection", function(socket){
socket.on("newUser", function(data) {
participants.push({id: data.id, name: data.name});
io.sockets.emit("newConnection", {participants: participants});
});
socket.on("nameChange", function(data) {
_.findWhere(participants, {id: socket.id}).name = data.name;
io.sockets.emit("nameChanged", {id: data.id, name: data.name});
});
socket.on("disconnect", function(data) {
participants = _.without(participants,_.findWhere(participants, {id: socket.id}));
io.sockets.emit("userDisconnected", {id: socket.id, sender:"system"});
});
});
http.listen(app.get("port"), app.get("ipaddr"), function() {
console.log("Server ready. IP address: " + app.get("ipaddr") + " ..port:" + app.get("port"));
});
This is the client side code (index.js)
function init() {
var url = document.domain;
var socket = io.connect(url);
var sId = '';
function updateParticipants(mem) {
$('#participants').html('');
for (var i = 0; i < mem.length; i++) {
$('#participants').append('<span id = ' + mem[i].id + '>' +
mem[i].name + ' ' + (mem[i].id === sId ? '(You)' : '') + '<br> </span>');
}
}
socket.on('connect', function () {
sId = socket.io.engine.id;
console.log('Connected ' + sId);
socket.emit('newUser', {id: sId, name: $('#name').val()});
});
socket.on('newConnection', function (data) {
updateParticipants(data.participants);
$('#messages').prepend('<br> New user joined <hr>');
});
socket.on('userDisconnected', function(data) {
$('#' + data.id).remove();
});
socket.on('nameChanged', function (data) {
$('#' + data.id).html(data.name + ' ' + (data.id === sId ? '(You)' : '') + '<br> ');
});
socket.on('incomingMessage', function (data) {
var message = data.message;
var name = data.name;
$('#messages').prepend('<b>' + name + '</b><br>' + message + '<h6 style = "color: green; font-size: 11px">'+new Date().toString()+'</h6>'+'<hr>');
});
socket.on('error', function (reason) {
console.log('Unable to connect to server', reason);
});
function sendMsg() {
var outgoingMessage = $('#outgoingMessage').val();
var name = $('#name').val();
$.ajax({
url: '/message',
type: 'POST',
contentType: 'application/json',
dataType: 'json',
data: JSON.stringify({message: outgoingMessage, name: name})
});
}
function sendAttachment(){
var attachment=$('#attachment').val();
var name = $('#name').val();
$.ajax({
url: '/message',
type: 'POST',
contentType: 'application/json',
dataType: 'json',
data: JSON.stringify({message: outgoingMessage, name: name})
});
}
function msgKeyDown(event) {
if (event.which == 13) {
event.preventDefault();
if ($('#outgoingMessage').val().trim().length <= 0) {
return;
}
sendMsg();
$('#outgoingMessage').val('');
var att = $('#attachment').val();
}
}
function msgKeyUp() {
var outgoingMessageValue = $('#outgoingMessage').val();
$('#send').attr('disabled', (outgoingMessageValue.trim()).length > 0 ? false : true);
}
function focusName() {
var name = $('#name').val();
socket.emit('nameChange', {id: sId, name: name});
}
$('#outgoingMessage').on('keydown', msgKeyDown);
$('#outgoingMessage').on('keyup', msgKeyUp);
$('#name').on('focusout', focusName);
$('#send').on('click', sendMsg);
$('#sendFile').on('click',sendAttachment);
}
$(document).on('ready', init);
And for the front-end I made a Jade file (index.jade)
doctype html
html
head
link(rel='stylesheet', href='http://fonts.googleapis.com/css?family=Open+Sans')
link(rel='stylesheet', href='/css/style.css')
script(src='//code.jquery.com/jquery-1.11.0.min.js')
script(src='/socket.io/socket.io.js')
script(src='/js/index.js')
title Chatroom
body
h1(style="color: red; text-align: center") Live ChatRoom
div(style="color: red;")
div.inlineBlock
span Your name:
input(type="text", value=" ", style="background-color: blue; color: orange; width: 300px; height:40px; font-size: 35px")#name
br
form#messageForm
textarea(rows="7", cols="60", placeholder="Say something and press enter(maximum 300 characters)",maxlength=300, style ="background-color: black;color: yellow; font-size: 20px")#outgoingMessage
br
input(type="button", value="SEND", disabled=true, style="backround-color: purple; color:black; ")#send
div.inlineBlock.topAligned
b Participants
br
div(style = "color: gold")#participants
div(style = "color: Yellow")#messages
Any suggestions how I can do file sharing in the code?
PS The 'express-fileupload' in server.js was a npm package i tried using for file sharing which didn't work.
You are right looking at:
<input type="file" id="input>
Here is an example code, that will send an "image" event via WebSockets after a file has been selected. The logic for handling "image" events should be similar to your "incomingMessage" but I recommend to separate them.
document.getElementById("input").addEventListener("change", function (event) {
// Prepeare file reader
var file = event.target.files[0];
var fileReader = new FileReader();
fileReader.onloadend = function (event) {
var image = event.target.result
// Send an image event to the socket
socket.emit("image", image);
};
// Read file
fileReader.readAsDataURL(file);
})
If you want to display the image coming from a WebSocket, you can simply set the "src" attribute on an image element:
<img src="" id="output />
And the JavaScript that listens for the WebSocket event:
socket.on("image", function (image) {
output.src = image;
});
You can find a complete example for sending images through WebSockets here: https://medium.com/#getflourish/from-mobile-to-desktop-cross-device-communication-using-websockets-f9c48f669c8

VueJS doesn't work on mobile

I have a problem with running VueJS on mobile devices. I created a weather prediction app on copepen.io
Here is the link for the project:
http://codepen.io/techcater/pen/xOZmgv
HTML code:
<div class="container-fluid text-center">
<h1>Your Local Weather</h1>
<p>
{{location}}
</p>
<p>
{{temperature}}
<a #click="changeDegree">{{degree}}</a>
</p>
<p>
{{weather | capitalize}}
</p>
<img :src="iconURL" alt="" />
<br>
by Dale Nguyen
<!-- <pre>{{$data | json}}</pre> -->
</div>
JS code:
new Vue({
el: '.container-fluid',
data: {
location: "",
temperature: "",
degree: "C",
weather: "",
iconURL: ""
},
created: function(){
this.getWeather();
},
methods: {
getWeather: function(){
var that = this;
this.$http.get("http://ipinfo.io").then((response) => {
console.log(response.data);
that.location = response.data.city + ", " + response.data.country;
// Get weather informaiton
var api = 'ebd4d312f85a230d5dc1db91e20c2ace';
var city = response.data.city;
var url = "http://api.openweathermap.org/data/2.5/weather?q={CITY}&APPID={APIKEY}&units=metric";
url = url.replace("{CITY}",city);
url = url.replace("{APIKEY}", api);
that.$http.post(url,{dataType: 'jsonp'},{
headers : {
'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8'
}}).then((response) => {
console.log(response.data);
that.temperature = response.data.main.temp;
that.weather = response.data.weather[0]['description'];
that.iconURL = "http://openweathermap.org/img/w/" + response.data.weather[0]['icon'] + ".png";
}, (response) => {
// error callback
});
}, (response) => {
console.log(response.data);
});
},
changeDegree: function() {
if(this.degree == "C"){
this.degree = "F";
this.temperature = Math.round((this.temperature*9/5 + 32)*100)/100;
}else {
this.degree = "C";
this.temperature = Math.round(((this.temperature - 32)*5 /9)* 100)/100;
}
}
}
})
It works well on my laptop but not on mobile. At first, I thought that it is because of Codepen. It may cause something when running through the site. However, when I created a project on my website, it also doesn't work.
Can you help to find the issue? Thanks,
Your code seems to be working well, except that on codepen it gives me error XMLHttpRequest cannot load http://ipinfo.io/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://s.codepen.io' is therefore not allowed access..
You can put your domain name on headers options to enable cross-origin, here is example:
this.$http.get('http://ipinfo.io', {
'headers': {
'Origin': 'http://yourdomain.com'
}
})
See example: http://bozue.com/weather.html
I also noticed you put vue.min.js and vue-resource.js scripts in wrong order that might trigger some error, vue.min.js should be on the first place.
I found a solution for this. I works on my mobile now. I believe that I will work on other browses too. The problem is that some browsers doesn't recognize the operation ">", so I changed it.
Here is the new code:
getWeather: function(){
var that = this;
this.$http.get('http://ipinfo.io', {'headers': {
'Origin': 'http://yourdomain.com'}
}).then(function(response) {
console.log(response.data);
that.location = response.data.city + ", " + response.data.country;
// Get weather informaiton
var api = 'ebd4d312f85a230d5dc1db91e20c2ace';
var city = response.data.city;
var url = "https://crossorigin.me/http://api.openweathermap.org/data/2.5/weather?q={CITY}&APPID={APIKEY}&units=metric";
url = url.replace("{CITY}",city);
url = url.replace("{APIKEY}", api);
that.$http.post(url,{dataType: 'jsonp'},{
headers : {
'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8'
}}).then(function(response) {
console.log(response.data);
that.temperature = response.data.main.temp;
that.weather = response.data.weather[0]['description'];
that.iconURL = "http://openweathermap.org/img/w/" + response.data.weather[0]['icon'] + ".png";
}).then(function(){
// error callback
});
}).then(function(){
console.log(response.data);
});
},

How to pass parameters in an URL using Plupload script in ASP MVC 4

I'm working with the plupload plug-in in MVC 4 to upload images to the server, this plug-in gives a script which calls an action to apload images.So in this script I want to add code to pass some parameters in the URL but I didn't succeed. I looked for the solution and I found that there is a property in the script to add parameters:
multipart_params: { idflight: [parameter to add]},
so when I give an example of a value to idflight, it works and I find that the parameter passes. but when I try to get a value from a dropdownlist using the code
multipart_params: { idflight: $('#IDFLIGHT').val()},
it gives me the error Failed to load resource: the server responded with a status of 500 (Internal Server Error).
Here is the view:
<div class="editor-label">
#Html.LabelFor(model => model.IDTYPE, "TYPES")
</div>
<div class="editor-field">
#Html.DropDownList("IDTYPE", String.Empty)
#Html.ValidationMessageFor(model => model.IDTYPE)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.IDFLIGHT, "FLIGHTS")
</div>
<div class="editor-field">
**#Html.DropDownList("IDFLIGHT", String.Empty)**
#Html.ValidationMessageFor(model => model.IDFLIGHT)
#Html.ActionLink("Add New flight","Create","Flight",null,new{#style="font-size:16px;", #class="popup"})
</div>
I removed the form tag from it because I don't need it. And this is the script of the plug-in:
<script type="text/javascript">
// Custom example logic
var uploader = new plupload.Uploader({
runtimes: 'html5,flash,silverlight,html4',
browse_button: 'pickfiles', // you can pass in id...
unique_names:true,
container: document.getElementById('container'), // ... or DOM Element itself
**url: '../../../Image/Ajouter',**
flash_swf_url: 'Scripts/Moxie.swf',
silverlight_xap_url: 'Scripts/Moxie.xap',
filters: {
max_file_size: '10mb',
mime_types: [
{ title: "Image files", extensions: "jpg,gif,png" },
{ title: "Zip files", extensions: "zip" }
]
},
**multipart_params: { idflight: $('#IDFLIGHT').val()},**
init: {
PostInit: function () {
document.getElementById('filelist').innerHTML = '';
document.getElementById('uploadfiles').onclick = function () {
uploader.start();
return false;
};
},
FilesAdded: function (up, files) {
plupload.each(files, function (file) {
document.getElementById('filelist').innerHTML += '<div id="' + file.id + '">' + file.name + ' (' + plupload.formatSize(file.size) + ') <b></b></div>';
});
},
UploadProgress: function (up, file) {
document.getElementById(file.id).getElementsByTagName('b')[0].innerHTML = '<span>' + file.percent + "%</span>";
},
Error: function (up, err) {
document.getElementById('console').innerHTML += "\nError #" + err.code + ": " + err.message;
}
}
});
uploader.init();
Thank you in advance

POST 500 (Internal Server Error) when I use the JEditable plugin

I'm trying to use JEditable plugin in my Symfony2 application. PYS entity is a a films and TV shows entity; then I've got Usuario and Critica entities. I want to manage the user's critics with the plugin. I've analyzed more and more examples, but I can not get it to work. The value (in this case the title of critic) is update in the template but not in the db; when I refresh the browser the old value appears.
THE ERROR:
This is my JS:
$('.edit').editable(function(value, settings) {
var data = {};
data[this.id] = value;
console.log(path);
console.log(data);
$.post(path, data);
return(value);
}, {
indicator : 'Saving...',
tooltip : 'Click to edit...'
});
This is the route:
critica_ajax:
locales: { es: "/gestion-critica/{pysStr}/", en: "/manage-critic/{pysStr}/" }
defaults: { _controller: UsuarioBundle:Default:gestionarCritica }
This is the controller:
public function gestionarCriticaAction($pysStr)
{
$em = $this->getDoctrine()->getManager();
$pys = $em->getRepository('PYSBundle:Pys')->findPys($pysStr);
$usuario = $this->get('security.context')->getToken()->getUser();
$critica = $em->getRepository('UsuarioBundle:Usuario')->findCritica($usuario, $pys);
if(!$critica)
{
$critica = new Critica($usuario, $pys);
}
$criTitulo = $this->request->get('value');
$critica->setCriTitulo($criTitulo);
$critica->setCriContenido($criContenido);
$critica->setCriFecha(new \DateTime("now"));
$em->persist($critica);
$em->flush();
return new Response($criTitulo);
}
The Twig template:
<h2 class="edit">{{ critica.criTitulo }}</h2>
<script>
var path = "{{ path('critica_ajax', { 'pysStr': pelicula.pysStr}) }}";
</script>
EDIT (The Symfony's return)
Notice: Undefined property: Filmboot\UsuarioBundle\Controller\DefaultController::$request
in C:\Programming\xampp\htdocs\filmboot\src\Filmboot\UsuarioBundle\Controller\DefaultController.php line 236
THIS IS THE LINE 236: $criTitulo = $this->request->get('value');
at ErrorHandler ->handle ('8', 'Undefined property: Filmboot\UsuarioBundle\Controller\DefaultController::$request', 'C:\Programming\xampp\htdocs\filmboot\src\Filmboot\UsuarioBundle\Controller\DefaultController.php', '236', array('pysStr' => 'machete', 'em' => object(EntityManager), 'pys' => object(Pys), 'usuario' => object(Usuario), 'critica' => object(Critica)))
in C:\Programming\xampp\htdocs\filmboot\src\Filmboot\UsuarioBundle\Controller\DefaultController.php at line 236 +
at DefaultController ->gestionarCriticaAction ('machete')
at call_user_func_array (array(object(DefaultController), 'gestionarCriticaAction'), array('machete'))
in C:\Programming\xampp\htdocs\filmboot\app\bootstrap.php.cache at line 1003 +
at HttpKernel ->handleRaw (object(Request), '1')
in C:\Programming\xampp\htdocs\filmboot\app\bootstrap.php.cache at line 977 +
at HttpKernel ->handle (object(Request), '1', true)
in C:\Programming\xampp\htdocs\filmboot\app\bootstrap.php.cache at line 1103 +
at ContainerAwareHttpKernel ->handle (object(Request), '1', true)
in C:\Programming\xampp\htdocs\filmboot\app\bootstrap.php.cache at line 413 +
at Kernel ->handle (object(Request))
in C:\Programming\xampp\htdocs\filmboot\web\app_dev.php at line 26 +
You need to get the request like this :
$request = $this->getRequest();
instead of
$request = $this->request;
the request is returned using a method its not a class property

Categories