Passing form data to the JSP without passing to the server - forms

html>
<head>
<title>Landing</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
</head>
<body>
<form name="testForm" action="move.jsp">
<label><h1>Enter the data <h1/></label><br/>
<input type="text" name="DATA"><br/>
<input type="submit">
</form>
<% out.println(DATA) %> <!-- WRONG!! -->
</body>
</html>
Please ignore the action part
I am working on a spring mvc project and I have a problem. What I want is that, when the user clicks submit, we should not leave the page, we should just stay. But the values submitted would be used as a parameter to a function in the same page. Here, let's just say I want to print it, and that is the part that is wrongly entered.
What should I do to accomplish this? Please help

You can use ajax here when your submit button is clicked call this function and then using this call your ajax passed the value from your input to your server and then at your server side perform operation which you needed to do and then the result back to ajax .
Your form :
<form name="testForm" action="move.jsp">
<label><h1>Enter the data <h1/></label><br/>
<input type="text" name="DATA"><br/>
<input type="button" onclick="submit_values()">
<!--^^added this-->
</form>
<div id="result"><!--here data will come back--></div>
Then on click of your button submit_values() function will get called . i.e :
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script>
<script>
function submit_values() {
//get input value
var values = $("input[name='DATA']").val();
console.log(values);
$.ajax({
type: 'POST',
data: {
values: values//passing to server
},
url: "Your_server_url",
success: function(data) {
alert(data);//this will display whatever server will return
$("#result").html(data);//add response back to show
}
});
}
</script>
Then at your server-side do like below :
String data =request.getParameter("values");//get value
String send_back = something(data);//call your function
out.println("DATA BACK"+send_back );//this will go back to ajax

Related

Can't change / get value of input after being opened with FeatherLight?

I've met a weird behavior. I'm trying to get / set the value of an input textbox After FeatherLight lightbox is closed. I get "Undefined" when trying to fetch the value of the textbox (again, after it was opened and closed via Featherlight). You can see my source code here:
https://jsfiddle.net/hgyba4dg/
The only relevant part is the html code. try running the code on JSFiddle and see the input's value (the textbox's value). You'll see that you'll get "undefined" after closing the Featherlightbox. Here is the html:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript">
var storeData = null;
function openFeatherLight()
{
if (!storeData)
{
storeData = $.featherlight($('#MyDiv'), { 'persist' : true , 'beforeOpen' : sayHi , 'beforeClose' : sayBye, 'afterClose' : changeInputValueAfterClose });
}
else
{
storeData.open();
}
}
function sayHi()
{
alert('Value of textbox BEFORE opening FeatherLight LightBox Is: ' + $('#MyTextBox').val());
}
function sayBye()
{
alert('Value of textbox BEFORE CLOSING the FeatherLight LightBox Is: ' + $('#MyTextBox').val());
}
function changeInputValueAfterClose()
{
$('#MyTextBox').val("Bla");
alert('Current Value Of Input TextBox After Change is: ' + $('#MyTextBox').val());
alert('We get "Undefined". Why?');
}
</script>
</head>
<body>
<div id="Shit" style="display: none;">
<div id="MyDiv">
Text
<form id="MyForm">
<input type="text" value="Initial_Value_Set_By_Me_For_Testings" id="MyTextBox">
</form>
</div>
</div>
<input name="Button1" type="button" value="Open FeatherLight" class="AddToMenuButton" onclick="openFeatherLight();">
</body>
</html>
After the first time, the DOM elements remain detached (I open to reinsert it one day...). So $('#MyTextBox') won't work afterwards. Either keep a reference to it, or use storeData.$content.find('#MyTextBox')

Use code captcha in two forms

