Detecting change in second dropdown (cascading) using HTML & Javascript - javascript

I'm having some trouble capturing a change in the second dropdown of a cascading dropdown. Basically my set up is this: the user first picks an ETF from the first dropdown. Upon picking an ETF, a change function detects the selection, sends it to Python using AJAX and populates the second dropdown based on the holdings within the ETF (cascading). This part works perfect. For the second dropdown, I want the user to select a visual and then that selection would be sent to Python as well and then a graph would be produced. I have not gotten to that point yet, but I'm trying to just flash a message letting me know that it is working, but for some reason the second change function does not work.
Here is the HTML:
<body> id="body" name="body">
<div class="container">
<h1 align="center">Welcome to the Alpaca Pair Trading Application! </h1>
<div class="row">
<div class="col-md-6">
<label>Select ETF</label>
<select name="etfs" data-live-search="true" id="etfs" class="form-control" class="selectpicker" title="Select ETF">
{% for etf in etfs %}
<option value="{{etf}}">{{etf}}</option>
{% endfor %}
</select>
</div>
<div class="col-md-6">
<label>Select Visual</label>
<select name="visuals" data-live-search="true" id="visuals" class="form-control" class="selectpicker" title="Select Visual"> </select>
</div>
</div>
</div>
<br>
{% for message in get_flashed_messages() %}
<p> {{ message }} </p>
{% endfor %}
<br>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.1/js/bootstrap-select.min.js">
</script>
</body>
<script type="text/javascript">
$("#etfs").change(function() {
$.ajax({
type: "POST",
url: "{{ url_for('visuals') }}",
data: {
etf: $("#etfs").val()
},
success: function(data) {
var html = "";
for (var count = 0; count < data.length; count++) {
html += '<option value="' + data[count].id + '">' + data[count].visual + "</option>";
}
$("#visuals").html(html);
}
});
});
</script>
<script type="text/javascript">
$(document).on("change", "$visuals", function() {
$.ajax({
type: "POST",
url: "{{ url_for('graphs') }}",
data: {
visual: $("#visuals").val()
},
success: function(data) {
var html = "";
}
}
});
</script>
Here is the python code:
app=Flask(__name__)
#app.route("/")
def index():
etfs=['DIA','XLV','XLU','XLE','VNQ','GLD/SLV','QQQ','XLP','XLF']
return render_template("index.html", etfs=etfs)
#app.route("/visuals", methods=["POST","GET"])
def visuals():
etf_dict={'DIA':['UNH','GS','HD','MSFT','CRM'],'XLP':['PG','KO','PEP','WMT','COST'],
'XLV':['JNJ','UNH','PFE','ABT','ABBV'],'XLF':['BRK.B','JPM','BAC','WFC','C'],
'XLU':['NEE','DUK','SO','D','EXC'],'VNQ':['AMT','PLD','CCI','EQIX'],
'QQQ':['AAPL','MSFT','AMZN','GOOG','FB'],'XLE':['XOM','CVX','COP','MPC','SLB'],
'GLD/SLV':['GLD','SLV']}
if request.method == 'POST':
etf = request.form['etf']
holdings=etf_dict[etf]
options_list=[]
if etf=='GLD/SLV':
options_dict={}
options_dict['id']=etf
options_dict['visual']='GLD vs SLV'
options_list.append(options_dict)
else:
for i in holdings:
options_dict={}
options_dict['id']=etf
options_dict['visual']=i+' vs '+etf
options_list.append(options_dict)
options_list.append({'id':etf,
'visual': 'All Holdings vs ' +etf})
return jsonify(options_list)
#app.route("/graphs", methods=["POST","GET"])
def graphs():
print("inside graphs function")
if request.method == 'POST':
print("received post request from front end")
graph = request.form['visual']
flash("This worked! The graph chosen is" + graph)
return render_template("index.html")
if __name__ == "__main__":
app.run(debug=True)
Here is what the web app screen looks like. As you can see, when I select "XLE", it updates the second dropdown correctly, so I know the change function is working properly for the first dropdown.
Web App dropdowns
The problem is when I select a visual in the second dropdown, the other change function does not seem to be running..

I figured out that I should be using a form tag to submit the data from each of the dropdowns instead of trying to detect a change in the second dropdown..
Here is the updated HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Alpaca Pair Trading App</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.1/css/bootstrap-select.min.css">
<link rel="stylesheet" href={{url_for( 'static',filename='css/main.css' )}}>
</script>
</head>
<body>
<form action='/graphs' method='POST'>
<div class="container">
<h1 align="center">Welcome to the Alpaca Pair Trading Application! </h1>
<div class="row">
<div class="col-md-6">
<label>Select ETF</label>
<select name="etfs" data-live-search="true" id="etfs" class="form-control" class="selectpicker" title="Select ETF">
{% for etf in etfs %}
<option value="{{etf}}">{{etf}}</option>
{% endfor %}
</select>
</div>
<div class="col-md-6">
<label>Select Visual</label>
<select name="visuals" data-live-search="true" id="visuals" class="form-control" class="selectpicker" title="Select Visual"> </select>
</div>
</div>
</div>
<br>
<div class="container">
<div class="row">
<div class="col-md-4">
<input type="submit" name="next" value="Go" class="btn btn-primary">
</div>
</div>
</div>
</form>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.1/js/bootstrap-select.min.js">
</script>
<script type="text/javascript">
$("#etfs").change(function() {
$.ajax({
type: "POST",
url: "{{ url_for('visuals') }}",
data: {
etf: $("#etfs").val()
},
success: function(data) {
var html = "";
for (var count = 0; count < data.length; count++) {
html += '<option value="' + data[count].visual + '">' + data[count].visual + "</option>";
}
$("#visuals").html(html);
}
});
});
</script>
</body>
</html>

Related

How can I update an already rendered built finished Chart.js page Flask?

How can I update an already rendered built finished Chart.js page Flask?
There is already ready Chart.js on the template page.
The value data for which is taken from Flask.
After what action on the page the values in the Flask code changed.
How can I make it so that after a certain action in the route, Flask is additionally updated Chart.js?
I have been thinking for a long time how to make it so that it is updated Chart.js when I change the values in the Flask route ("/range") - I can transfer them (changed DataFrame values) to the database - but then I don't know how to update Chart.js.
it's html code
<div class="row">
<div class="col-md-3">
<input type="text" name="From" id="From" class="form-control" placeholder="From Date"/>
</div>
<div class="col-md-3">
<input type="text" name="to" id="to" class="form-control" placeholder="To Date"/>
</div>
<div class="col-md-6">
<input type="button" name="range" id="range" value="Range" class="btn btn-success"/>
</div>
</div>
<div id="purchase_order"></div>
<hr>
<div class="row" style="align-content: center">
{# <div class="col col-lg-0"></div>#}
</div>
<div class="outer-wrapper" style="align-content: center">
<div class="table-wrapper" id="table-wrapper" style="align-content: center">
<table>
<thead>
{% for col in column_names %}
<th>{{col}}</th>
{% endfor %}
</thead>
<tbody>
{% for row in row_data %}
<tr>
{% for cell in row %}
<td>{{ cell }}</td>
{% endfor %}
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
{# <div class="col col-lg-0"></div>#}
</div>
<div class="row">
<div class="col-md-1">
</div>
<div class="col-md-10">
<div>
<canvas id="myChart" width="800px" style="align-content: center"></canvas>
</div>
</div>
<div class="col-md-1">
</div>
</div>
<br>
</div>
It's script
</script>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
$(document).ready(function (){
$.datepicker.setDefaults({
dateFormat: 'yy-mm-dd'
});
$(function (){
$("#From").datepicker();
$("#to").datepicker();
});
$('#range').click(function (){
var From = $('#From').val();
var to = $('#to').val();
if (From != '' && to != '')
{
$.ajax({
url:"/range",
method:"POST",
data:{From:From, to:to},
success:function (data)
{
$('#table-wrapper').html(data);
$('#table-wrapper').append(data.htmlresponse);
}
});
}
else
{
alert("Please Select the Date")
}
});
});
</script>
<script>
const labels = [{% for item in os_x %}
"{{ item }}",
{% endfor %}];
const data = {
labels: labels,
datasets: [{
label: 'My First dataset',
backgroundColor: 'rgb(255, 99, 132)',
borderColor: 'rgb(255, 99, 132)',
data: [{% for item in os_y %}
{{ item }},
{% endfor %}],
}]
};
const config = {
type: 'line',
data: data,
options: {}
};
</script>
<script>
const myChart = new Chart(
document.getElementById('myChart'),
config
);
</script>
it's Flask routes
#app.route('/', methods=['GET','POST'])
#app.route('/index')
def home_page(): # put application's code here
df = pd.read_sql('select * from kotel', con=db.engine)
df['date'] = df['date'].dt.round('2min')
y_data = df['tnv'].tolist()
x_data = df['date'].tolist()
df_graph = df.copy()
return render_template('index new.html', column_names=df.columns.values, row_data=list(df.values.tolist()), column_names_graph=df_graph.columns.values, os_y = y_data, os_x = x_data)
#app.route("/range", methods=["POST","GET"])
def range():
if request.method == 'POST':
From = request.form['From']
to = request.form['to']
df = pd.read_sql('select * from kotel', con=db.engine)
df['date'] = pd.to_datetime(df['date'])
df = df.loc[(df['date'] >= From) & (df['date'] <= to)]
df['date'] = df['date'].dt.round('2min')
return jsonify({'htmlresponse': render_template('response.html', column_names=df.columns.values, row_data=list(df.values.tolist()))})
If the page is already loaded, only the values sent with the first request are displayed. If you want to see constantly updated values in your chart, you should use Websockets.
I've never worked with charts.js before, but I've used Flot Plot with Flask and Websocket to stream values to a chart in real time. it works great.
You can read more about Websockets and Flask here
If you want to load new values after and action, as example a click over a button, then you have to use ajax.
i found this page that could help you.
I see you are already using ajax. I would recommend just wrapping your code in a SetInterval() which will execute the code over and over again in a specific interval, you could do it like this
<script>
$(document).ready(function (){
setInterval(function() {
$.datepicker.setDefaults({
dateFormat: 'yy-mm-dd'
});
$(function (){
$("#From").datepicker();
$("#to").datepicker();
});
$('#range').click(function (){
var From = $('#From').val();
var to = $('#to').val();
if (From != '' && to != '')
{
$.ajax({
url:"/range",
method:"POST",
data:{From:From, to:to},
success:function (data)
{
$('#table-wrapper').html(data);
$('#table-wrapper').append(data.htmlresponse);
}
});
}
else
{
alert("Please Select the Date")
}
});
},1000);
});
</script>
you can change the number at the end, it specifies how long you want your interval to be in ms, so right now it's set to run every 1 second.

Django and Ajax. js not running

I hope anyone can help me with my code. I have here this html that was a js function with the goal that, whenever someone changes the "filament" option, it will change the "colors" available options available in the select:
<form method="post" enctype="multipart/form-data" style="max-width: 1000px;">
{% csrf_token %}
{{ form.as_p }}
{% for message in messages %}
<div class="alert alert-success">
<a class="close" href="#" data-dismiss="alert">×</a>
{{ message }}
</div>
{% endfor %}
<h2 class="sr-only">Login Form</h2>
<div class="illustration">
<div class="form-group">
<input type="file" name="printingfile"/ style="font-size: medium;">
<select class="form-select" aria-label="Default select example" id="=filament">
<option value="1">PLA</option>
<option value="2">ABS</option></select>
<select class="form-select" aria-label="Default select example" id="=color"></select>
<button class="btn btn-primary btn-block" type="submit">Submit</button></div>
</div>
</form>
</section>
<div></div>
<script src="{% static 'assets/js/jquery.min.js'%}"></script>
<script src="{% static 'assets/bootstrap/js/bootstrap.min.js'%}"></script>
<script src="{% static 'assets/js/Animated-Text-Background.js'%}"></script>
<script src="{% static 'assets/js/Cookie-bar-footer-popup.js'%}"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
{% block javascript %}
<script> //updating the colors available
$("#filament").change(function () {
var filament = $(this).val();
var color = $('#color');
console.log(filament);
$.ajax({
url: '/get_colors/',
data: {
'filament': filament
},
dataType: 'json',
success: function (data) {
color.empty();
for (var i = 0; i < data.lenght; i++) {
color.append('<option value=' + data[i].name + '>' + data[i].name + '</option>');
}
}
});
});
</script>
{% endblock javascript %}
</body>
</html>
This calls a view in Django. I know that the problem is here because I tried to use console.log and got 0 results, so probably there is nothing wrong (for now) in the Python code. Anyone could help me? Stuck here for hours and any tip would be really helpfull!

How to create ajax functions to control a form

I am developing a form in laravel that shows products and projects of a certain department. I need to create a function in js/ajax so I can allow users to choose a product, and once that happens, the project field in the form should show a drop-down menu of all the projects related to that product. How can I do that? Below is the code for the form, which has two fields (Produto) and (Projeto).
<form action="/arquiteturas/store" method="post" role="form" class="form-horizontal">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<div class="form-group {{$errors->has('combo_produto')? ' has-error' : '' }}">
<label class="col-md-2 control-label">Product</label>
<div class="col-md-8">
<select class="form-control search-select" name="combo_produto"
id="combo_produto">
<option value="0">Choose</option>
#foreach($produtos as $value)
<option #if(old('combo_produto')==$value->id){{'selected'}}#endif value='{{$value->id}}'>{{$value->nome}}</option>
#endforeach
</select>
<span class="help-block">
#if($errors->has('combo_produto'))
#foreach ($errors->get('combo_produto') as $error)
<b>{{$error}}</b>
#endforeach
#endif
</span>
</div>
</div>
<!--Projet.-->
<div class="form-group {{$errors->has('combo_projeto')? ' has-error' : '' }}">
<label class="col-md-2 control-label">Project</label>
<div class="col-md-8">
<select class="form-control search-select" name="combo_projeto" id="combo_projeto">
<option value="0">Choose</option>
#foreach($produtos as $value)
<option #if(old('combo_projeto')==$value->id){{'selected'}}#endif value='{{$value->id}}'>{{$value->nome}}</option>
#endforeach
</select>
<span class="help-block">
#if($errors->has('combo_projeto'))
#foreach ($errors->get('combo_projeto') as $error)
<b>{{$error}}</b>
#endforeach
#endif
</span>
</div>
</div>
I am sharing an excerpt of code for a similar funcionality of a form in which the user selects a product from a dropdown menu. Once that happens, a list of related branches is shown in the branch dropdown menu.
loadProdutos()
$("#combo_produto" ).change(function() {
clearCampos('combo_branch')
if(checkItemSel('combo_produto')){
$('#div_produto').removeClass('has-error');
$('.help-produto').empty();
var produto_id = document.getElementById('combo_produto').value
$('#combo_branch').prop("disabled", false);
loadbranchs(produto_id )
}else{
insertCombo('combo_branch', '0','Selecione')
$('#combo_branch').prop("disabled", true);
}
});
$("#combo_branch" ).change(function() {
if(checkItemSel('combo_produto')){
$('#div_branch').removeClass('has-error');
$('.help-branch').empty();
}
});
function loadProdutos()
{
var request = $.ajax({
method:"GET",
url:"/validar_fontes/request_produtos",
dataType:"json",
beforeSend: function () {
blockPage();
},
complete: function() {
// unblock when remote call returns
$.unblockUI();
}
});
request.done(function(e){
if(e.status){
if(e.produtos.length>0)
{
$('#combo_produto').append('<option value="0">Selecione</option>');
$('#combo_produto').val("0").trigger("change");
for(var i=0;i<e.produtos.length;i++)
{
$('#combo_produto').append('<option value="'+e.produtos[i]['id']+'">'+e.produtos[i]['nome']+'</option>');
}
}else
{
$('#combo_produto').append('<option value="0">Nenhum produto encontrado</option>');
$('#combo_produto').val("0").trigger("change");
}
}
});
}
function loadbranchs(produto_id)
{
var request = $.ajax({
method:"GET",
url:"/validar_fontes/request_branchs",
data:{produto_id : produto_id},
dataType:"json",
beforeSend: function () {
blockPage();
},
complete: function() {
// unblock when remote call returns
$.unblockUI();
}
});
request.done(function(e){
if(e.status){
if(e.branchs.length>0)
{
$('#combo_branch').append('<option value="0">Selecione</option>');
$('#combo_branch').val("0").trigger("change");
for(var i=0;i<e.branchs.length;i++)
{
$('#combo_branch').append('<option value="'+e.branchs[i]['id']+'">'+e.branchs[i]['nome']+'</option>');
}
}else
{
$('#combo_branch').append('<option value="0">Nenhuma branch encontrada</option>');
$('#combo_branch').val("0").trigger("change");
}
}
});
}
You have to create a end point (server side method in laravel) which will take the "producto" and return all "projecto" related to selected "producto"
Then on change event of "producto" dropdown in javascript/jquery you need to call the avobe created method and pass the producto value.
The projecto list should be key value pair so that it can be populated in dropdown projecto
Here is a draft page what you are trying to achieve, let me know if you can understand by this.
<!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 runat="server">
<title></title>
<script src="js/jquery-1.4.1.min.js" type="text/javascript"></script>
<script type = "text/javascript">
function PopulateContinents() {
var producto = $('#combo_produto').val();
if (producto == "") {
alert("Please select a valid product");
}
else {
$('producto').empty().append('<option selected="selected" value="0">Loading...</option>');
$.ajax({
type: "POST",
url: pageUrl + '<enter the url of server method created>',
data: '{producto: ' + producto + '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(datas){
for(i=0; i<datas.length; i++)
{
$('#combo_projeto options').append("<option value='"+datas[i].Value+"'>"+datas[i].Text+"</option>");
}
},
failure: function (response) {
alert(response.d);
}
});
}
}
</script>
<form action="/arquiteturas/store" method="post" role="form" class="form-horizontal">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<div class="form-group {{$errors->has('combo_produto')? ' has-error' : '' }}">
<label class="col-md-2 control-label">Product</label>
<div class="col-md-8">
<select class="form-control search-select" name="combo_produto"
id="combo_produto">
<option value="0">Choose</option>
#foreach($produtos as $value)
<option #if(old('combo_produto')==$value->id){{'selected'}}#endif value='{{$value->id}}'>{{$value->nome}}</option>
#endforeach
</select>
<span class="help-block">
#if($errors->has('combo_produto'))
#foreach ($errors->get('combo_produto') as $error)
<b>{{$error}}</b>
#endforeach
#endif
</span>
</div>
</div>
<!--Projet.-->
<div class="form-group {{$errors->has('combo_projeto')? ' has-error' : '' }}">
<label class="col-md-2 control-label">Project</label>
<div class="col-md-8">
<select class="form-control search-select" name="combo_projeto" id="combo_projeto">
<option value="0">Choose</option>
#foreach($produtos as $value)
<option #if(old('combo_projeto')==$value->id){{'selected'}}#endif value='{{$value->id}}'>{{$value->nome}}</option>
#endforeach
</select>
<span class="help-block">
#if($errors->has('combo_projeto'))
#foreach ($errors->get('combo_projeto') as $error)
<b>{{$error}}</b>
#endforeach
#endif
</span>
</div>
</div>
</body>
</html>

text message disapears after doing javascript validation

I have a form and I'm doing some validation JavaScript before send it to PHP, and the JavaScript function after validation post the text the user entered in a <p> tag at the bottom of the page; However, this message displays briefly and then disappears...
How can I make the message stay in the page, and send the rest of data to a PHP script?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<title>Contact Us</title>
<!-- Bootstrap -->
<link href="bootstrap.min.css" rel="stylesheet">
<!-- stylesheet for this form -->
<link href="contact-stylesheet.css" rel="stylesheet">
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
<script type="text/javascript">
function validateForm() {
var message = "";
var letters = /^[A-Za-z]+$/;
var name = document.forms["myForm"]["name"].value;
var email = document.forms["myForm"]["email"].value;
var subject = document.forms["myForm"]["subject"].value;
var text = document.forms["myForm"]["text"].value;
var outputMsg = "";
if (name == null || name == "") {
message += "name field missing!\n";
}
if (name != "" && !name.match(letters)) {
message += "Invalid name: only letters allowed!\n";
}
if (subject == null || subject == "") {
message += "Subject field is empty!\n";
}
if (text == null || text == "") {
message += "Text field is empty!\n";
}
if (message != "" ) {
alert(message);
return false;
}
outputMsg = "Message Sent!....\n" +
"Name: " + name + "\n" +
"Email: " + email + "\n" +
"Subject: " + subject + "\n" +
"Text: " + text + "\n";
document.getElementById("msg-result").innerHTML = outputMsg;
return true;
}
</script>
</head>
<body>
<div class="row">
<div class="hero-unit" style="padding:20px 100px">
<h1>Contact Us</h1>
<p>aldkfjasdkfjaskdfasdfkasdkfjadsfjsdkfjaskfjasdkfjasjfaskdfjsdkfjsksdsdkjsd</p>
</div>
<div class="col-sm-6">
<div class="my-form">
<form class="form-horizontal" name="myForm" action="" onsubmit="validateForm()" method="post">
<div class="form-group">
<label for="inputEmail3" class="col-sm-2 control-label">Name:</label>
<div class="col-sm-8">
<input type="name" name="name" class="form-control" id="inputEmail3" placeholder="Name">
</div>
</div>
<div class="form-group">
<label for="inputPassword3" class="col-sm-2 control-label">Email:</label>
<div class="col-sm-8">
<input type="email" name="email" class="form-control" id="inputPassword3" placeholder="Email">
</div>
</div>
<div class="form-group">
<label for="inputPassword3" class="col-sm-2 control-label">Subject:</label>
<div class="col-sm-8">
<input type="text" name="subject" class="form-control" placeholder="Subject">
</div>
</div>
<div class="form-group">
<label for="inputPassword3" class="col-sm-2 control-label">Text:</label>
<div class="col-sm-8">
<textarea name="text" class="form-control" rows="7" placeholder="Text"></textarea>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-default">Send</button>
</div>
</div>
</div>
</form>
</div>
<div class="col-sm-6">
<div style="width:500px;heigth:350px;border:solid 1px brown">
<h1>GOOGLE MAP HERE!</h1>
</div>
<!-- <img sytle="padding:0px 20px" src="https://maps.googleapis.com/maps/api/staticmap?center=Miami+Downtown,Miami,FL&zoom=13&size=500x350&maptype=roadmap&markers=color:red%7CMiami+Downtown,Miami,FL"> -->
</div>
</div>
<div class="col-sm-6" style="padding:10px 140px">
<p id="msg-result"></p>
<!-- display form result message here! -->
</div>
<!--
Welcome <?php echo $_POST["name"]; ?><br>
Your email address is: <?php echo $_POST["email"]; ?>
-->
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="js/bootstrap.min.js"></script>
</body>
</html>
It's because you are updating the text in the field and then submitting to php (wiping out all of the fields since the page refreshes). You could set hidden elements to hold the values that you want to display so they post over to php and then you can just echo them where you want them to be. Another way of doing it would be to make an ajax call to a php to do your updating instead of posting back to the same page.
So with ajax you would do something like:
formSubmit()
{
//do validation
//do a jquery post to a php page
$.ajax
({
type: "POST",
//the url of the php page
url: 'test.php',
dataType: 'json',
async: false,
//json object to sent to the authentication url
data: '{"test": "info"}',
success: function (result) {
//update stuff
}
})
return false;
}
I think the form is submitted after the check. You must return the result (to cancel the submit if validateForm() is false):
onsubmit="return validateForm();"
or prevent default:
onsubmit="return validateForm(event);"
with
function validateForm(event) {
...
event.preventDefault();

Get value of input without submitted form

I need to make my jsp page work without reloading page using jquery.
$(".btn.btn-default.btn-lg").click(function( event ) {
event.preventDefault();
$.post(main.jsp,{operand1: request.getParameter("operand1")});
alert(<%= request.getParameter("operand1") %>);
});
I'm trying to post parameter to the page and alert it. Nothing happens.
However function works fine.
what's my mistake?
Here is full jsp code.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="css/bootstrap.min.css" rel="stylesheet">
<title>Insert title here</title>
</head>
<body>
<script src="https://code.jquery.com/jquery.js"></script>
<script src="js/bootstrap.min.js"></script>
<form class="form-horizontal" role="form" method="get">
<div class="form-group">
<div class="col-lg-10">
<input name="operand1" id="operand1" class="values"></input>
<input name="operand2" id="operand2" class="values"></input>
</div>
</div>
<div class="form-group">
<div class="col-lg-10">
<select name="operation" id="operation" class="values">
<option value="plus">+</option>
<option value="minus">-</option>
<option value="multiply">*</option>
<option value="divide">/</option>
<option value="mod">mod</option>
</select>
</div>
</div>
<div class="form-group">
<div class="col-lg-10">
<input type="submit" class="btn btn-default btn-lg" value="Submit"></input>
</div>
</div>
</form>
<script>
$(".btn.btn-default.btn-lg").click(function( event ) {
event.preventDefault();
$.ajax({
method:"POST",
url: "main.jsp",
data: {operand1: document.getElementById("operand1").value, operand2: document.getElementById("operand2").value, operation: document.getElementById("operation")}
}).done(function (result) {
alert(result);
});
alert($('input.values').val());
});
</script>
<%
Double operand1=0.0;
Double operand2=0.0;
String operation=new String();
if ((request.getParameter("operand1")!=null)&&(request.getParameter("operand2")!=null)&&(request.getParameter("operation")!=null)){
operand1 = Double.parseDouble(request.getParameter("operand1"));
operand2 = Double.parseDouble(request.getParameter("operand2"));
operation=request.getParameter("operation");
}
Double result=0.0;
if (operation.equals("plus")){
result=operand1+operand2;
}
if (operation.equals("minus")){
result=operand1-operand2;
}
if (operation.equals("divide")){
result=operand1/operand2;
}
if (operation.equals("multiply")){
result=operand1*operand2;
}
if (operation.equals("mod")){
result=operand1%operand2;
}
if ((request.getParameter("operand1")!=null)&&(request.getParameter("operand2")!=null)&&(request.getParameter("operation")!=null)){
String resultString="Result:";
out.println(resultString+result);
}
%>
</body>
</html>
Any suggestions?
You should use ajax something like this:
$(".btn.btn-default.btn-lg").click(function( event ) {
$.ajax({
method:"POST",
url: "main.jsp",
data: {operand1: document.getElementById("operand1").value}
}).done(function (result) {
alert(result)
});
});
request is a JSP implicit object which will not work in javascript. Instead you can use following to get the value.
$('#operand1').val(); //operand1 is an id of the element
Use the success callback :
$(".btn.btn-default.btn-lg").click(function( event )
{
$.ajax(
{
method:"POST",
url: "main.jsp",
data: {operand1: document.getElementById("operand1").value},
success: function(result)
{
alert(result);
}
})
});

Categories