Text input elements returning 'undefined' to .csv file - node.js

EDIT: I figured the problem out. It had turned out I was appending the items to themselves. The correct method I worked out would be to make a new variable as such:
var form = document.getElementById("listItems");
and then editing the document.body.appendChild(itemName); to
form.appendChild(itemName) and form.appendChild(itemQuantity) respectively.
For context, the call to the backend looked as such:
<form action="/buy" method=post id="listItems">
<input type="submit" value="Send">
</form>
When creating text boxes, I save the contents to a .csv file, however when I access these files I am returned a value of 'undefined'.
I looked into the code, and found that the input is saving itself as undefined no matter what was put in the text box.
Specifically these text boxes,
<script>
function addItems(){
var itemName = document.createElement("input");
itemName.setAttribute('type', 'text');
itemName.placeholder = "itemName";
document.body.appendChild(itemName);
var itemQuantity = document.createElement("input");
itemQuantity.setAttribute('type', 'text');
itemQuantity.placeholder = "itemQuantity";
document.body.appendChild(itemQuantity);
}
</script>
var itemName and itemQuantity show up in console.log and in the file as undefined values.
What should've happened was that when I ran:
var itemN = req.body.itemName;
var itemQ = req.body.itemQuantity;
await fs.appendFile('receipt.csv', "\n" + itemN + " " + itemQ, err => {
if (err) {
console.error(err);
}
console.log(itemN, itemQ);
// done!
})
It should have appended to the file 'receipt.csv' as ItemN + ItemQ as a string, however when accessed the file shows the submitted text as: Undefined Undefined.

Related

Why me subscribe method in angular is not working?

I'm new in Angular, Nodejs and I was doing a CRUD app of txt files
I have to list all the files in a list, if you click one file need to display the data on a 'P'aragraph
My document component
getDocuments() - returns an array of all files in a path
getOneDOcument(name) -> get all the data of a file given "name"
getData(name) -> have to send the data to the paragraph with the id _> "paragraph_content"
getDocuments(){
this.DocumentService.getDocuments()
.subscribe(res => {
this.DocumentService.documents = res as Document[]
console.log("dentro del susbcribe");
console.log(res);
});
console.log("Fuera del subscribe");
}
getOneDocument(name : String){
console.log("NOO");
this.DocumentService.getOneDocument(name).subscribe(res => {
this.DocumentService.documentSelected = res as Document;
console.log(".");
});
}
getData(name : String){
console.log("hello name -> " , name)
// document.getElementById("paragraph_content").innerHTML = this.DocumentService.getOneDocument(name)
console.log("Before the subscrie");
this.DocumentService.getOneDocument(name)
.subscribe( (res ) =>{
//I need to change the paragraph content like this
//document.getElementById("paragraph_content").innerHTML = res.toString() Not working
console.log("Within", res);
} )
console.log("After Subscribe ")
}
Document Service
I got the arrays of the url given
getDocuments(){
console.log("Get Documents method");
return this.http.get(this.URL_API );
}
getOneDocument(name: String){
console.log("Get OneDocyment method name given: " , name);
return this.http.get(this.URL_API + `/${name}`)
}
postDocument(){
//left
}
deleteDocument(name:String){
//left
}
Document Component html
<nav>
<ul class="ds-list-unstyled" *ngFor="let document of DocumentService.documents">
<li> {{document}} </li>
</ul>
</nav>
<article>
<h2>Texto en pantalla: </h2>
<p id="paragraph_content">Needs to change with a click
</p>
</article>
And the responde that I got when I click a file is:
Thanks in advance
The XMLHttpRequest property responseType is an enumerated string value specifying the type of data contained in the response. It also lets the author change the response type.
You should set the responseType to text.
Try like this
getOneDocument(name: String){
console.log("Get OneDocyment method name given: " , name);
const requestOptions: Object = {
responseType: 'text'
}
return this.http.get(`${this.URL_API}/${name}`,requestOptions )
}
I think you problem is that you are not specifying that the data is text, that is why is trying to convert to JSON.
Try adding the responseType to the request, something like this,
getOneDocument(name: String){
return this.http.get(`${this.URL_API}/${name}`, {responseType: 'text'})
}

nodeJS how to use router to add icon tag into pug file?

