Update database from bootstrap modal using AJAX - javascript

I am creating a page which displays some records from the database (please refer to the screen shots). Each row has an edit button which opens up a bootstrap modal for inputing comments and changing the user's status. On clicking the done button, I have to update the changes in the database preferably using AJAX. However it's not properly working. I can't seem to understand what's going wrong.
This is my jsp page...
<%#page import="java.sql.ResultSet"%>
<%#page import="java.sql.Statement"%>
<%#page import="java.sql.Connection"%>
<%#page import="java.util.ArrayList"%>
<%# 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 lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<link rel="stylesheet"
href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script
src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<%
String loginIdEdit = "";
%>
**<script>
$(function() {
//twitter bootstrap script
$("button#save").click(function(e) {
$.ajax({
type : "POST",
url : "defaulterUpdater.jsp",
data : $('form.contact').serialize(),
success : function(msg) {
},
error : function() {
alert("Failed");
}
});
});
});
</script>**
<script type="text/javascript">
function myFun() {
alert("welcome");
var demo = document.createElement('div');
demo.innerHTML = demo.innerHTML
+ "<tr><input type='text' name='mytext'><tr>";
}
</script>
</head>
<body>
<div class="container">
<form method="post" action="RegistrationServlet">
<%
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Cache-Control", "no-store");
response.setHeader("Pragma", "no-cache");
response.setDateHeader("Expires", 0);
Connection con = null;
con = DBManager.getConnection();
Statement st = con.createStatement();
String userName = "";
ArrayList<AutoDefaulterVO> defaulterList = null;
HttpSession session2 = request.getSession();
if (session2.getAttribute("first_name") == null) {
out.println("Your session expired.....");
%>
Please Login Again to continue
<%
} else {
defaulterList = (ArrayList<AutoDefaulterVO>) session2
.getAttribute("autoDefaulterList");
userName = session2.getAttribute("first_name").toString();
%>
<form action='LogoutServlet' method=POST>
<table align="right" style="width: 100%">
<tr>
<td align="left"><input type="submit" name="logout"
value="Home" onclick="form.action='AdminHome';">
</td>
<td align="right"><input type="submit" name="logout"
value="Logout" onclick="form.action='LogoutServlet'">
</td>
</tr>
</table>
</form>
<h3 align="center">Auto Defaults</h3>
<table border="1" style="width: 100%">
<br>
<br>
<h3 align="center">
Welcome
<%=userName%></h3>
<table border="1" style="width: 100%" class="table table-hover">
<tr>
<th>Default Status</th>
<th>Borrower Name</th>
<th>Borrower Rating</th>
<th>Accural Status</th>
<th>Bank Number</th>
<th>Account Number</th>
<th>Days Past Due</th>
<th>Comments</th>
</tr>
<%
for (int i = 0; i < defaulterList.size(); i++) {
AutoDefaulterVO defaulter = new AutoDefaulterVO();
defaulter = defaulterList.get(i);
loginIdEdit = defaulter.getDefaulterLoginID();
System.out.println("Printing only auto defaulter in jsp ");
%>
<tr>
<%-- <td><%=defaulter.getDefaultStatus()%></td> --%>
<td>Auto Defaulter</td>
<td><%=defaulter.getBorrowerName()%></td>
<td><%=defaulter.getBorrowerRating()%></td>
<td><%=defaulter.getAccuralStatus()%></td>
<td><%=defaulter.getBankNumber()%></td>
<td><%=defaulter.getAccountNumber()%></td>
<td><%=defaulter.getDaysPastDue()%></td>
<%-- <td><%=loginIdEdit%></td> --%>
<td>
<%
ResultSet rs = st
.executeQuery("select * from aip_comments");
while (rs.next()) {
System.out.println("Auto defaulter loginId printing-->"
+ defaulter.getDefaulterLoginID());
String loginId = rs.getString("login_id");
System.out.println("databse loginId printing-->"
+ rs.getString("login_id"));
if (defaulter.getDefaulterLoginID().equals(
rs.getString("login_id"))) {
%> <%=rs.getString("comments")%> <%
}
}
%>
</td>
<td>
<!-- <form name="editForm" action="edit.jsp">
<button type="button" data-toggle="modal" class="btn btn-default" data-target="#myModal">Edit</button>
-->
<form class="contact">
<button href="#edit-modal" type="button" data-toggle="modal"
class="btn btn-default" data-target="#<%=loginIdEdit %>">Edit</button>
<!-- <a data-toggle="modal" data-target="#<%=loginIdEdit%>" href="#">Edit</a> -->
<!-- <input type="submit" name="editButton" value="Edit"> -->
<!--<input type="hidden" id="edit" name="edit" value="<%=loginIdEdit%>" />-->
</td>
<div class="modal fade" id="<%=loginIdEdit%>" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">
Edit status and add comment for
<%=defaulter.getBorrowerName()%></h4>
</div>
<div class="modal-body">
<div class="form-group">
<label for="sel1"><span></span>Select status:</label> <select
class="form-control" id="sel1" name="sel1">
<option>Validate Error</option>
<option>Auto Weaver</option>
<option>ReDefault</option>
</select>
</div>
<div class="form-group">
<label for="defaultercomment"><span></span>Add
comment:</label> <input type="text" class="form-control"
name="defaultercomment" id="defaultercomment"<%-- value="<%=loginIdEdit%>" --%>>
</div>
</div>
<div class="modal-footer">
<button type="button" id="save" name="save"
class="btn btn-default" data-dismiss="modal" align="centre">Done</button>
</div>
</div>
</div>
</div>
</form>
<%
}
%>
</tr>
</table>
<%
}
%>
</body>
</html>
ajax URL redirects to below jsp page,defaulterUpdater.jsp where I only print the values to see if they're correctly retrieved.
<%# 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>
</head>
<body>
<% String selection = request.getParameter("sel1");
String comment = request.getParameter("defaultercomment");
System.out.println("selection-"+selection+"comment--"+comment);
%>
</body>
</html>
The values are accepted only for the first row..For rest of the rows null values are being printed. Any help will be appreciated. Thanks!

