Updating the Div with added text, comment feature - javascript

I am developing an MVC application with razor syntax.
I am developing the partial class for commenting feature.
I have code in which disply output of comments in following pattern.
John Smith 15-Aug-2012
-------------------------------
Called Customer today, hold me to call later.
Will Parkar 15-Aug-2012
-------------------------------
Keep track with him.
*Add New Comment in below text box.*
___________________________________________
|Called Again... |
| |
|___________________________________________|
Add Comment Clear
Now, whenever user put the comment in text box , that text should added in above list...
out put should be
John Smith 15-Aug-2012
-------------------------------
Called Customer today, hold me to call later.
Will Parkar 15-Aug-2012
-------------------------------
Keep track with him.
John Smith 16-Aug-2012
-------------------------------
Called Again... <---------------------New Comment get added here.
*Add New Comment in below text box.*
___________________________________________
| |
| |
|___________________________________________|
Add Comment Clear
I have below code...
#model IEnumerable<CRMEntities.Comment>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<!DOCTYPE html>
<script src="../../Scripts/jquery.js" type="text/javascript"></script>
<script type="text/javascript">
function clearText()
{
document.getElementById('Comment').value = "";
}
</script>
<script src="../../Scripts/jquery.js" type="text/javascript"></script>
<script type="text/javascript">
$('#AddCommentButton').click(function () {
$.ajax({
type:'post',
url: '/Comment/SaveComments', //url to your action method
dataType: 'json',
data: { 'comments': $('#Comment').val() },
success: function(data)
{
$('#ParentBlock').appendChild("<div>" + data.msg + "</div>");
}
});
});
</script>
<script src="../../Scripts/jquery.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$(".ShowComments").click(function () {
$(".ParentBlock").slideToggle("slow");
$("CommentP").append(document.getElementById('Comment').value);
});
});
</script>
<script src="../../Scripts/jquery.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$(".ShowComments2").click(function () {
$(".1").append("<strong>Hello</strong>");
});
});
</script>
<style type="text/css">
div.ParentBlock
{
position:relative;
display:none;
}
#ClassPara
{
position:relative;
background-color:#ECF5FC;
cursor:pointer;
border:2px;
width: 115px;
border-style:solid;
border-width:thin;
border-color: #DCEDF8;
}
<style type="text/css">
#OwnerName
{
background-color : #F0F6FF;
font-style:normal;
font-family:Calibri;
}
#CommentTextBlock
{
background-color : #F9F9FF;
}
#EmpName
{
font-style:normal;
font-size:medium;
}
#Clear
{
text-decoration:underline;
cursor:pointer;
color:Blue;
}
#AddComment
{
text-decoration:underline;
cursor:pointer;
color:Blue;
}
</style>
</head>
<body>
#{
<p id="ClassPara" class="ShowComments" >Show Comments</p>
<div class="ParentBlock">
#foreach (var item in Model)
{
<div id="OwnerName">
<span class="EmpName"> #Html.ActionLink(item.Owner.FullName, "Details", "EMployee", new { id = item.OwnerId }, new { #style = "color:#1A6690;" })</span>
#Html.DisplayFor(ModelItem => item.CommentDateTime)
</div>
#* <div id="CommentTextBlock">
#Html.DisplayFor(ModelItem => item.CommentText)
</div>*#
<p class="CommentP">
#Html.DisplayFor(ModelItem => item.CommentText)
</p>
<br />
}
</div>
#Html.TextArea("Comment", "", 5, 80, "asdsd")
<input type="button" value="Add Comment" id="AddCommentButton"/>
<input type="button" value="Clear" onclick="clearText()"/>
<br />
#* <label id="AddComment">Add Comment</label>
<label id="Clear" onclick="clearText()">Clear</label>*#
}
</body>
</html>
How to do this ?

