Form OnClick ReferenceError: comment is not defined - forms

I'm trying to update my comment system and have run in to a snag. This is the error firebug is showing : ReferenceError: comment is not defined : comment(1000);
I'm at a loss to what the issue is - any ideas?
<div class="comment_heading">Leave a Comment</div>
<div class="post_comment">
<textarea name="txtpostcomment" id="txtpostcomment-1000" class="txtpostcomment"></textarea>
<button class="btnpostcomment" id="btnpostcomment-1000" onclick="comment(1000);" type="button">Send</button>
<input type="hidden" name="token" id="token" value="19vtyWh5iOpeKamXAQl3udqU9mMjnfKv/LnWr70M2jE=">
</div>
<script>
function comment(postid1)
{
var txt = $('#txtpostcomment-'+postid1);
var btn = $('#btnpostcomment-'+postid1);
var comment1 = $(txt).val();
var token = $("#token").val();
$(btn).css('background-image', 'url(/comments/submit-busy.gif)');
$(btn).attr('disabled', true);
var dataString = 'commenting=1&postid=' + postid1 + '&comment=' + comment1 + '&name=' + name + '&token=' + token;
.ajax({
url: "/comments/submit.php",
type: "POST",
data: dataString,
cache: false,
success: function()
{
$('.post_comment .error_msg').remove();
$('.comment-list-'+postid1).prepend(msg.html);
$(txt).val('');
},
error: function()
{
$('.post_comment .error_msg').value = 'Error - Please try again';
}
});
$(btn).css('background-image', 'none');
$(btn).attr('disabled', false);
$(txt).attr('disabled', false);
}
</script>