I got the code working. Basically needed an unique identifier for "done" button as is rule of javascript. Hence it was not working for all rows.
I gave unique id's to the form
and by submitting called the onclick method..
onClick="callAjax(this.form)"
So now it's working. Thank you all for your help!

You are putting the modal wrong inside the table. By table syntax it is wrong. You must put this modal out from the table and call ajax inside the shown.bs.modal event of bootstrap.
As you need to repeat buttons. Keep a hardwired id of the button which will open the modal, also keep an data-attribute-id to uniquely identify the button clicked which will help you to get details about which button clicked in the list(as buttons are repeating for each row, your data-attribute-id will be loginid of the row).
Then write jquery with event shown.bs.modal, like
$("#modalId").on("shown.bs.modal", function(e){
var btnClicked= $(e).relatedTarget();
var btnClickedId= btnClicked.data("attribute-id"); // id of clicked button
// here more code see attached link below for more
}
I have posted a similer answer previously in asp.net mvc but you will have idea as situation is similer to you.
Please visit my answer on question dynamically created bootstrap3 modals do not work
Hope it will help to get idea to resolve this.
#Update Section Removed your some code for clean view
<script type="text/javascript">
$(document).ready(function () {
$('#editModal').on('show.bs.modal', function (event) {
var button = $(event.relatedTarget);//Button which is clicked
var clickedButtonId= button.data('loginidedit');//Get loginidedit of the button or get other variable same
$("#loginid").val(clickedButtonId);//Put here id of the btn clicked which has attribute for loginidedit
//you can get here other required filed or make ajax call to get other values formt he database for this loginidedit.
})
});
</script>
<body>
<div class="container">
//Table here
<table border="1" style="width: 100%" class="table table-hover">
<%
for (int i = 0; i < defaulterList.size(); i++) {
AutoDefaulterVO defaulter = new AutoDefaulterVO();
defaulter = defaulterList.get(i);
loginIdEdit = defaulter.getDefaulterLoginID();
System.out.println("Printing only auto defaulter in jsp ");
%>
<tr>
<td>
<button href="#edit-modal" type="button" data-toggle="modal"
class="btn btn-default" data-target="#editModal" data-loginidedit = "<%=loginIdEdit %>">Edit</button>
</td>
</tr>
<%
}
%>
</table>
//Modal here
<div class="modal fade" id="editModal" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
</div>
<form class="contact"> //give action, method attribute here or make ajax call on save button clicked,
<input type="hidden" name="????" id="loginid">// the modal on shown will fill this value.
<div class="modal-body">
<div class="form-group">
<label for="sel1"><span></span>Select status:</label> <select
class="form-control" id="sel1" name="sel1">
<option>Validate Error</option>
<option>Auto Weaver</option>
<option>ReDefault</option>
</select>
</div>
<div class="form-group">
<label for="defaultercomment"><span></span>Add
comment:</label> <input type="text" class="form-control"
name="defaultercomment" id="defaultercomment"<%-- value="<%=loginIdEdit%>" --%>>
</div>
</div>
<div class="modal-footer">
<button type="button" id="save" name="save"
class="btn btn-default" data-dismiss="modal" align="centre">Done</button>
</div>
</form>
</div>
</div>
</div>
</body>
</html>
$(function() {
//twitter bootstrap script
$("button#save").click(function(e) {
$.ajax({
type : "POST",
url : "defaulterUpdater.jsp",
data : $('form.contact').serialize(),
success : function(msg) {
},
error : function() {
alert("Failed");
}
});
});
});

Related

Adding Dynamic buttons to display pop-up window to link entries

I am creating a list of entries each with a Link button in a foreach loop on my Razor Page. The Link button is clicked to open a modal with another list of entries and all of these entries have a checkbox. This view allows me to Link an entry to multiple other entries. Code below for HTML:
#foreach (var entry in Model.EntryList.Where(w => w.IsLinked == false))
{
<tr>
<td class="pt-3-half" contenteditable="true">#entry.Description</td>
<td class="pt-3-half" contenteditable="true">
<button id="btnShowModal" type="button" class="btn btn-sm btn-default pull-left col-lg-11 button button4">
Link
</button>
<div class="modal fade" tabindex="-1" id="loginModal"
data-keyboard="false" data-backdrop="static">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Link Entries</h4>
<button type="button" class="close" data-dismiss="modal">
×
</button>
</div>
<form enctype="multipart/form-data" asp-controller="Home" asp-action="Index" asp-route-id="#entry.Description" method="post" class="mt-3">
<div class="modal-body">
<table style="text-align: center; width: 100%">
<thead>
<tr>
<th class="text-center">Description</th>
<th class="text-center"></th>
</tr>
</thead>
<tbody>
#foreach (var LinkEntry in Model.EntryList.Where(w => w.IsLinked == true))
{
<tr>
<td class="pt-3-half" contenteditable="true">#LinkEntry.Description</td>
<td class="pt-1-half" contenteditable="true">
<input name="AreChecked" type="checkbox" value="#LinkEntry.Id" />
</td>
</tr>
}
</tbody>
</table>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary button button4">Link Entries</button>
<button type="button" id="btnHideModal" class="btn btn-primary button button4">
Hide
</button>
</div>
</form>
</div>
</div>
</div>
</tbody>
</table>
</div>
</td>
</td>
</tr>
}
When the Link button is clicked the below jQuery runs:
<script type="text/javascript">
$(document).ready(function () {
$("#btnShowModal").click(function () {
$("#loginModal").modal('show');
});
$("#btnHideModal").click(function () {
$("#loginModal").modal('hide');
});
});
</script>
The current problem I have is that only the first Link button shows the Modal div. The rest of the Link buttons do not do anything when clicked. So I then moved the entire Modal Div outside of the foreach but does not fix the problem and this then also doesn't allow me to parse the asp-route-Id due to now being outside the foreach.
The issue here is that you are using hard-coded ids for your buttons, but they are created in a loop so more than one element with the same id is created, which you definitely do not want.
Remove the ids and replace them with a unique class, like btn-show-modal, then change your jquery selector from $("#btnShowModal") to $(".btn-show-modal").
Do the same thing with your hide buttons, but use a different unique class name like btn-hide-modal. Be sure to do this with all hard-coded ids (looks like there is at least one more instance).
One other point I should make is you will need to query the modal relative to the button that is clicked. Inside the click events, you should do $(this).next().modal('show') / $(this).next().modal('hide') , since as stated, you need to remove the id="loginModal" and will need an alternative method to get the correct modal to show.
I believe jquery is smart enough to not search the entire DOM when using the id selector (#), so that is why only your first button is firing your click event.
My suggestion to future proof these kinds of errors is to create a <script> that will search the DOM for duplicate ids and show an alert(), or something, to let you know that your DOM is invalid. I'd also make sure that this script is only added when debugging, as with this <script> you will catch the errors during development and do not want to the extra overhead in production.
Yes as William says, you have that error because you are using an id and that button is being created so many times as items you have in your collection. And if I was you I'll put the modal outside the first loop because otherwise you can create a lot of modal too. I leave you an example of something that I hope can help you.
This is the model:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace HelloWorldMvcApp
{
public class SampleViewModel
{
[Required]
[MinLength(10)]
[MaxLength(100)]
[Display(Name = "Ask Magic 8 Ball any question:")]
public string Question { get; set; }
//See here for list of answers
public string Answer { get; set; }
public List<Test> EntryList { get; set; }
}
public class Test {
public int Id { get; set; }
public string Description { get; set; }
public bool IsLinked { get; set; }
}
}
Here you are the controller:
using System;
using System.Web.Mvc;
using System.Collections.Generic;
namespace HelloWorldMvcApp
{
public class HomeController : Controller
{
[HttpGet]
public ActionResult Index()
{
var list = new SampleViewModel();
list.EntryList = new List<Test>();
var test1 = new Test();
test1.Id = 1;
test1.Description = "test1";
test1.IsLinked = false;
list.EntryList.Add(test1);
var test2 = new Test();
test2.Id = 2;
test2.Description = "test2";
test2.IsLinked = false;
list.EntryList.Add(test2);
var test3 = new Test();
test3.Id = 3;
test3.Description = "test3";
test3.IsLinked = false;
list.EntryList.Add(test3);
var test11 = new Test();
test11.Id = 11;
test11.Description = "test11";
test11.IsLinked = true;
list.EntryList.Add(test11);
var test12 = new Test();
test12.Id = 12;
test12.Description = "test12";
test12.IsLinked = true;
list.EntryList.Add(test12);
var test21 = new Test();
test21.Id = 21;
test21.Description = "test21";
test21.IsLinked = true;
list.EntryList.Add(test21);
var test22 = new Test();
test22.Id = 22;
test22.Description = "test22";
test22.IsLinked = true;
list.EntryList.Add(test22);
return View(list);
}
}
}
And this is the view.
#model HelloWorldMvcApp.SampleViewModel
#{
Layout = null;
}
<!DOCTYPE html>
<!-- template from http://getbootstrap.com/getting-started -->
<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">
<title>Bootstrap 101 Template</title>
<!-- CSS Includes -->
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
<style type="text/css">
.field-validation-error {
color: #ff0000;
}
</style>
</head>
<body>
<div class="container">
<div class="col-md-6 col-md-offset-3">
<table>
<tbody>
#foreach (var entry in Model.EntryList.Where(w => w.IsLinked == false))
{
<tr>
<td class="pt-3-half" contenteditable="true">#entry.Description</td>
<td class="pt-3-half" contenteditable="true">
<button type="button" onClick="showModal('#entry.Description')" class="btn btn-sm btn-default pull-left col-lg-11 button button4">
Link
</button>
</td>
</tr>
}
</tbody>
</table>
<div class="alert alert-warning fade">
<img src="http://entechprod.blob.core.windows.net/dotnetfiddle/morpheus.jpg"
style="max-width:100%;" /><br /><br />
<strong><span class="alert-content"></span></strong>
</div>
</div>
</div>
<div class="modal fade" tabindex="-1" id="loginModal" data-keyboard="false" data-backdrop="static">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Link Entries</h4>
<button type="button" class="close" data-dismiss="modal">
×
</button>
</div>
<form enctype="multipart/form-data" id="modalForm" asp-controller="Home" asp-action="Index"
asp-route-id="" method="post" class="mt-3">
<div class="modal-body">
<table style="text-align: center; width: 100%">
<thead>
<tr>
<th class="text-center">Description</th>
<th class="text-center"></th>
</tr>
</thead>
<tbody>
#foreach (var LinkEntry in Model.EntryList.Where(w => w.IsLinked == true))
{
<tr>
<td class="pt-3-half" contenteditable="true">#LinkEntry.Description</td>
<td class="pt-1-half" contenteditable="true">
<input name="AreChecked" type="checkbox" value="#LinkEntry.Id" />
</td>
</tr>
}
</tbody>
</table>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary button button4">Link Entries</button>
<button type="button" onClick="hideModal()" class="btn btn-primary button button4">
Hide
</button>
</div>
</form>
</div>
</div>
</div>
<!-- JS includes -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
<script src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>
<script src="//ajax.aspnetcdn.com/ajax/mvc/4.0/jquery.validate.unobtrusive.min.js"></script>
<script type="text/javascript">
function showModal(desc) {
$('#modalForm').attr('asp-route-id', desc);
$("#loginModal").modal('show');
}
function hideModal(desc) {
$("#loginModal").modal('hide');
}
</script>
</body>
</html>
Creating a modal for each entry in the loop seems unnecessary to me,
Create a single modal outside your loop and update all its data according with the Link button you clicked
Use data- attributes to pass the info you require to the click event and to build/update your modal, you can JSON your info and use a javascript function to create the table and checkboxes bit
#foreach (var entry in Model.EntryList.Where(w => w.IsLinked == false))
{
<tr>
<td class="pt-3-half" contenteditable="true">#entry.Description</td>
<td class="pt-3-half" contenteditable="true">
<button data-entry-id="#entry.Id" data-entries="<?= htmlentities(json_encode(Model.EntryList.Where(w => w.IsLinked == true)))?>" id="btnShowModal" type="button" class="btn btn-sm btn-default pull-left col-lg-11 button button4 ">
Link
</button> ...
then you add a listener with JS to all those Link buttons
function onClickLinkButtonUpdateModal($e){
let entries = JSON.parse($e.target.dataset.entries);
let entry_id = $e.target.dataset.entryId;
//pass the info you need, you can create the tr elements or the whole tbody with document.create or with template literals
let tr_entries = generateHTMLEntries(entry_id, entries);
//assuming you put an id to the table or the table body
document.querySelector('#modal-table').appendChild(tr_entries);
//or
//document.querySelector('#modal-tbody').innerHTML = tr_entries;
}

HTML not processing correctly

We are working on a dApp that is giving us problems. The site loads OK and the button to open the subform ("Post My Rental") works. When I fill out the subform and click the 'submit' button, nothing happens. I have confirmed that I am connected to Metamask and Ganache, but no transaction goes through. Checking inspect in Chrome, no errors there. I suspect there is something missing in this code, but I can't find it. If you could help out, we would really appreciate it. Here is the HTML:
<!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>Rent My Place</title>
<!-- Title will appear as a tab in browser on webpage -->
<!-- Bootstrap -->
<link href="css/bootstrap.min.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.3/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
<!-- Application -->
<link href="css/app.css" rel="stylesheet">
<!-- stylesheet refers to the look of the page, Font, color-->
</head>
<body>
<div class="container">
<!-- container that contains title panel-->
<div class="jumbotron text-center">
<p style="font-size:80px;padding: 1em;padding-top: 10px;padding-bottom: 10px; border:10px;border-style:solid;border-color:#c3c3c3;">
<font color = "#880015" >Rent My Place</font></p>
</div>
<div class="col-md-12" id="article-list">
<div class="row">
<div class="col-lg-12">
<!--<p id="account" class="welcome pull-right"></p>
<p id="accountBalance" class="welcome pull-left"></p>-->
</div>
</div>
<div class="row panel panel-default">
<div class="panel-heading clearfix">
<div class="panel-title">
<p style="font-size:24px;padding: 1em;padding-top: 10px;padding-bottom: 10px; border:5px;border-style:solid;border-color:#c3c3c3;">
<font color = "#880015">Renter's Tip: </font><font color = "#000000">Inspect the property before you send money.</font><br><font color = "#880015">Landlord's Tip: </font><font color = "#000000">Meet prospective tenants in person.</font></p>
<!-- Button that opens second window to a form to fill out-->
<button class="btn btn-info btn-lg pull-right" data-toggle="modal" data-target="#sellArticle">Post a Rental</button>
</div>
</div>
<!-- when the event button gets click, it will show the list-->
<ul id="events" class="collapse list-group"></ul>
</div>
<div id="articlesRow" class="row">
<!-- ARTICLES with pertinent item information LOAD HERE -->
</div>
</div>
</div>
<!--Result that is displayed after input-->
<div id="articleTemplate" style="display: none;">
<div class="row-lg-12">
<div class="panel panel-default panel-article">
<div class="panel-heading">
<h3 class="panel-title"></h3>
</div>
<div class="panel-body">
<strong>Beds</strong>: <span class="beds"></span><br/>
<strong>Baths</strong>: <span class="baths"></span><br/>
<strong>Address</strong>: <span class="propaddress"></span><br/>
<strong>Rental Price</strong>: <span class="rental_price"></span><br/>
<strong>Description</strong>: <span class="article_description"></span><br/>
<strong>Property is available for showing</strong>: <span class="available"></span><br/>
<strong>Contact Email</strong>: <span class="contact_email"></span><br/>
<!--<strong>Sold by</strong>: <span class="article-seller"></span><br/>-->
</div>
<div class="panel-footer">
<button type="button" class= "btn btn-primary btn-success btn-buy" onclick="App.buyArticle(); return false;">Buy</button>
</div>
</div>
</div>
</div>
<!-- Modal form to sell an article -->
<div class="modal fade" id="sellArticle" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Rent Your Place</h4>
</div>
<div class="modal-body">
<div class="row">
<div class="col-lg-12">
<form>
<div class="form-group">
<!--NOTE: For radio buttons to work, 'name' field must match-->
<label for="property_type">Property Type</label>
<input type="radio" name="property" id="property_type" value="house" > House
<input type="radio" name="property" id="property_type" value="apartment" > Apartment
<input type="radio" name="property" id="property_type" value="duplex" > Duplex
</div>
<div class="form-group">
<label for="propaddress">Address</label>
<input type="text" class="form-control" id="propaddress" placeholder="Enter the address">
</div>
<div class="form-group">
<label for="beds">Beds</label>
<input type="radio" name="beds" id="beds" value="0"> Studio
<input type="radio" name="beds" id="beds" value="1"> One
<input type="radio" name="beds" id="beds" value="2"> Two
<input type="radio" name="beds" id="beds" value="3"> Three +
</div>
<div class="form-group">
<label for="baths">Baths</label>
<input type="radio" name="baths" id="baths" value="1"> One
<input type="radio" name="baths" id="baths" value="2"> Two
<input type="radio" name="baths" id="baths" value="3"> Three +
</div>
<div class="form-group">
<label for="rental_price">Rent (in USD)</label>
<input type="text" class="form-control" id="rental_price" placeholder="$" pattern="[0-9]+([\.,][0-9]+)?">
</div>
<div class="form-group">
<label for="description">Description</label>
<textarea type="text" class="form-control vresize" id="article_description" placeholder="Describe your property" maxlength="255"></textarea>
</div>
<div class="form-group">
<label for="available"></label>
<input type="checkbox" name="available" value="available" id="available"> Property is available for showing
</div>
<div class="form-group">
<label for="contact_email">Contact Email</label>
<input type="text" class="form-control" id="contact_email" placeholder="Enter your contact email">
</div>
</form>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary btn-success" data-dismiss="modal" onclick="App.sellArticle(); return false;">Submit</button>
<button type="button" class="btn" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<div id="footer" class="container">
<nav class="navbar navbar-default navbar-fixed-bottom">
<div class="navbar-inner navbar-content-center text-center">
<p class="text-muted" credit>AXbean - © 2018</a></p>
</div>
</nav>
</div>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="js/OurRentalManualInputDataInitWeb3appMay22.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/web3.min.js"></script>
<script src="js/truffle-contract.js"></script>
</body>
</html>
Here is the app.js that is called:
App = {
web3Provider: null,
contracts: {},
account: 0x0,
loading: false,
init: function() {
return App.initWeb3();
},
initWeb3: function() {
// initialize web3
if(typeof web3 !== 'undefined') {
//reuse the provider of the Web3 object injected by Metamask
App.web3Provider = web3.currentProvider;
} else {
//create a new provider and plug it directly into our local node
App.web3Provider = new Web3.providers.HttpProvider('http://localhost:7545');
}
web3 = new Web3(App.web3Provider);
App.displayAccountInfo();
return App.initContract();
},
displayAccountInfo: function() {
web3.eth.getCoinbase(function(err, account) {
if(err === null) {
App.account = account;
$('#account').text(account);
web3.eth.getBalance(account, function(err, balance) {
if(err === null) {
$('#accountBalance').text(web3.fromWei(balance, "ether") + " ETH");
}
})
}
});
},
initContract: function() {
$.getJSON('OurRentalTestFromClassMay24.json', function(chainListArtifact) {
//added May24 to json file name
// get the contract artifact file and use it to instantiate a truffle contract abstraction
App.contracts.OurRentalTestFromClassMay24 = TruffleContract(chainListArtifact);
// set the provider for our contracts
App.contracts.OurRentalTestFromClassMay24.setProvider(App.web3Provider);
// listen to events
App.listenToEvents();
// retrieve the article from the contract
return App.reloadArticles();
});
},
reloadArticles: function() {
//avoid reentry bugs
if(App.loading){
return;
}
App.loading = true;
// refresh account information because the balance might have changed
App.displayAccountInfo();
var chainListInstance;
App.contracts.OurRentalTestFromClassMay24.deployed().then(function(instance) {
chainListInstance = instance;
return chainListInstance.getArticlesForSale();
}).then(function(articlesIds) {
// retrieve the article placeholder and clear it
$('#articlesRow').empty();
for(var i = 0; i < articlesIds.length; i++){
var articleId = articlesIds[i];
chainListInstance.articles(articleId.toNumber()).then(function(article){
App.displayArticle(article[0], article[1], article[3], article[4], article[5]);
});
}
App.loading = false;
}).catch(function(err) {
console.error(err.message);
App.loading = false;
});
},
displayArticle: function(id, seller, beds, baths, propaddress, rental_price, description, available, contact_email){
var articlesRow = $('#articlesRow');
var etherPrice = web3.fromWei(price, "ether");
var articleTemplate = $("#articleTemplate");
//articleTemplate.find('.panel-title').text(name);
articleTemplate.find('.beds').text(beds);
articleTemplate.find('.baths').text(baths);
articleTemplate.find('.propaddress').text(propaddress);
articleTemplate.find('.rental_price').text(rental_price);
articleTemplate.find('.description').text(description);
articleTemplate.find('.available').text(available);
articleTemplate.find('.contact_email').text(contact_email);
// articleTemplate.find('.article_price').text(etherPrice + " ETH");
articleTemplate.find('.btn-buy').attr('data-id', id);
articleTemplate.find('.btn-buy').attr('data-value', etherPrice);
//seller
if(seller == App.account){
articleTemplate.find('.article-seller').text("You");
articleTemplate.find('.btn-buy').hide();
}else{
articleTemplate.find('.article-seller').text(seller);
articleTemplate.find('.btn-buy').show();
}
//add this new article
articlesRow.append(articleTemplate.html());
},
sellArticle: function() {
// retrieve the detail of the article
// var _article_name = $('#article_name').val();
var _description = $('#description').val();
var _beds = $('#beds').val();
var _baths = $('#baths').val();
var _propaddress = $('#propaddress').val();
var _rental_price = $('#rental_price').val();
var _property_type = $('#property_type').val();
var _available = $('#available').val();
var _contact_email = $('#contact_email').val();
// var _article_price = $('#article_price').val();
// var _price = web3.toWei(parseFloat($('#article_price').val() || 0), "ether");
//if((_article_name.trim() == '') || (_price == 0)) {
// nothing to sell
// return false;
// }
App.contracts.OurRentalTestFromClassMay24.deployed().then(function(instance) {
return instance.sellArticle(_description, _beds, _baths, _propaddress, _rental_price, _property_type, _available, _contact_email, {
from: App.account,
gas: 500000
});
}).then(function(result) {
}).catch(function(err) {
console.error(err);
});
},
// listen to events triggered by the contract
listenToEvents: function() {
App.contracts.OurRentalTestFromClassMay24.deployed().then(function(instance) {
instance.LogSellArticle({}, {}).watch(function(error, event) {
if (!error) {
$("#events").append('<li class="list-group-item">' + event.args._name + ' is now for sale</li>');
} else {
console.error(error);
}
App.reloadArticles();
});
instance.LogBuyArticle({}, {}).watch(function(error, event) {
if (!error) {
$("#events").append('<li class="list-group-item">' + event.args._buyer + ' bought ' + event.args._name + '</li>');
} else {
console.error(error);
}
App.reloadArticles();
});
});
},
buyArticle: function() {
event.preventDefault();
// retrieve the article price and data
var _articleId = $(event.target).data('id');
var _price = parseFloat($(event.target).data('value'));
App.contracts.OurRentalTestFromClassMay24.deployed().then(function(instance){
return instance.buyArticle(_articleId, {
from: App.account,
value: web3.toWei(_price, "ether"),
gas: 500000
});
}).catch(function(error) {
console.error(error);
});
}
};
$(function() {
$(window).load(function() {
App.init();
});
});

Razor: button click not fired correctly

I have a view. I want to load it to get all information then click Edit or Delete button to do something. When click Edit button then I hope it goes to another view.
#model Models.CountryLanguagesModel
#{
ViewBag.Title = "Language";
}
<div class="span4 proj-div text-center" data-toggle="modal" data-target="#addLanguageModal">
<u>Add Language</u>
<div><br /> </div>
<table class="table table-bordered table-dark-header table-responsive">
<tr>
<th class="text-center">Language Name</th>
<th class="text-center">Welcome Message</th>
<th></th>
</tr>
#foreach (var item in Model.CountryLanguages)
{
<tr>
<td>#Html.DisplayFor(modelItem => item.LanguageName)</td>
<td>#Html.DisplayFor(modelItem => item.WelcomeMessage)</td>
</tr>
}
</table>
</div>
<div class="container">
<div class="col-md-8 col-md-offset-2">
<button class="btn btn-success" id="editLanguage">Edit</button>
<button class="btn btn-danger" id="deleteLanguage">Delete</button>
</div>
</div>
<div class="modal fade" id="addLanguageModal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3>Add Language</h3>
</div>
<div class="modal-body">
<div class="form-group">
</div>
<div class="form-group">
<div class="left">
<label>Language Name:</label>
</div>
<div class="right">
<input type="text" class="form-control" name="languageName" id="languageName" />
</div>
</div>
<div class="form-group">
<div class="left">
<label>Welcome Messagee:</label>
</div>
<div class="right">
<input type="text" class="form-control" name="welcomeMessage" id="welcomeMessage" />
</div>
</div>
</div>
<div class="modal-footer">
<button class="btn btn-gray" data-dismiss="modal" aria-hidden="true">Close</button>
<button class="btn btn-primary" id="addLanguageBtn">Save</button>
</div>
</div>
</div>
</div>
#section scripts
{
<script type="text/javascript">
$(document).ready(function () {
$("#addLanguageBtn").on("click", function (evt) {
var CountryId = #Model.CountryId;
var languageName = $("#languageName").val();
var welcomeMessage = $("#welcomeMessage").val();
$.post("/Country/AddLanguage", { id: CountryId, languageName: languageName, welcomeMessage: welcomeMessage }, function (data) {
$("#languageName").val("");
$("#welcomeMessage").val("");
$("#addLanguageModal").modal('hide');
});
});
$("#editLanguage").on("click", function (evt) {
var CountryId = #Model.CountryId;
$.post("/Country/LanguageEdit", { id: CountryId }, function () {
});
});
$("deleteLanguage").on("click", function (evt) {
var CountryId = #Model.CountryId;
$.post("/Country/LanguageDelete", { id: CountryId }, function () {
});
});
});
</script>
}
Now the question is when the page loaded, I found the the code reached click event script. It is strange. When I click the button, it doesn't reach the script. But it goes to the controller action method,
[HttpPost]
public ActionResult LanguageEdit(MyModel model)
{
I guess some stupid error to cause the onclick event not fired correctly, but I can't figure it out.
EDIT
public ActionResult LanguageEdit(int id)
{
var model = new CountryLanguageModel();
model.CountryId = id;
model.CountryLanguageQuestion = MyService.GetQuestion(x => x.CountryId == id);
return View(model);
}
Add type='button' attribute to your buttons, if not it will behave as a submit button.
can you change button to a ?
<button class="btn btn-success" id="editLanguage">Edit</button>
to
<a href="/Country/LanguageEdit?id=#Model.CountryId" class="btn btn-success" />
Some more information
if you want to GET somekind of HTML use HTTPGET instead of HTTPPOST.
Use HTTPPOST if you want to send some kind of information, that server should for example save. Use HTTPGET if you want to render some kind of view ( for example get a new view),
Your Action required 'MyModel model' not a id.
As per your comment you may get this behaviour:
why it was fired when page loaded, I didn't click the button at all.
When your javascript code not inside the button click event and instead it is inside any of the other event such document ready or page load ..etc.
So kindly check the event of javascript and surely you will get the direction to solution .
After checked ,If you ,still had the same problem. kindly show us your javascript so that it will be useful to help you further
Thanks
Karthik

Rails 4 Stripe API only working on Refresh

I thought I had the stripe API working. However when I deployed it to Heroku I found that I had to 'refresh' my page or else I would get a javascript in the console when visiting my charging form. The error was
ReferenceError: Stripe is not defined
Now when I refresh the same page this error dissapears and I can continue with my payments. I am not that knowledgeable on JS so that may be the problem I suspect. I have tried adding other stripe libraries but no avail. My code for the form is below:
<h4>Begin your $5.00 a month subscription</h4>
<form action="/users/charge" method="POST" id="payment-form">
<span class="payment-errors"></span>
<div class="row">
<div class="col-md-6">
<label>Card Number</label>
<input class="form-control" type="text" name="Card Number" size="20" data-stripe="number" placeholder="4242424242424242"/>
</div>
</div>
<br />
<div class="row">
<div class="col-xs-2">
<label>CVC</label>
<input type="text" data-stripe="cvc" class="form-control" name="CVC" placeholder="123">
</div>
</div>
<br />
<div class="row">
<div class="col-xs-2">
<label>Expiration</label>
</div>
</div>
<div class="row">
<div class="col-xs-4">
<label>MM</label>
<input type="text" data-stripe="exp-month" class="form-control" name="MM" placeholder="01">
</div>
<div class="col-xs-4">
<label>YYYY</label>
<input type="text" data-stripe="exp-year" class="form-control" name="YYYY" placeholder="2020">
</div>
</div>
<div class="row">
<div class="col-xs-4">
<br/><button class="btn btn-primary" type="submit">Create Subscription</button>
</div>
<div class="col-xs-4">
<br/>
<%= link_to image_tag("big.png"), "https://stripe.com/" %>
</div>
<div class="col-xs-4">
<br/>
<ul>
<li>Reasons To Subscribe:</li>
<li>More tutorials</li>
<li>Personal Contact with A.J.</li>
<li>Request Your own tutorials!</li>
<li>Open Source Help</li>
</ul>
</div>
</div>
<%= token_tag nil %>
</form>
<script src="https://checkout.stripe.com/checkout.js"></script>
<script type="text/javascript" src="https://js.stripe.com/v2/"></script>
<script type="text/javascript">
Stripe.setPublishableKey("<%= ENV['STRIPE_PUBLIC_KEY'] %>");
function stripeResponseHandler(status, response) {
// Grab the form:
var $form = $('#payment-form');
if (response.error) { // Problem!
// Show the errors on the form:
$form.find('.payment-errors').text(response.error.message);
$form.find('.submit').prop('disabled', false); // Re-enable submission
} else { // Token was created!
// Get the token ID:
var token = response.id;
// Insert the token ID into the form so it gets submitted to the server:
$form.append($('<input type="hidden" name="stripeToken">').val(token));
// Submit the form:
$form.get(0).submit();
}
};
$(function() {
var $form = $('#payment-form');
$form.submit(function(event) {
// Disable the submit button to prevent repeated clicks:
$form.find('.submit').prop('disabled', true);
// Request a token from Stripe:
Stripe.card.createToken($form, stripeResponseHandler);
// Prevent the form from being submitted:
return false;
});
});
</script>
This may be due to Turbolink
Change 'data-turbolinks-track' => false infollowing lines in your application.html.haml or application.html.erb file in views/layouts folder.
%meta{:content => "width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no", :name => "viewport"}/
= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track' => 'reload'
= javascript_include_tag 'application', 'data-turbolinks-track' => 'reload'
= csrf_meta_tags
so your code becomes:
%meta{:content => "width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no", :name => "viewport"}/
= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track' => false
= javascript_include_tag 'application', 'data-turbolinks-track' => false
= csrf_meta_tags
I had this right before my checkout page: <a href='/my/checkout'>Purchase Subscription</a>
I had to add data-no-turbolink='true' to the tag:
<a href='/my/checkout' data-no-turbolink='true'>Purchase Subscription</a>

Submit form refresh the page

I have an index.html
<!DOCTYPE html>
<html lang="it">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>League of Legends Straw Poll</title>
<link rel="stylesheet" type="text/css" href="css/bootstrap.css">
<link rel="stylesheet" type="text/css" href="css/styles.css" />
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<h1 class="text-center">Game Straw Poll</h1>
</div>
</div>
<br>
<div class="row">
<div class="col-md-6 col-md-offset-3">
<div class="panel panel-default">
<div class="panel-body">
<!-- FORM -->
<form name="submitForm" id="submitForm" action="process.php" method="post">
<div class="row">
<div class="col-md-12">
<!-- GAME -->
<select class="form-control" id="game-group" name="game" onchange="ChangeBackground();">
<option selected disabled>Select your Game...</option>
<option value="League_of_Legends">League of Legends</option>
<option value="Heartstone">Hearthstone</option>
</select>
</div>
</div>
<br>
<div class="row">
<div class="col-md-12">
<!-- QUESTION -->
<div class="input-group" id="question-group">
<input type="text" class="form-control" name="question" id="question" placeholder="Start typing your question...">
<span class="input-group-addon">
<i class="glyphicon glyphicon-question-sign"></i>
</span>
</div>
</div>
</div>
<br>
<div class="row">
<!-- OPTIONS -->
<div class="form-group form-group-options col-md-12 col-sm-12 col-xs-12">
<div class="input-group input-group-option col-md-12 col-sm-12 col-xs-12" id="options-group">
<input type="text" name="option[]" id="option" class="form-control" placeholder="Options...">
<span class="input-group-addon input-group-addon-remove">
<span class="glyphicon glyphicon-remove"></span>
</span>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<!-- CHOICE -->
<div class="checkbox" id="choice-group">
<label>
<input type="checkbox" id="choice" name="choice" value="Yes">Allow multiple choice
</label>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<button type="submit" class="btn btn-primary btn-lg pull-left" name="submit_button" id="submit_button" data-toggle="modal" data-target="#myModal">Create Poll</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
<div id="myModal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Poll created</h4>
</div>
<div class="modal-body">
<p>Share it: http://gamepoll.net/<?php echo $rand_value; ?></p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Chiudi</button>
<button type="button" class="btn btn-primary">Invia</button>
</div>
</div>
</div>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="js/bootstrap.js"></script>
<script type='text/javascript' src='js/addfield.js'></script>
<script type='text/javascript' src='js/changebackground.js'></script>
<script type='text/javascript' src='magic.js'></script>
</body>
</html>
An AJAX function into a js script
// magic.js
$(document).ready(function() {
// process the form
$('form').submit(function(event) {
$('.form-group').removeClass('has-error'); // remove the error class
$('.help-block').remove(); // remove the error text
// get the form data
// there are many ways to get this data using jQuery (you can use the class or id also)
var formData = {
'game' : $('input[name=game]').val(),
'question' : $('input[name=question]').val(),
'option' : $('input[name=option[]]').val(),
'choice' : $('input[name=choice]').val()
};
// process the form
$.ajax({
type : 'POST', // define the type of HTTP verb we want to use (POST for our form)
url : 'process.php', // the url where we want to POST
data : formData, // our data object
dataType : 'json', // what type of data do we expect back from the server
encode : true
})
// using the done promise callback
.done(function(data) {
// log data to the console so we can see
console.log(data);
// here we will handle errors and validation messages
if ( ! data.success) {
// handle errors for game ---------------
if (data.errors.game) {
$('#game-group').addClass('has-error'); // add the error class to show red input
$('#game-group').append('<div class="help-block">' + data.errors.game + '</div>'); // add the actual error message under our input
}
// handle errors for question ---------------
if (data.errors.question) {
$('#question-group').addClass('has-error'); // add the error class to show red input
$('#question-group').append('<div class="help-block">' + data.errors.question + '</div>'); // add the actual error message under our input
}
// handle errors for option ---------------
if (data.errors.option) {
$('#option-group').addClass('has-error'); // add the error class to show red input
$('#option-group').append('<div class="help-block">' + data.errors.option + '</div>'); // add the actual error message under our input
}
// handle errors for choice ---------------
if (data.errors.choice) {
$('#choice-group').addClass('has-error'); // add the error class to show red input
$('#choice-group').append('<div class="help-block">' + data.errors.choice + '</div>'); // add the actual error message under our input
}
} else {
// ALL GOOD! just show the success message!
$('form').append('<div class="alert alert-success">' + data.message + '</div>');
// usually after form submission, you'll want to redirect
// window.location = '/thank-you'; // redirect a user to another page
}
})
// using the fail promise callback
.fail(function(data) {
// show any errors
// best to remove for production
console.log(data);
});
// stop the form from submitting the normal way and refreshing the page
event.preventDefault();
});
});
And a process.php
<?php
//Include configuration file
include('includes/config.php');
//Define variables
$question=$_POST['question'];
$game=$_POST['game'];
$option=$_POST['option'];
$choice=$_POST['choice'];
//Generate random number
$rand_value=rand();
//Create temporary folder
mkdir($rand_value);
//Copy page of Ask Poll
copy('page.php', $rand_value . '/page.php');
rename($rand_value . '/page.php', $rand_value . '/index.php');
//Add data into database
mysql_connect($db_host, $db_username, $db_password) or die ("Errore di connessione!");
mysql_select_db($db_name) or die ("Impossibile selezionare database!");
$sql1="CREATE TABLE `" . $rand_value . "` (Question VARCHAR(200), Options VARCHAR(200), Choice INT(11))";
mysql_query($sql1) or die ("Impossibile eseguire la query!");
//Count number of Options available
$count=count($option);
for ($i=0; $i<($count-1); $i++)
{
${$sql . $i}="INSERT INTO `" . $rand_value . "` (Question, Options, Choice) VALUES ('$question', '$option[$i]', '$choice')";
mysql_query(${$sql . $i});
}
?>
But when i send the form, the page redirect me to process.php
I don't want that the site refresh the page
EDIT
Werner, I followed your suggestion adding preventDefault but it doesn't work :(
You have an syntax error in your magic.js file. You should start by enabling your console and watch it for errors.
Uncaught Error: Syntax error, unrecognised expression: input[name=option[]]
That is what I could read when pressing the submit button and then Escape just after that to stop the submit.
The problem lies the part where you create your formData. (Which you can actually create a lot easier with http://api.jquery.com/serialize/)
You have a typo on line 15. Notice the extra brackets? You are not supposed to add the brackets even though they are in the name of the field. I recommend you to use the Serialize solution or at least select the fields using their IDs (that's what they are basically for).
$('input[name=option[]]') // Not valid
$('#option') // Better way to select a field
Hope this will get you in the right direction.

Categories

Resources