On click of ADD Comment button post that comment to your action to save it to Database or wherever you want to save, and then return that comment in call back function of ajax to show it on page.
$('#addCommentButtonID').click( function() {
$.ajax({
type:'post',
url: 'SaveComments' //url to your action method
dataType: 'json',
data: {'comments':$('#textboxId').val()},
success: function(data)
{
$('#yourMainDiv').appendChild("<div>"+data.msg+"</div>");
}
});
});
Second way :
$('#addCommentButtonID').click( function() {
$.post('SaveComments',comments:$('#commentTextbox').val(),
function (data) {
$('#yourMainDiv').appendChild("<div>"+data.msg+"</div>");
},'json');
});
Your Action
public JsonResult SaveComments(string comments)
{
// save it wherever you want
// after saving success return this string as jsonresult
return Json(new { sc = true, msg = comment });
}

Related

Show Captured WebCam file name to Next Page in Python (Flask)

I am trying to capture an image from WebCam and show its file name on the next page when the user clicks the Upload button.
Currently, the snap function is taking the image and working fine. But When the users click on the Upload button, nothing happened.
Expected Output: Click on the Upload button will open a New Page (Test2) and show the file name.
My Code
app.py
#app.route('/Test', methods=['GET','POST'])
def Test():
if request.method == 'POST':
return render_template('Test2.html',data=request.form['file'])
return render_template('Test.html')
if __name__ == '__main__':
app.run(debug=True)
Test.html
<!doctype html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>WebcamJS Test Page</title>
<style type="text/css">
body { font-family: Helvetica, sans-serif; }
h2, h3 { margin-top:0; }
form { margin-top: 15px; }
form > input { margin-right: 15px; }
#results { float:right; margin:20px; padding:20px; border:1px solid; background:#ccc; }
</style>
</head>
<body>
<div id="results">Your captured image will appear here...</div>
<h1>WebcamJS Test Page</h1>
<h3>Demonstrates simple 320x240 capture & display</h3>
<div id="my_camera"></div>
<!-- First, include the Webcam.js JavaScript Library -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/webcamjs/1.0.26/webcam.min.js" integrity="sha512-dQIiHSl2hr3NWKKLycPndtpbh5iaHLo6MwrXm7F0FM5e+kL2U16oE9uIwPHUl6fQBeCthiEuV/rzP3MiAB8Vfw==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<form method="POST" enctype="multipart/form-data" id="myForm">
<table>
<tr>
<td>Name/EmailId</td>
<td>: <input type="text" name="userID"></td>
</tr>
<tr>
<td><input type="button" value="Upload" onclick="upload()"></td>
</tr>
</table>
</form>
<div id="my_camera"></div>
<input type="button" onclick="snap()" value="Snap">
<div id="results"></div>
</body>
<script>
function ShowCam() {
Webcam.set({
width: 320,
height: 240,
image_format: 'jpeg',
jpeg_quality: 100
});
Webcam.attach('#my_camera');
}
window.onload= ShowCam;
function snap() {
Webcam.snap( function(data_uri) {
// display results in page
document.getElementById('results').innerHTML =
'<img id="image" src="'+data_uri+'"/>';
} );
}
function upload() {
console.log("Uploading...")
var image = document.getElementById('image').src;
var form = document.getElementById('myForm');
var formData = new FormData(form);
formData.append("file", image);
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", "/Test");
// check when state changes,
xmlhttp.onreadystatechange = function() {
}
xmlhttp.send(formData);
console.log(formData);
console.log(formData.get('file'));
console.log(formData.get('userID'));
}
</script>
Test2.html
<!DOCTYPE html>
<html>
<body>
<h1>My First Heading</h1>
<p>My first paragraph.</p>
<p> {{data}}
</body>
</html>

getting data from a form using ajax?