Hello I think it's easier to show partial lines of my code.
What I'm trying to do is when I input a zipcode, the right icon will show.
I'm using https://erikflowers.github.io/weather-icons/ this git.
for example: if NY weather condition says clear
weather condition in weather.pug should be like i.wi.wi-night-sleet
is it possible to add class name in icon tag from topic.js? or
can I use equal statement in pug flie like - if text=='clear' i.wi.wi-night-sleet
topic.js
router.post('/weather', function(req,res){
let url = `http://api.openweathermap.org/data/2.5/weather?zip=${req.body.zipcode}&units=imperial&appid=${apiKey}`
request(url, function (err, response, body) {
if(err){
res.status(500).send('Internal Server Error');
console.log('error: ' ,err);
} else {
if(req.body.zipcode.length != 5) {
res.render('topic/weather', {text: "Zipcode does not exist"})
} else {
let weather = JSON.parse(body)
let temp = weather.main.temp
let location = weather.name;
let day_weather = weather.weather[0].main;
let message = `It's ${weather.main.temp} degrees in ${weather.name}!`;
//below this I want to call icon tag that has a class name
res.render('topic/weather', {text: location + " : " + day_weather, weatherCondition: `i.wi.wi-night-sleet`});
}
}
});
})
weather.pug
extends ./homepage
block navigate
div.container-fluid
div.row.row-centered
p= text
//- space 넣을떄
= " "
if text
= date
div.col-lg-6.col-centered
form.form-group(action='/weather', method='post')
p
input(type='text', class="form-control", id="zipcode",name='zipcode', placeholder='zipcode')
p
button(type='submit', class="btn btn-primary btn-lg" style='margin-right: 10px;') Login
In your route just pass the identifying part of the icon you need:
res.render('topic/weather', {text: location + " : " + day_weather, weatherCondition: "night-sleet"});
Then here's what your pug template needs to look like:
i.wi(class= 'wi-' + weatherCondition)
or
i(class= 'wi wi-' + weatherCondition)
Either of those lines of pug will produce the same html:
<i class="wi wi-night-sleet"></i>

handling JSOM clientcontext properly

I am trying out JSOM in Sharepoint 2016. I have made a WebPart containing the following code -
<div id="user-output"></div>
Movie Title: <input type="text" id="movie-title" /><br />
Description: <input type="text" id="movie-description" /><br />
<button type="button" id="submit-button">Add Movie</button>
<div id="movies-output"></div>
<script type="text/javascript" src="/SiteAssets/jquery-3.2.1.min.js"></script>
<script type="text/ecmascript" src="../_layouts/15/SP.UserProfiles.js"></script>
<script type="text/javascript">
$(function () {
$('#submit-button').on('click', function () {
var context = SP.ClientContext.get_current();
var movies = context.get_web().get_lists().getByTitle('Movies');
var movieCreationInfo = new SP.ListItemCreationInformation();
var movie = movies.addItem(movieCreationInfo);
movie.set_item("Title", $('#movie-title').val());
movie.set_item("MovieDescription", $('#movie-description').val());
movie.update();
context.load(movie);
context.executeQueryAsync(success, failure);
});
function success() {
$('#movies-output').text('Created movie!');
}
function failure() {
$('#movies-output').text('Something went wrong');
}
var upp;
// Ensure that the SP.UserProfiles.js file is loaded before the custom code runs.
//SP.SOD.executeOrDelayUntilScriptLoaded(getUserProperties, 'SP.UserProfiles.js');
SP.SOD.executeFunc('userprofile', 'SP.UserProfiles.PeopleManager', getUserProperties);
//SP.SOD.executeFunc('SP.UserProfiles.js', getUserProperties);
function getUserProperties() {
// Get the current client context and PeopleManager instance.
var clientContext = new SP.ClientContext.get_current();
var peopleManager = new SP.UserProfiles.PeopleManager(clientContext);
upp = peopleManager.getMyProperties();
clientContext.load(upp, 'UserProfileProperties');
clientContext.executeQueryAsync(onRequestSuccess, onRequestFail);
}
// This function runs if the executeQueryAsync call succeeds.
function onRequestSuccess() {
$('#user-output').html('User Name: ' + upp.get_userProfileProperties()['PreferredName'] +
'<br/>Department: ' + upp.get_userProfileProperties()['Department'] +
'<br/>Designation: ' + upp.get_userProfileProperties()['Title'] +
'<br/>Employee ID: ' + upp.get_userProfileProperties()['EmployeeID'] +
'<br/>Branch Code: ' + upp.get_userProfileProperties()['branchCode']
);
}
// This function runs if the executeQueryAsync call fails.
function onRequestFail(sender, args) {
$('#user-output').text("Error: " + args.get_message());
}
});
What this code does is -
Show user information in user-output div at document load ready
Saves a movie record when Add Movie button is clicked
However, for some reason, when Add Movie button is clicked, the code adds two movies instead of one. I think it has something to do with the ClientContext. But I am not sure why, or how to solve it. Can anyone help?
I am not sure how it happened, or if it's a bug, but while fiddling with the page source to find out why double posting was occurring, I saw that my web part code was being rendered twice in the page. One part was visible, and another was under a hidden div. However, when I went to edit page to delete the hidden web part, I couldn't. So I restored my page to the template version and re-added the web part. After that the web part was working correctly. There were no problems with the code.