I have two forms on a page containing Google captcha code, but only one code works. Does anyone know if you can use the same code with the same key on two forms on the same page?,
Thks,
Yes, you can. But you have to explicitly render the widget as mentioned on the developer guide
you should use something like this on your front end(taken from the developer guide):
<html>
<head>
<title>reCAPTCHA demo: Explicit render for multiple widgets</title>
<script type="text/javascript">
var verifyCallback = function(response) {
alert(response);
};
var widgetId1;
var widgetId2;
var onloadCallback = function() {
// Renders the HTML element with id 'example1' as a reCAPTCHA widget.
// The id of the reCAPTCHA widget is assigned to 'widgetId1'.
widgetId1 = grecaptcha.render('example1', {
'sitekey' : 'your_site_key',
'theme' : 'light'
});
widgetId2 = grecaptcha.render(document.getElementById('example2'), {
'sitekey' : 'your_site_key'
});
grecaptcha.render('example3', {
'sitekey' : 'your_site_key',
'callback' : verifyCallback,
'theme' : 'dark'
});
};
</script>
</head>
<body>
<!-- The g-recaptcha-response string displays in an alert message upon submit. -->
<form action="javascript:alert(grecaptcha.getResponse(widgetId1));">
<div id="example1"></div>
<br>
<input type="submit" value="getResponse">
</form>
<br>
<!-- Resets reCAPTCHA widgetId2 upon submit. -->
<form action="javascript:grecaptcha.reset(widgetId2);">
<div id="example2"></div>
<br>
<input type="submit" value="reset">
</form>
<br>
<!-- POSTs back to the page's URL upon submit with a g-recaptcha-response POST parameter. -->
<form action="?" method="POST">
<div id="example3"></div>
<br>
<input type="submit" value="Submit">
</form>
<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit"
async defer>
</script>
</body>
</html>
I just wanted a HTML snipped which I can insert multiple times, each time displaying another captcha. Also, I did not want to take care for specific IDs assigned to the containers, which would be very annoying when multiple formulars still appearing on one page will be designed and rendered independently. Here is my solution.
<div class="g-recaptcha"></div>
<script type="text/javascript"><![CDATA[
function renderCaptchas() {
var captchaNodes = document.getElementsByClassName('g-recaptcha');
for (var i = 0; i < captchaNodes.length; i++) {
var captchaNode = captchaNodes[i];
if (!captchaNode.captchaRendered) {
captchaNode.captchaRendered = true;
grecaptcha.render(captchaNode, {"sitekey": "YOUR_SITE_KEY"});
}
}
}
]]></script>
<script src="https://www.google.com/recaptcha/api.js?onload=renderCaptchas&render=explicit" async="async" defer="defer"></script>

Ajax form submit, validate and return success or fail

Searched and browsed the forum and tried many examples of ajax and form submission but can't get anything close to work for what I am trying to achieve. I must admit I've been going in circles for days with this and need someone with a fresh pair of eyes.
I have 2 pages:
page1.php
page2.php
Using Google jquery/1.9.0/jquery.js and developing this locally.
page1.php is as follows (I've omitted the head script and body/html tags for clarity)
$(document).ready(function() {
$('#theForm').submit(function(){
$.ajax({
type: "POST",
url: "page2.php",
data: 'html',
success: function(html){
if(html == 'success'){
$('#address').fadeOut('slow');
$('#done').fadeIn('slow');
}else if(html == 'fail'){
alert('fail');
}
}
});
return false;
});
});
<div id="address">
<form action="page2.php" method="post" name="theForm">
<input name="checkname" type="text" id="checkname">
<input name="Proceed" type="submit" id="submit" value="Next Page" />
</form>
</div>
<div id="done">
That Worked!
</div>
Page2.php
Has a mysql query that checks the database for the checkname and echoes 'success' or ' fail' depending upon the result. The query runs fine and is not showing any error.
When the form is submitted page2.php loads and just shows 'success' in the browser.
Firebug also shows success under both response and html. There are no errors within firebug.
I basically want page1.php to stay and for the #address div to hide and the #done div to show when success is passed from page2.php
Hope someone can help.
Update
I tried this test page:
ajaxone.php
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#theForm').submit(function(){
$.ajax({
type: "POST",
url: "ajaxtwo.php",
data: 'html',
success: function(html){
if(html == 'success'){
$('#address').fadeOut('slow');
$('#payment').fadeIn('slow');
alert('ok');
}else if(html == 'fail'){
alert('fail');
}
}
});
return false;
});
});
</script>
<style type="text/css">
#payment{
visibility:hidden;
}
</style>
<div id="address">
<form action="ajaxtwo.php" method="post" name="theForm" id="theForm">
<p>
<input name="name" type="text" id="name">
</p>
<p>
<input type="submit" name="submit" value="submit">
</p>
</form></div>
<div id="payment">Name is correct</div>
ajaxtwo.php
print_r($_POST);
if($_POST['name'] == 'rob'){
echo 'success';
}else{
echo 'fail';
}
Using the above firebug shows the following error:
Array ( )
Undefined index: name
fail
However, when I remove the ajax call the submit works and the data is passed.
So, am I right to assume that if you do not specify the form variables within the ajax call nothing is posted to the next page?
Update 2
Sorry I'm answering myself here.
It does appear that you need to specify the form data to send within the ajax call.
I've just added:
$('#theForm').serialize();
within the ajax call and now the form submits without an error.
However, this still goes to ajaxtwo.php and does not show the success or fail on the ajaxone.php page.
So my next stage is to get the success or fail to show on ajaxone.php
You need to add id="theForm" in the form tag itself.
Example:
<form action="page2.php" method="post" id="theForm" name="theForm">
I would say, add a and then make jq read the output and then redirect accordingly, or use php to redict based on $success_fail result.