I am trying to get data from an html form using jquery. I have tried the following but for some reason when I tried to log the data in the console, I keep getting null. What could I be doing wrong ? I want to send the data captured from my form in json format to my servlet. Thanks
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<style>
.vertical-menu {
width: 200px;
}
.vertical-menu a {
background-color: #eee;
color: black;
display: block;
padding: 12px;
text-decoration: none;
}
.vertical-menu a:hover {
background-color: #ccc;
}
.vertical-menu a.active {
background-color: #4CAF50;
color: white;
}
</style>
</head>
<body>
<form id="register">
<div class="vertical-menu">
</div>
API Name:<br>
<input type="text" id = "apiname" name="apiname">
API ENDPOINT:<br>
<input type="text" id ="apiendpoint" name="apiendpoint">
<br>
API VERSION:<br>
<input type="text" id="apiversion" name="apiversion">
ACCESSIBLE:<br>
<input type="checkbox" name="source" value="internet"> Internet<br>
<input type="checkbox" name="source" value="vpn"> VPN<br>
<br>
<input type="submit" id="check" name="check" value="Insert">
</form>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(document).on("click", "#check", function() { // When HTML DOM "click" event is invoked on element with ID "somebutton", execute the following function...
event.preventDefault();
var d = $('register').serialize();
console.log("d",d);
$.ajax({
type: "POST",
url: "HomeServlet",
dataType: "text",
contentType: "application/json",
data:d,
success: function(data){
console.log(data);
},
error:function(){
console.log("error");
},
});
});
</script>
</body>
</html>
You forgot to give proper selector:
register is the ID of the form so;
$(document).on("click", "#check", function() { // When HTML DOM "click" event is invoked on element with ID "somebutton", execute the following function...
event.preventDefault();
var d = $('#register').serialize(); // You had missed # here.
console.log("d",d);
$.ajax({
type: "POST",
url: "HomeServlet",
dataType: "text",
contentType: "application/json",
data:d,
success: function(data){
console.log(data);
},
error:function(){
console.log("error");
},
});
});
// Handle submit action on the forms.
$('#register').on('submit', function(e) {
// Prevent the browser to submit the form (we want to do it manually)
e.preventDefault();
var form = $(this);
var formdata = (window.FormData) ? new FormData(form[0]) : null;
var data = (formdata !== null) ? formdata : form.serialize();
console.log(data);
// POST request to server
$.ajax({
url : "URL/TO/SERVER",
type : "POST",
data : data,
// other fields you need
});
});
I think that this is a proper way to achieve what you need. Don't forget to add the event argument to your callback function.

Multiple Submit Actions

I have a script given to me by another developer to send push messages to my Apps.
I want to be able to send them from one page to both App types but cannot figure how.
Problem is I do not have any control over the pages on the server they are sent to.
If you look at the code the only differences in the two critical pieces of code are the Form action to send them to each Server page and the name of the App Id's...the other info remains the same.
I also found a piece of javascript to submit to two places from one button but could not get it working with both...
I know from reading that I probably need an array...Could someone please show me some code with these in an array with a submit button to send them to their respective pages.
Thanks in advance...
EDITED
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script src="jquery-1.11.3.min.js"></script>
<script type="text/javascript" src="../../ScriptLibrary/jquery-latest.pack.js"></script>
</head>
<body>
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<form name="push" method="post" >
<input name="pushmessage" type="hidden" value="HAIR EXTENSIONS ">
<p align="center">Notification Message:<br />
<textarea style="width: 280px; height: 150px; margin-bottom: 30px; font-family: Verdana, Geneva, sans-serif; border-color: #000; border- width: 1px; resize: none;" name="pushmessage" id="push-message"> </textarea><br />
<input type='button' class="inputbtn" name='Submit' value='Push' onclick='sendFormData()' />
<form/>
<script type="text/javascript">
function sendFormData() {
var formURL1 = 'http://apple/iPhone-message';
var formURL2 = 'http://google/android-message';
var postData1 = {'publishersid':'appdeveloper','username':'myself','pass':'mypassword','appid':' CommunityApp-i','topics':'test'};
var postData2 = {'publishersid':'appdeveloper','username':'myself','pass':'mypassword','ap pid':'CommunityApp','topics':'test'};
submitForm(formURL1, postData1);
submitForm(formURL2, postData2);
};
function submitForm(formURL, postData) {
$('#push-message').append('sending data to url : '+formURL+'\n');
$.ajax(
{
url: formURL,
type: "POST",
data: postData,
success: function (data, textStatus, jqXHR) {
$('#push-message').text('success');
},
error: function (jqXHR, textStatus, errorThrown) {
$('#push-message').append('oops:error occured'+errorThrown+'\n');
}
});
}
</script>
</body>
</html>
You should not use native submit button (that triggers a page change) but use a ajax submit method using XHR object.
You can take a look to this jquery plugin: http://jquery.malsup.com/form/
you dont need to html form tag, you can do that with this piece of this code:
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<form name="push" method="post" >
<input name="pushmessage" type="hidden" value="HAIR EXTENSIONS ">
<p align="center">Notification Message:<br />
<textarea style="width: 280px; height: 150px; margin-bottom: 30px; font-family: Verdana, Geneva, sans-serif; border-color: #000; border- width: 1px; resize: none;" name="pushmessage" id="push-message"> </textarea><br />
<input type='button' class="inputbtn" name='Submit' value='Push' onclick='sendFormData()' />
<script type="text/javascript">
function sendFormData() {
var formURL1 = 'http://apple/iPhone-message';
var formURL2 = 'http://google/android-message';
var postData1 = {'publishersid':'appdeveloper','username':'myself','pass':'mypassword','appid':' CommunityApp-i','topics':'test'};
var postData2 = {'publishersid':'appdeveloper','username':'myself','pass':'mypassword','ap pid':'CommunityApp','topics':'test'};
submitForm(formURL1, postData1);
submitForm(formURL2, postData2);
};
function submitForm(formURL, postData) {
$('#push-message').append('sending data to url : '+formURL+'\n');
$.ajax(
{
url: formURL,
type: "POST",
data: postData,
success: function (data, textStatus, jqXHR) {
$('#push-message').text('success');
},
error: function (jqXHR, textStatus, errorThrown) {
$('#push-message').append('oops:error occured'+errorThrown+'\n');
}
});
}
</script>