Solved .. all I needed to change was :
.ajax({
To :
$.ajax({

Related

When we pass the Object using fetch api in Fakeapi , obj doesn't add in 101 id

I am a trying to pass the object using fetch api in JsonPacehoder Post api and print the value of then method but then methods returns blank object . this object only carry id not holdes my values. so i am dont understand what kind of problem in this code please help me....
<body>
<h1>i am a heading</h1>
<input type="text" id="title" title="title" >
<input type="text" id="body">
<input type="text" id="userId">
<button onclick="myFunction()">ok</button>
<script>
async function myFunction(){
let title_Value = document.getElementById("title").value;
let body_Value = document.getElementById("body").value;
let userId_Value = document.getElementById("userId").value;
let obj = {
title: "title_Value",
body: "body_Value",
userId: "userId_Value",
}
await fetch('https://jsonplaceholder.typicode.com/posts' ,
{
method: "POST",
body : JSON.stringify(obj),
headers: {
'Accept': 'application/json',
"contentType" : "application/json; charset=UTF-8",
},
})
.then((resolve)=> resolve.json())
.then((result)=> console.log(result))
}
Here the output
>{id: 101}
id: 101
>[[Prototype]]: Object

VueJS lifecycle after submit form

I would like to plot some d3js chars in vuejs after performing an API call to get some data. To do so, I created a form whose input is used to collect the data from the API. Once I submit the form, I call my d3js function to plot the charts based on the retrieved data. I want the plotting functions to be called only when the data is not empty. To do so, I used the conditional rendering v-if based on the length of the data. So far so good. My problem is that once the plots are rendered if I type anything in the form, a new plot will be created as if every time the if statement is evaluated again and again, I don't know if it is related to lifecycle or not, but how can avoid this behavior?
<template>
<meta charset="utf-8">
<h4>Associate Information</h4>
<form #submit.prevent="onSubmit">
<input placeholder="Associate Id" v-model="associateId" /> <br />
<input placeholder="Starting date" v-model="initialDate" /> <br />
<input placeholder="Ending date" v-model="finalDate" /> <br />
<button v-on:click="getAssociatesbyIdAndDates()">submit</button>
</form>
<div class="chart" v-if="dailyData.length">
{{ DailyBillabilityLinePlot() }}
{{ WeeklyMonthlyQuarterlyBarPlot(weeklyData) }}
</div>
<div class="linePlot"></div>
<div class="barPlot" v-if="weeklyData.length">
<button v-on:click="WeeklyMonthlyQuarterlyBarPlot(weeklyData)">Weekly</button>
<button v-on:click="WeeklyMonthlyQuarterlyBarPlot(monthlyData)">Monthly</button>
<svg id="chart" viewBox="0 0 960 300"></svg>
</div>
</template>
<script>
import * as d3 from 'd3'
export default {
name: 'Timecard',
props: {
msg: String
},
data() {
return {
apiUrl: "",
myNumber: 0,
environment: "",
apiTst:"",
name:"",
initialDate: "",
finalDate: "",
associateId: "",
dailyData: [],
weeklyData:[],
monthlyData:[],
}
},
methods: {
WeeklyMonthlyQuarterlyBarPlot(data){
// plot a d3 bar plot
},
DailyBillabilityLinePlot() { // plot another d3 line plot}
getAssociatesbyIdAndDates() {
// Connect to the backend and get the list of associates
// http://localhost:8080/timecards/period/test/274/2020-04-14/2020-04-22
console.log("Fetching the data for an associates from the backend based on initial date and final date...");
this.axios.get(this.apiUrl + "test/period/test/" + this.associateId + "/" + this.initialDate + "/" + this.finalDate)
.then(response => {
this.dailyData = response.data;
console.log(response.status);
})
.catch(error => {
console.error(error);
})
this.axios.get(this.apiUrl + "test/weekly/" + this.associateId + "/" + this.initialDate + "/" + this.finalDate)
.then(response => {
this.weeklyData = response.data;
console.log(response.status);
})
.catch(error => {
console.error(error);
})
this.axios.get(this.apiUrl + "test/monthly/" + this.associateId + "/" + this.initialDate + "/" + this.finalDate)
.then(response => {
this.monthlyData = response.data;
console.log(response.status);
})
.catch(error => {
console.error(error);
})
},}
onSubmit() {
let consultantApi = {
name: this.name,
initialDate: this.initialDate,
finalDate: this.finalDate,
}
this.$emit('consultantApi-submitted', consultantApi)
this.name = ''
this.initialDate = ''
this.finalDate = ''
}
},
mounted: function() {
this.apiUrl = process.env.VUE_APP_BACKEND_API;
this.environment = process.env.NODE_ENV;
}
Initial Form
D3 plots after submitting the completed form
Creation of new d3 plots whenever I press any key in the form
Yes, this is because updating any model will re-render the entire component.
To get around it, I find the simplest way is to put the chart into another component so that the re-render is then guarded.
Example:
var app = Vue.createApp({
data() {
return {
abc: 'ABC',
list: [1, 2, 3]
};
}
});
app.component("my-chart", {
template: `<div >{{Math.random()}}</div>`
});
app.mount("#app");
<script src="https://unpkg.com/vue#3.0.6/dist/vue.global.prod.js"></script>
<div id="app">
<input v-model="abc" />
<div v-if="list.length">
{{Math.random()}}
</div>
<my-chart></my-chart>
</div>
I think your bug is in the parent component. I would try to check how often does it emmit the consultantApi. It seems like your form keeps submitting on input change event and not on form submit.

wrong value for parameter wsServers

i'm using freeswitch 1.6 and following cookbok to implement webrtc. for this i download sip.js#0.7.0 too. and have created call.html, call.js and answer.html, answer.js pages. my call.html including js is
<html>
<body>
<button id="startCall">Start Call</button>
<button id="endCall">End Call</button>
<br/>
<video id="remoteVideo"></video>
<br/>
<video id="localVideo" muted="muted" width="128px" height="96px"></video>
<!--<script src="js/sip-0.7.0.min.js"></script>-->
<!--<script src="call.js"></script>-->
</body>
<HEAD>
<script src="js/sip-0.7.0.min.js"></script>
<script>
var session;
console.log('hiiiiiiiiiiii')
var endButton = document.getElementById('endCall');
endButton.addEventListener("click", function () {
session.bye();
alert("Call Ended");
}, false);
console.log('hiiiii2')
var userAgent = new SIP.UA({
uri: 'sip:anonymous#gmaruzz.org',
wsServers: ["ws://call.sia.co.in:5066"],
authorizationUser: 'anonymous',
password: 'welcome'
});
console.log('hiiii3')
var startButton = document.getElementById('startCall');
startButton.addEventListener("click", function () {
session =userAgent.invite('sip:1010#139.59.17.63', options);
alert("Call Started");
}, false);
console.log('hiiii4')
var options = {
media: {
constraints: {
audio: true,
video: true
},
render: {
remote:document.getElementById('remoteVideo'),
local: document.getElementById('localVideo')
}
}
};
</script>
</HEAD>
</html>
please correct me where i'm going wrong. Thanks in advance.
you must put the wsServers in transportOptions like :
var userAgent = new SIP.UA({
uri: 'sip:anonymous#gmaruzz.org'
transportOptions: {
wsServers: "ws://call.sia.co.in:5066"
},
authorizationUser: 'anonymous',
password: 'welcome'

Can't get the autocomplete search form to work

I'm implementing a search form that displays suggestions as you start typing but can't get it to work..the problem is that when you start typing it doesn't shows any suggestion. Can you help me to get the code right? Many thanks!
This is the code:
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.2/jquery-ui.min.js"></script>
<div><input id="autocomplete" type="text"></div>
<script>
$("input#autocomplete").autocomplete({
source: [
{ id : "Google", value : "Google"},
{ id : "Yahoo", value : "Yahoo"},
],
minLength: 1,
open: function(event, ui) {
$("ul.ui-autocomplete").unbind("click");
var data = $(this).data("autocomplete");
console.log(data);
for(var i=0; i<=data.options.source.length-1;i++)
{
var s = data.options.source[i];
$("li.ui-menu-item a:contains(" + s.value + ")").attr("href", "/" + s.id);
}
}
});
/*
$("input#autocomplete").bind("autocompleteselect", function(event, ui) {
//alert(ui.item.id + ' - ' + ui.item.value);
//document.location.href = ui.item.id + '/' + ui.item.value;
//event.preventDefault;
} );
*/
</script>
Here Is the code:
<div id="search">
<input list="results" id="project" onkeydown="if (event.keyCode == 13) { checkInput(this.value); return false; }" />
</div>
The avaible results...
<datalist id="results">
<option>Demo</option>
<option>Example</option>
<option>pizza</option>
</datalist>
Finally the javascript
function checkInput(searchQuery)
{
if(searchQuery=="Home")
{
window.location = "Home.html";
}
else if(searchQuery == "Contact")
{
window.location = "Contact.html";
}
else if(searchQuery == "Sitemap")
{
window.location = "Sitemap.html";
}
else
{
window.location = "noresult.html";
}
}
So that way when ever someone goes to search they have a limited amount of options in the pre-populated list and which ever one they select leads them to your target page! I can't take all the credit, but I hope that helps!

how to handle multipart/form-data in node.js

I am uploading image file from client side using multipart form data. I want to receieve and write it as a file in the server side using node.js.
<html>
<body>
<form action="url" method="post" enctype="multipart/form-data">
<input type="text" name="imageName">
<input type="file" name="sam">
</form>
</body>
</html>
This is my client side code. How to handle this file in server side.
It is repeated question below link.
Uploading images using Node.js, Express, and Mongoose
Here is example:
// Expose modules in ./support for demo purposes
require.paths.unshift(__dirname + '/../../support');
/**
* Module dependencies.
*/
var express = require('../../lib/express')
, form = require('connect-form');
var app = express.createServer(
// connect-form (http://github.com/visionmedia/connect-form)
// middleware uses the formidable middleware to parse urlencoded
// and multipart form data
form({ keepExtensions: true })
);
app.get('/', function(req, res){
res.send('<form method="post" enctype="multipart/form-data">'
+ '<p>Image: <input type="file" name="image" /></p>'
+ '<p><input type="submit" value="Upload" /></p>'
+ '</form>');
});
app.post('/', function(req, res, next){
// connect-form adds the req.form object
// we can (optionally) define onComplete, passing
// the exception (if any) fields parsed, and files parsed
req.form.complete(function(err, fields, files){
if (err) {
next(err);
} else {
console.log('\nuploaded %s to %s'
, files.image.filename
, files.image.path);
res.redirect('back');
}
});
// We can add listeners for several form
// events such as "progress"
req.form.on('progress', function(bytesReceived, bytesExpected){
var percent = (bytesReceived / bytesExpected * 100) | 0;
process.stdout.write('Uploading: %' + percent + '\r');
});
});
app.listen(3000);
console.log('Express app started on port 3000');
If your question is not solve then please visit this link . This is a nice article about file uploading.
You can use request module for sending a multipart request. Here is the sample code:
var jsonUpload = { };
var formData = {
'file': fs.createReadStream(fileName),
'jsonUpload': JSON.stringify(jsonUpload)
};
var uploadOptions = {
"url": "https://upload/url",
"method": "POST",
"headers": {
"Authorization": "Bearer " + accessToken
},
"formData": formData
}
var req = request(uploadOptions, function(err, resp, body) {
if (err) {
console.log('Error ', err);
} else {
console.log('upload successful', body)
}
});