Jquery mobile form response page does not download content from pageinit until refresh of page

I am new to jquery mobile, and am having problems getting content I have inserted dymically using pageinit to display on the first time of the form response page. It displays on subsequent refreshes of the page. I also don't want the content to cache.
I need to use querystring values like ?blah=1&blah=2 as I use these in my call to an external json file.
How should I be doing this? If I use rel="external", and setting ajax to false, I have problems with issues on android. So using pageinit in the header, how do I make the dynamically loaded content (in the example, the time in seconds) in the 2nd page display first time round?
I have simplified the problem into test pages below.
Expected behaviour. When you click on the submit button of the form you go through to the 2nd page which should display the no of seconds taken from datetime
Actual behaviour. The seconds/time does not display on the 2nd page until the page is refreshed.
Elsewhere, I have come across the suggestion to put the pageinit code into the div itself, however this has caused the content to cache on android (ie the no of seconds remains the same), so I don't want to do this.
Any ideas on how I should approach this would be much appreciated
Sample code
=======
Page 1 - form
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.0.1/jquery.mobile-1.0.1.min.css" />
<script src="http://code.jquery.com/jquery-1.6.4.min.js"></script>
<script src="http://code.jquery.com/mobile/1.0.1/jquery.mobile-1.0.1.min.js"></script>
<script src="/scripts/myinit.js"></script>
</head>
<body>
<div data-role="page" id="page1" data-add-back-btn="true">
<div data-role="content" data-theme="b">
<form action="page_2.htm" method="GET" id="form1" name="form1">
<input type="hidden" name="seconds" value="">
<div class="ui-block-b"><button type="submit" data-theme="a">Submit</button></div>
</form>
</div>
</div>
</body>
</html>
===
Page 2 form response page
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.0.1/jquery.mobile-1.0.1.min.css" />
<script src="http://code.jquery.com/jquery-1.6.4.min.js"></script>
<script src="http://code.jquery.com/mobile/1.0.1/jquery.mobile-1.0.1.min.js"></script>
<script src="/scripts/myinit.js"></script>
</head>
<body>
<div data-role="page" id="page2" data-add-back-btn="true">
<div id="job" data-role="content">
</div>
</div>
</body>
</html>
===
custom javascript file called /scripts/myinit.js (included in both pages above)
$('#page1').live('pageinit', function(event) {
var seconds = new Date().getTime();
$('input[name=seconds]').val(seconds);
});
$('#page2').live('pageinit', function(event) {
var querystring = location.search.replace( '?', '' ).split( '&' );
var queryObj = {};
for ( var i=0; i<querystring.length; i++ ) {
var name = querystring[i].split('=')[0];
var value = querystring[i].split('=')[1];
queryObj[name] = value;
}
var seconds = queryObj["seconds"];
$('#job').append("seconds=" + seconds);
});
try changing pageinit by pageshow. i had the same problem and it worked for me
Link to the external file like this:
HTML --
I'm a Link
JS --
$(document).delegate('#external-link', 'click', function () {
$.mobile.changePage('/path/to/file.html', { reloadPage : true });
return false;
});
Setting the reloadPage option for the changePage() function will allow the external page to be refreshed rather than loading the cached version. Since the external page will be refreshed, the pageinit code for it will run when it's initialized and your code should function properly.
Documentation: http://jquerymobile.com/demos/1.1.0-rc.1/docs/api/methods.html

How could I create a popup form when clicking a button?

I would like to create a popup form which will ask a user if he/she agrees with the terms and condition and has a post and cancel button. How could I create one? Could you give me an example. Thank you.
<html>
<head>
<script type="text/javascript">
<!--
function confirmation() {
var answer = confirm("Leave tizag.com?")
if (answer){
alert("Bye bye!")
window.location = "http://www.google.com/";
}
else{
alert("Thanks for sticking around!")
}
}
//-->
</script>
</head>
<body>
<form>
<input type="button" onclick="confirmation()" value="Leave Tizag.com">
</form>
</body>
</html>
Taken from TizTag...or you could use jQuery Dialog :)