the loading gif keeps appearing without any output

I'm making instagram API that should retrieve user accounts that contain a given keyword, the code worked well at first, but when i inserted the part of the loading gif it didn't work, the gif just kept appearing without any result
here is my code
<!DOCTYPE html>
<html>
<head charset="utf-8">
<style type="text/css">
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script>
$(document).on("mouseover", "#instaUser img", function() {
$(this).css('opacity', '0.5');
});
$(document).on("mouseout", "#instaUser img", function() {
$(this).css('opacity', '1');
});
var keyword;
var arr=new Array();
var time;
function getUsers() {
keyword=document.getElementById("search").value;
document.getElementById("name").innerHTML = keyword;
//retrieve user accs
$.ajax({
type: "POST",
url: "get_info.php?keyword='+keyword+"&"count=20",
beforeSend: function()
{
$('#images').html("<img src='ajax-loader.gif'/>");
},
success: function(data)
{
$.getJSON('get_info.php?keyword='+keyword,function(data){
$("#instaUser").empty();
$( "#images" ).fadeOut( "fast" );
$("#instaUser").empty();
// this is where we can loop through the results in the json object
for (var i = 0; i <20; i++){
if(i%4==0)
$("#instaUser").append("<br>");
$("#instaUser").append("<figure style='display:inline-block'><img id='"+i+"' src='"+data.data[i].profile_picture+"' alt='pic number "+i+"' height='"+200+"' width='"+200+"'> <figcaption>#"+data.data[i].username+"</figcaption></figure>");
// $("#instaUser").append("");
}//end for
$( "#images" ).fadeIn( "slow" );
});//end getJSON
}
});
}
</script>
</head>
<body>
<header>
Instagram User Search
<span style=" margin-left: 400px; margin-right: auto;font-family:Times New Roman, Times, serif;">Search
<input id="search" type="text" onchange="getUsers()" >
</div>
</header>
<article>
<section>
<h1 id="name" style="text-align: center; font-family:cashC; color:#95B9C7; text-shadow: 1px 2px #000000;">
</h1>
<div id="images" style="text-align: center ;">
<div id="instaUser" style="font-family:Times New Roman, Times, serif">
</div>
</div>
</section>
</article>
</body>
</html>
it's like the gif is going through an infinite loop but i don't know where is the problem exactly in my code

How to make my form post to its self