How to get the value of Liferay input editor in a javascript variable

In my application i am using liferay-ui:input-editor .I want to get the value of input editor to a javascript variable, How to achieve that?? I have tried
<liferay-ui:input-editor />
<input name="<portlet:namespace />htmlCodeFromEditorPlacedHere" type="hidden" value="" />
function createPopUp(){
var url ="<%=fetchCandidateByIdForPhoneURL%>";
var type= "fetchCandidateInfo";
var candidateId = $('#candidateID').val();
var jobId = $('#JobList').val();
var text1 = $('#text1').val();
var text2 = $('#text2').val();
var text3 = $('#text3').val();
var interviewVenue = $('#interviewVenue').val();
var interviewCC = $('#interviewCC').val();
var interviewBCC =$('#interviewBCC').val();
var startDate = $('#start-date').val();
var interviewType = $('#interviewType').val();
var x ;
function <portlet:namespace />initEditor() {
return '<font style="font-weight: bold">scott was here</font>';
}
function <portlet:namespace />extractCodeFromEditor() {
var x = document.<portlet:namespace />fm.<portlet:namespace />htmlCodeFromEditorPlacedHere.value = window.<portlet:namespace />editor.getHTML();
alert(x);
}
But it is showing that
ReferenceError: _InterviewSchedule_WAR_InterviewScheduleportlet_initEditor is not defined error. How to resolve it and get the value in a javascript variable
Given the information provided in question, it seems that the javascript initialization function is missing for <liferay-ui:input-editor />. As pointed out in the tutorial here, which OP seems to be using (juding by variable names):
By default, the editor will call "initEditor()" to try and pre-populate the body of the editor. In this example, when the editor loads, it will have the value of "scott was here" in bold.
(...)
function <portlet:namespace />initEditor() {
return '<font style="font-weight: bold">scott was here</font>';
}
By default, the ck editor that Liferay uses will try to call the initEditor() javascript method to try and pre-populate the contents of the editor.
Therefore, you should define such a method, even if you return a blank string.
An example is given below:
<aui:script>
function <portlet:namespace />initEditor() {
return "<%= content %>";
}
</aui:script>
, where content is the string variable with the content you want to pass in when the editor is loaded. If you do not want to pass initial content then simply pass a black string.

Get Attribute Values From Child Element With No ID - JQuery

Lets say I have this code:
<div id="Element_1" class="draggable">
<input type="text" placeholder="Enter Your Text Here" style="width:300px;">
</div>
<div id="Element_2" class="draggable">
<textarea placeholder="Enter Your Text Here" style="width:400px;height:200px;"></textarea>
</div>
What I am trying to do is get the element attribute values, from the child of the "div" and also the "Type" (Input/Tagname) so I can store the values in variables.
Currently I can get the element and store in a Var, this is the code I have:
$(".draggable").live("click",function(){
var SelectedID = $(this).attr("id");
$("*").removeClass("selected");
var Element = $("#"+SelectedID,":first-child").addClass("selected").html();
PlaceholderPropValue = $(element).attr("placeholder");
StylesPropValue = $(element).attr("style");
WidthProp = StylesProp.match(/(width:)([0-9].*?)(?=px;)/)[2];
HeightProp = StylesProp.match(/(height:)([0-9].*?)(?=px;)/)[2];
alert(PlaceholderPropValue+ " " +WidthProp+ " " +HeightProp);
});
Thanks!
Carl
Your code is kind of overkill.
.live() is deprecated in jQuery 1.7 and totally removed in 1.9, jquery documentation says you should use .on() instead.
Everything is simple. You can try something like:
$('.draggable').click(function(){
var $element = $(this).children();
var width = parseInt($element.width());
var height = parseInt($element.height());
var placeholder = $element.attr('placeholder');
alert(placeholder+ " " +width+ " " +height);
})
.children() method normally return set of element's children but there are only one in your example, so it's ok.
.width() and .height() returns values like "300px", so we use parseInt() to make int values.
.click(handler) is a shortcut for .on( "click", handler )

Resources