Ajax `appendTo` replaces the existing element - javascript

I am trying to submit some form data to Servlet using JQuery and retrieve the Servlet response from the same JQuery. Please have a look at the below code.
<%--
Document : index
Created on : Feb 23, 2015, 8:18:52 PM
Author : Yohan
--%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
var form = $('#customItemForm');
function formSubmit(){
$.ajax({
url:'SampleServlet',
data: $("#customItemForm").serialize(),
success: function (data) {
$("#results").text(data);
var $textbox = $('<input type=text>').appendTo($('<div>')).appendTo($('#results'));
$textbox.attr("id",data);
//alert($textbox.attr("id"));
}
});
}
</script>
</head>
<body>
<form method="get" action="SampleServlet" id="customItemForm" onsubmit="formSubmit(); return false;">
Name <input type="text" name="name">
<button>Submit</button>
</form>
<br>
<div id="results"></div>
</body>
</html>
In the above code in JQuery section, I am trying to read the value I got from servlet, create a Text Input in a DIV. My expectation was if I click the "Submit" button twice, then 2 text boxes; if I click the submit button thrice, then 3 text boxes and so on. Unfortunatly it is not happening here. Only one text box appear, all the time, replacing the previous one.
How can I fix this?

$.ajax({
url:'SampleServlet',
data: $("#customItemForm").serialize(),
success: function (data) {
$("#results").text(data); //replace with $("#results").append(data)
var $textbox = $('<input type=text>').appendTo($('<div>')).appendTo($('#results'));
$textbox.attr("id",data);
//alert($textbox.attr("id"));
}
});
}
you need to make the change above as .text() replaces the existing data in the div (so the previous run you did gets over-written)

Related

JavaScript - result disappears immediately [duplicate]

This question already has answers here:
JavaScript code to stop form submission
(14 answers)
Closed 4 years ago.
I am a beginner to JavaScript. I am buliding a BMI calculator. It gives the output for a few milliseconds and then the result disappears.
<!DOCTYPE html>
<html>
<head>
<title>BMI Calculator</title>
</head>
<body>
<form>
Weight:-<input type="text" id="wtxt"><br>
Height:-<input type="text" id="htxt"><br>
BMI:-<input type="text" id="bmitxt"><br>
<input type="reset" value="clear"><br>
<button onclick="calcbmi()">Calc BMI</button>
</form>
<script type="text/javascript">
function calcbmi(){
var w=parseInt(document.getElementById('wtxt').value);
var h=parseInt(document.getElementById('htxt').value);
var z=w/(h*h);
document.getElementById('bmitxt').value=z;
}
</script>
</body>
</html>
To separate behavior from the view, you can do it like this:
The button:
<button>Calc BMI</button>
The script:
<script type="text/javascript">
document.querySelector("button").addEventListener("click", function(event) {
calcbmi();
event.preventDefault();
}, false);
function calcbmi() {
var w = parseInt(document.getElementById('wtxt').value);
var h = parseInt(document.getElementById('htxt').value);
var z = w / (h * h);
document.getElementById('bmitxt').value = z;
}
</script>
Source
Looks like the comments are answering your question. Shortest path is to change the button to a different type so it doesn't submit the form, thus causing the page to load again. Form makes it simple for inputs, but isn't strictly necessary.
Calc BMI
More info here:
How to prevent buttons from submitting forms
By default, form makes a GET request on submit. Source
You're submitting the form each time you click submit and the browser is trying to make a request to nothing since there is no action attribute specified. I've copied a working example of your code below. As noted in the comments, remove the form. Your code will work then.
<!DOCTYPE html>
<html>
<head>
<title>BMI Calculator</title>
</head>
<body>
Weight:-<input type="text" id="wtxt"><br>
Height:-<input type="text" id="htxt"><br>
BMI:-<input type="text" id="bmitxt"><br>
<input type="reset" value="clear"><br>
<button onclick="calcbmi()">Calc BMI</button>
<script type="text/javascript">
function calcbmi(){
var w=parseInt(document.getElementById('wtxt').value);
var h=parseInt(document.getElementById('htxt').value);
var z=w/(h*h);
document.getElementById('bmitxt').value=z;
}
</script>
</body>
</html>
You can see a fiddle here

Submitting the closest form without a submit button?