I have a form in which users can submit issues, what I want to happen is when users hit the add button, i want what they add to be posted in the box below. So say the add something, x out the window and come back to add something else later what they added previously will still be there.
here is my fiddle
http://jsfiddle.net/grahamwalsh/rCB9V/
IssueList(html)
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Issue List</title>
<script src="Scripts/jquery-2.1.1.js"></script>
<script src="Scripts/knockout-3.1.0.js"></script>
<script src="Issuelist.js"></script>
<link type="text/css" rel="stylesheet" href="Issuelistcss.css" />
</head>
<body>
<div class='issuelist'>
<form data-bind="submit:addIssue">
Add Issue: <input type="text" data-bind='value:issueToAdd, valueUpdate: "afterkeydown"' />
<button type="submit" data-bind="enable: issueToAdd().length > 0">Add</button>
</form>
<p>Your Issues:</p>
<select multiple="multiple" data-bind="options:allIssues, selectedOptions:selectedIssues"> </select>
<div>
<button data-bind="click: removeSelected, enable: selectedIssues().length > 0">Remove</button>
<button data-bind="click: sortIssues, enable: allIssues().length > 1">Sort</button>
</div>
</div>
</body>
</html>
IssueList (js)
$(document).ready(function(){
var Issuelist = function () {
this.issueToAdd = ko.observable("");
this.allIssues = ko.observableArray(["test"]);
this.selectedIssues = ko.observableArray(["test"]);
this.addIssue = function () {
if ((this.issueToAdd() != "") && (this.allIssues.indexOf(this.issueToAdd()) < 0))
this.allIssues.push(this.issueToAdd());
this.issueToAdd("");
};
this.removeSelected = function () {
this.allIssues.removeAll(this.selectedIssues());
this.selectedIssues([]);
};
this.sortIssues = function () {
this.allIssues.sort();
};
};
ko.applyBindings(new Issuelist());
});
IssueListcss
body { font-family: arial; font-size: 14px; }
.issuelist { padding: 1em; background-color: #87CEEB; border: 1px solid #CCC; max-width: 655px; }
.issuelist input { font-family: Arial; }
.issuelist b { font-weight: bold; }
.issuelist p { margin-top: 0.9em; margin-bottom: 0.9em; }
.issuelist select[multiple] { width: 100%; height: 8em; }
.issuelist h2 { margin-top: 0.4em; }
You could have the form 'post' to its self then make an ajax request for their new issue and put it inside a div. I would also hold off on so much on the javascript or have support for those without it:
getissues.php
getissues.php
<?php
/*
connect to your database code
*/
$query = "select * from issues";
$result = mysql_query($query, $connect);
while($row = mysql_fetch_array($result))
{
echo $row['issues'];
echo '<hr>';
}
?>
process.php
process.php:
<?php
/*
connect to your database
*/
$issue = strip_tags$_POST['issue'];
$query = "insert into issues (issue) values ('$issue')";
$result = mysql_query($query, $connect);
?>
main form page:
<!DOCTYPE HTML>
<html>
<head>
<title>issue page</title>
<script src="Scripts/jquery-2.1.1.js"></script>
<script src="Scripts/knockout-3.1.0.js"></script>
<script src="Issuelist.js"></script>
<link type="text/css" rel="stylesheet" href="Issuelistcss.css" />
<script type="text/javascript">
function check()
{
var request = $.ajax({
url: "getissues.php",
type: "POST",
dataType: "html"
});
request.done(function(msg) {
$("#issues").html(msg);
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
}
function validate()
{
var issue = $("#issue");
var errcount = 0;
if (issue == "")
{
errcount++;
alert("enter something");
}
if (errcount == 0)
{
/*
make request to php script to put issue into database
*/
$.post("process.php",
{
issue:issue
},
function(data,status){
window.alert("Request done!");
check();
});
}
}
</script>
</head>
<body>
<form action="issuelist.html" method="post">
Add Issue: <input type="text" name="issue"/>
Add Issue: <input type="text" name="issue" id="issue"/>
<button onclick="validate()">submit</button>
</form>
<div id="issues" class="issues">
<!--your ajax fetched issues will appear here-->
</div>
</body>
</html>
hope this helps!

Categories