I have page with many forms consisting of only a textarea and a hidden field with an id
I am trying to use jQuery to submit the form each time the user enters some text and hits command+enter on the keyboard.
For that I am using
$('textarea').keydown(function(e) {
if(e.keyCode == 13 && e.metaKey) {
That part works fine, but then when I try to submit my form the script stops execution. I am sure I am doing some mess with the closest('form') submit.
Here is my full code
$('textarea').keydown(function(e) {
if(e.keyCode == 13 && e.metaKey) {
$('textarea').closest('form').submit(function() {
$.post("someurl.php", $(this).serialize(), function(data) {
alert(data);
});
});
};
});
When I debug it never enters inside the $('textarea').closest('form').submit(function() {
Any idea how can I pass the content of the form for which command+enter was entered to my processing URL?
Any tips will be appreciated,
Thanks
UPDATE
HTML code for the forms
<form action="#">
<div class="col-xs-1">
<textarea class="form-control" rows="5" placeholder="Enter your answer"></textarea>
<input type="hidden" name="idval" value="xxxx">
</div>
</form>
EDIT 2
While debugging the code I see that the parameters are correctly passed but at one point jquery loses the values.
What is even stranger is that the fiddle posted below works fine in fiddle, but when I download the code and test it on my localhost it doesn't.
Here is the code
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="robots" content="noindex, nofollow">
<meta name="googlebot" content="noindex, nofollow">
<script
src="https://code.jquery.com/jquery-2.2.4.js"
integrity="sha256-iT6Q9iMJYuQiMWNd9lDyBUStIq/8PuOW33aOqmvFpqI="
crossorigin="anonymous"></script>
<style type="text/css">
</style>
<title> by b</title>
<script type='text/javascript'>//<![CDATA[
window.onload=function(){
$('textarea').keydown(function(e) {
if(e.keyCode == 13 && e.metaKey) {
// e.preventDefault();
$.post($(this).closest("form").attr("action"), { html: $(this).closest("form").serialize()}, function(data) {
alert(data);
});
}
});
}//]]>
</script>
</head>
<body>
<form action="#">
<textarea name="area1"></textarea>
</form>
<form action="#">
<textarea name="area2"></textarea>
</form>
</body>
</html>
any clues?
You shouldn't define an event handler inside another event handler. You should just post the current form.
$('textarea').keydown(function(e) {
if(e.keyCode == 13 && e.metaKey) {
$.post($(this).closest("form").attr("action"), $(this).closest("form").serialize(), function(data) {
alert(data);
});
}
});

open a simple pop up window with my string contents

I used jquery getJSON method to get the two strings from java servlet. one string contains the type of data like simple string, XML and HTML and another string contains data. I need to open a popup window with different size based on contents.
Below the code used to get the strings.
<%# 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>AJAX calls using Jquery in Servlet</title>
<script src="http://code.jquery.com/jquery-latest.js"> </script>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script src="https://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<script>
$(document).ready(function() {
$('#submit').click(function(event) {
var applid=$('#applicationid').val();
var applname=$('#appname').val();
$.getJSON('ActionServlet',
{
appid:applid,
appname:applname
},function(data) {
var errortype = data.errortype;
var errorMsg = data.errorMsg;
});
});
});
</script>
</head>
<body>
<form id="form1">
<h1>AJAX Demo using Jquery in JSP and Servlet</h1>
Enter your Name:
<input type="text" id="applicationid"/>
<input type="text" id="appname"/>
<input type="button" id="submit" value="Ajax Submit"/>
<br/>
<div id="hello" title="Hello World!"></div>
</form>
</body>
</html>
You can user fancybox. It gives options for opening the passed html string check here
To open a new window you can use the window.open() function.
To display the XML as raw text, you need to escape the special characters.
Javascript does not have builtin function for it (like htmlentities() in php).
You can try the following code:
function htmlentities(str)
{
return String(str).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
}

Inserting Row in Table inside Form tag autosubmitting in firefox/chrome

I have a form that will have dynamic elements inserted with javascript and am experiencing some strange behavior. When I click the button to add another element to the table in the form, it adds the element but seems to to a form post immediately (without intending to submit the form yet)
I have created a simplified example of the page that has the same behavior. the first table element is created on page load and subsequent elements are added when clicking on the button. this form works successfully in IE. does anyone have an idea of how to prevent this behavior?
here is the code sample.
<!DOCTYPE html>
<html>
<head>
<title>Test Creating Form</title>
<meta http-equiv="Content-type" content="text/html;charset=UTF-8">
<style type="text/css">
td{font-family:verdana;}
</style>
<script type="text/javascript">
var counter = 0;
function makeTitle(title){
if(counter){
title += " " + counter;
}
counter++;
var tbl = document.getElementById('tbl');
var tr = tbl.insertRow(-1)
var td1 = tr.insertCell(-1);
td1.innerHTML = title;
}
function load1(){
makeTitle('Primary Specimen');
}
</script>
</head>
<body onload="load1();">
<form action="formtest.htm" method="post" name="testForm" id="testForm">
<table id="tbl" border="1"></table>
<button onclick="makeTitle('Alternate Specimen')" id="clone" >Add Another Specimen</button>
</form>
</body>
</html>
Button tags default to type="submit"; add type="button".
Cancel the click event with return false; or add type="button". A <button /> without a type-attribute is per default a submit-button.
<button type="button" onclick="makeTitle('Alternate Specimen')" id="clone" >Add Another Specimen</button>

Adding data dynamically to a HTML page

In a htmlpage using jQuery or JavaScript how can the following be achieved?
User types in a question in a textarea and press on enter button, then the same question should be displayed dynamically in the page below the textarea and the user can enter as many questions.
And when the user is done the page is submitted through a submit button.
Can you give a small hint of how this can be done?
Try this to get started :
<!DOCTYPE html>
<html>
<head>
<title>Example</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#textareabutton').click(function(){
var q = $('#textarea').val(),
$p = $('<p>').html( q );
$('#questions').append( $p );
});
$('#submit').click(function(){
var tab;
tab = $('#questions p').serializeArray();
// now do something with $.ajax to submit the questions
$.post("myphp.php",tab,function(resp){
// what do I do with the server's reply ???
});
});
});
</script>
<style type="text/css">
</style>
</head>
<body>
<textarea id='textarea'></textarea>
<button type='button' id='textareabutton'>Add question</button>
<div id='questions'></div>
<button type='button' id='submit'>Submit questions</button>
</body>
</html>
Use the innerHTML property of a div to add the questions to.

Categories