JS-validation doesn't work - javascript

I'm trying to validate the number of seats in a form I already wrote the JSP, provided the servlets. Now I'm trying to do the validation with JS, and I'm doing something wrong.
<script>
window.onload = function() {//zorgt ervoor dat eerst html-document wordt geladen vooraleer functies worden aangesproken
console.log("voor vrijePlaatsen");
function validate_form(e) {
console.log("in validate");
var plaatsen = document.getElementById("plaatsen");
var vrijePlaatsen = document.getElementById("beschikbaar");
console.log(plaatsen.value);
console.log(vrijePlaatsen.value);
if (plaatsen.value === "") {
alert("Gelieve een aantal plaatsen te reserveren");
plaatsen.focus();
e.preventDefault();
}
else if (plaatsen.value < 0) {
alert("Geef een positief aantal plaatsen in");
plaatsen.focus();
e.preventDefault();
}
else if (plaatsen.value > vrijePlaatsen.value) {
alert("U kan slechts " + vrijePlaatsen.value + " plaatsen reserveren./nU probeerde er " + vrijePlaatsen.value + " te reserveren");
plaatsen.focus();
e.preventDefault();
}
else if (isNaN(plaatsen.value)) {
alert("Gelieve een getal in te geven.")
plaatsen.focus();
e.preventDefault();
}
return true;
}
}
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<c:set var="contextPath" value="${pageContext.servletContext.contextPath}"/>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Cultuurhuis - Reservaties</title>
<link rel="stylesheet" href="${contextPath}/CSS/default.css"/>
</head>
<body>
<div id="container">
<div id="titel">
<h1>Het Cultuurhuis: Reserveren</h1>
</div>
<c:url value="/images/reserveren.png" var="imgReservering"/>
<img src="${imgReservering}"/>
<div id="content">
<c:url value="/voorstellingen" var="voorstellingen"/>
voorstellingen
<form method="post" action="${contextPath}/reservaties" >
<p id="voorstelling">Voorstelling:</p>
${voorstelling.titel}<br/>
<p>Uitvoerders: </p>
${voorstelling.uitvoerders}<br/>
<p>Datum: </p>
${voorstelling.datum}<br/>
<p>Prijs:</p>
${voorstelling.prijs}<br/>
<p>Vrije Plaatsen</p>
<p id ="beschikbaar">${voorstelling.vrijePlaatsen}</p><br/>
<br/>
<label>Plaatsen<br/>
<c:choose >
<c:when test="${not empty alGereserveerd}">
<c:set value="${alGereserveerd}" var="ingevuldePlaatsen"/>
</c:when>
<c:otherwise>
<c:set var="ingevuldePlaatsen" value="${param.plaatsen}"/>
</c:otherwise>
</c:choose>
<input id="plaatsen" type="text" name="plaatsen" value="${ingevuldePlaatsen}" autofocus/>
</label>
<input id="submitknop" type="submit" value="reserveren" onclick="return validate_form();" />
<p id="fout"></p>
<!--<span id="fout">${fouten}</span>-->
</form>
</div>
</div>
</body>

Change
<form method="post" action="${contextPath}/reservaties" >
To
<form method="post" action="${contextPath}/reservaties" onsubmit="return validate_form();">
Additionally move your validate_form function out of the onload scope, or use event listeners to attach it to the form within your onload
Also please explain your problem in the future so people don't have to figure it out for themselves :)

There are two problems.
You are trying to call validate_form when the submit button is clicked, but not if the form is submitted through some other means.
validate_form is not a global, so, when you try to call it, you get a reference error.
Bind your event handler to the form's submit when using Javascript while the function is in scope.
document.getElementsByTagName('form')[0].addEventListener('submit', validate_form);
function validate_form(e) {
console.log("in validate");
I'd add an ID to the form to make it easier to select with JavaScript.

Related

how do i make a webhook for the javascript ideal payment from stripe

im kinda new to programming with this advanced stuff but i wanna learn. i hope you can help me to get it working so not when people cancel the payment and still get ther stuff.
i want to know how to do a webhook voor ideal if you have a better way to create the payment is fine asswel
on the index page is the payment form with ofc the javascript included
i want to get a notification for stripe (with the webhook) when the payment comes true, And after that it needs to send de email with a ticker for a store.
index.php
<form id="payment-form" class="betaal">
<div class="weggeven">
<h1>Aantal verkochten cadeau kaarten</h1>
</div>
<div class="aantal">
<p id="aantal"><?php aantal(); ?></p>
</div>
<div class="form-row">
<label for="name">
Name
</label>
<input id="name" name="name" placeholder="Jenny Rosen" required>
</div>
<div class="form-row">
<label for="name">
Email
</label>
<input id="email" name="email" placeholder="test#gmail.com" required>
</div>
<div class="form-row">
<label for="ideal-bank-element">
iDEAL Bank
</label>
<div id="ideal-bank-element">
<!-- A Stripe Element will be inserted here. -->
</div>
</div>
<div class="bedrag">
<p>
Bedrag € <span id="prijs"></span>
</p>
</div>
<div class="info">
<span>U heeft voor de bon: <b class="bon"><?= $_GET['betalen'] ?></b> gekozen</span>
</div>
<button>nu betalen</button>
<!-- Used to display form errors. -->
<div id="error-message" role="alert"></div>
<div class="pedi">
pedicurepraktijkpapendrecht
</div>
</form>
var stripe = Stripe('api key');
// Create an instance of Elements.
var elements = stripe.elements();
var options = {
// Custom styling can be passed to options when creating an Element.
style: {
base: {
// Add your base input styles here. For example:
fontSize: '16px',
color: '#32325d',
padding: '10px 12px',
},
}
}
// Create an instance of the idealBank Element.
var idealBank = elements.create('idealBank', options);
// Add an instance of the idealBank Element into
// the `ideal-bank-element` <div>.
idealBank.mount('#ideal-bank-element');
idealBank.on('change', function(event) {
var bank = event.value;
// Perform any additional logic here...
});
// Create a source or display an error when the form is submitted.
var form = document.getElementById('payment-form');
form.addEventListener('submit', function(event) {
event.preventDefault();
var randNo = Math.floor(Math.random() * 100) + 2 + "" + new Date().getTime() + Math.floor(Math.random() * 100) + 2 + (Math.random().toString(36).replace(/[^a-zA-Z]+/g, '').substr(0, 5));
var email = document.querySelector('input[name="email"]').value;
var sourceData = {
type: 'ideal',
amount: price,
currency: 'eur',
owner: {
name: document.querySelector('input[name="name"]').value,
email: document.querySelector('input[name="email"]').value,
},
// Specify the URL to which the customer should be redirected
// after paying.
redirect: {
return_url: 'https://url/stripe/cadeau.php?gelukt=jaa' + '&email=' + email + '&id=' + randNo + '&bon=' + bon,
},
};
// Call `stripe.createSource` with the idealBank Element and
// additional options.
stripe.createSource(idealBank, sourceData).then(function(result) {
if (result.error) {
// Inform the customer that there was an error.
var errorElement = document.getElementById('error-message');
errorElement.textContent = error.message;
} else {
// Redirect the customer to the authorization URL.
stripeSourceHandler(result.source);
}
});
});
function stripeSourceHandler(source) {
// Redirect the customer to the authorization URL.
document.location.href = source.redirect.url;
}
on the fetch.php wil receive the stuff from the payment (email, name, ect) and insert it in a database
fetch.php
if (isset($_GET['gelukt'], $_GET['email'], $_GET['id'])) {
$input = #file_get_contents('php://input');
$event_json = json_decode($input);
if ($event_json->type == 'source.chargeable') {
$aankoop_id = $_GET['id'];
$email = $_GET['email'];
$bon = $_GET['bon'];
$select_stmt = $db->prepare('SELECT * FROM cadeau WHERE aankoop_id =?'); //sql select query
$select_stmt->execute([$aankoop_id]);
$aankoopcheck = $select_stmt->fetch();
unset($select_stmt);
if ($aankoopcheck) {
// email found
echo"<h1 class='gestuurd'>De email is al verstuurd!</h1>";
} else {
$gebruikt = "nee";
$sql = "INSERT INTO `cadeau` (`aankoop_id`, `gebruikt`, `bon`) VALUES (?,?,?)";
$stmt= $db->prepare($sql);
$stmt->execute([$aankoop_id, $gebruikt, $bon]);
unset($stmt);
$sender = 'info#pedicurepraktijkpapendrecht.nl';
$subject = "Pedicurepraktijkpapenrecht tegoedbon";
$message = "Bedankt voor uw bestelling.\r\n U kunt hem download via deze link: https://www.pedicurepraktijkpapendrecht.nl/stripe/download.php?email=" . $email . "&id=" . $aankoop_id . "&bon=" . $bon;
$headers = 'From:' . $sender;
if (mail($email, $subject, $message, $headers))
{
}
else
{
}
}
}
}
on the cadeau.php is kinda the payment complete page were the email will sent from
cadeau.php
<?php
include('fetch.php');
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
<script src="https://js.stripe.com/v3/"></script>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"
integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ=" crossorigin="anonymous"></script>
<link rel="stylesheet" href="style.css">
<title>Email versturen naar uw email!</title>
</head>
<body>
<div class="form-row">
<h1>Bedankt voor het kopen van een tegoedbon!</h1>
<p>Uw tegoedbon word gestuurd naar uw email!</p>
<div class="flex">
<a href="https://www.pedicurepraktijkpapendrecht.nl/"
class="btn text-center margin-right max-width">Naar de
website</a>
Nog een tegoedbon kopen?
</div>
</div>
</body>
</html>

ajax jquery is not working

I am trying to submit the login request using Jquery Ajax. But the form is not submitting. I am tried to find the issue but can not. the code is vey simple but as I have started learning javascript so I am failing to find the problem in my code. Below is the code Please find the problem with it......
$(function() {
//get form by id
var form = $('#login_form');
//get message container by is
var message = $('#message');
//prevent default on form submit
$(form).submit(function(event) {
event.preventDefault();
//serialize form data
var form_data = $(form).serialize();
$.ajax({
type: 'post',
url: $(form).attr('action'),
data: form_data
}).done(function(response) {
//set the class of message container to success
$(message).removeClass('error');
$(message).addClass('success');
//put data received from server
$(message).html(response);
//clear form
$('#email').val('');
$('#password').val('');
}).fail(function(data) {
//set the class of message container to error
$(message).removeClass('success');
$(message).addClass('error');
//put the error message
if (data.responseText !== '') {
$(message).html(data.responseText);
} else {
$(message).text('Sorry...! an unexpected error has occured...!');
}
});
});
});
<html>
<head>
<meta charset="UTF-8">
<title>Ajax Practice</title>
<link href="assets/css.css" rel="stylesheet" type="text/css" />
<script src="assets/jquery.js" type="text/javascript"></script>
<script src="assets/ajax_code.js" type="text/javascript"></script>
</head>
<body>
<div class="login_form_div">
<form action="login.php" method="POST" name="login_form" id="login_form" class="login_form">
<div class="label">
<label>Email:</label>
</div>
<div class="form_input">
<input type="text" name="email" id="email">
</div>
<div class="label">
<label>Password:</label>
</div>
<div class="form_input">
<input type="password" name="password" id="password">
</div>
<div class="form_input">
<button type="submit" name="submit_form" id="submit_form">Login</button>
</div>
</form>
<span class="message1 error success" id="message">
</span>
</div>
</body>
</html>
your html and javascript is working perfectly.
can you post your php code?.
otherwise try put this code in your login.php file:
<?php
echo "form submitted";
?>
If you are using js fiddle then import the jquery js file on the dropdown on the left side of the panel.
$(function () {
//get form by id
var form = $('#login_form');
//get message container by is
var message = $('#message');
//prevent default on form submit
$(form).submit(function (event) {
event.preventDefault();
//serialize form data
var form_data = $(form).serialize();
$.ajax({
type: 'post',
url: $(form).attr('action'),
data: form_data
}).done(function (response) {
//set the class of message container to success
$(message).removeClass('error');
$(message).addClass('success');
//put data received from server
$(message).html(response);
//clear form
$('#email').val('');
$('#password').val('');
}).fail(function (data) {
//set the class of message container to error
$(message).removeClass('success');
$(message).addClass('error');
//put the error message
if (data.responseText !== '') {
$(message).html(data.responseText);
} else {
$(message).text('Sorry...! an unexpected error has occured...!');
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head>
<meta charset="UTF-8">
<title>Ajax Practice</title>
<link href="assets/css.css" rel="stylesheet" type="text/css"/>
<script src="assets/jquery.js" type="text/javascript"></script>
<script src="assets/ajax_code.js" type="text/javascript"></script>
</head>
<body>
<div class="login_form_div">
<form action="login.php" method="POST" name="login_form" id="login_form" class="login_form">
<div class="label">
<label>Email:</label>
</div>
<div class="form_input">
<input type="text" name="email" id="email">
</div>
<div class="label">
<label>Password:</label>
</div>
<div class="form_input">
<input type="password" name="password" id="password">
</div>
<div class="form_input">
<button type="submit" name="submit_form" id="submit_form">Login</button>
</div>
</form>
<span class="message1 error success" id="message">
</span>
</div>
</body>
</html>
Actually the problem was here. as the default form submission is prevented through javascript and I was looking for the message.
if (isset($_POST['submit_form'])) {
$email = mysqli_real_escape_string($_POST['email']);
$password = mysqli_real_escape_string($_POST['password']);
if (!empty($email) && !empty($password)) {
echo "Login Must be Successful...!";
} else {
echo "Login Failed....!";
}
}

Update database from bootstrap modal using AJAX

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");
}
});
});
});

Form submit with JavaScript

I'm having issues running my code can any one verifiy it and tell me why it's not working properly?. My javascript doesn't seems to be working fine and the best that I got was the first vars to display. I'm really new to javascript thought.
<!DOCTYPE html>
<html>
<head>
<title> Template Suivi Client </title>
<link rel="icon" href="icone.ico" type="image/x-icon">
<link rel="stylesheet" href="aidememoire.css">
<script>
function myFunction {
alert();
var compte = form.inputcompte.value;
var nom = form.inputnom.value;
var telephone = form.inputtelephone.value;
var quand = form.inputdate.value;
var hdebut = form.inputheuredebut.value;
var hfin = form.inputheurefin.value;
var info = form.inputdescription.value;
document.getElementById("displaycompte").innerHTML = ("Numéro de Compte Client: " + compte);
document.getElementById("displaynom").innerHTML = ("Nom du Client : " + nom);
document.getElementbyId("displaytelephone").innerHTML = ("Numéro de téléphone : ");
document.getElementbyId("displayquand").innerHTML =("Date :" + quand);
document.getElementbyId("displayheured").innerHTML = ("Heure de début : " + hdebut);
document.getElementById("displayheuref").innerHTML = ("Heure de fin: " +hfin);
document.getElementById("displaydescription").innerHTML =("Déscription :" + info);
}
</script>
</head>
<body>
<h2 style="text-align: Center">
Template Suivi Client
</h2>
<form method="get">
Numéro de Compte Client :
<input type="text" name="inputcompte">
<br><br>
Nom du Client :
<input type="text" name="inputnom">
<br><br>
Numéro de téléphone :
<input type="text" name="inputtelephone">
<br><br>
Date :
<input type="date" name="inputdate">
<br><br>
Heure de début :
<input type="time" name="inputheuredebut">
<br><br>
Heure de fin :
<input type="time" name="inputheurefin">
<br><br>
Description du problème :
<input type="text" name="inputdescription">
<br><br>
<button type="button" onclick="myFunction(from.here)"> Soummettre </button>
</form>
<br><br><br>
<p id="displayfinal"> Produit final s'affichera ici </p>
<p id="displaycompte">
</p>
<p id="displaynom">
</p>
<p id="displaytelephone">
</p>
<p id="displayquand">
</p>
<p id="displayheured">
</p>
<p id="displayheuref">
</p>
<p id="displaydescription">
</p>
</body>
</html>`
You are using a variable form that is not defined anywhere.
You can sent the reference to the form from the button:
onclick="myFunction(this.form)"
Catch the parameter in the function:
function myFunction(form) {
try giving the form an id, like <form id="abc" method="GET">...</form>
then use $("#abc").off('submit'); (after the end of the form)
The info that I got from the console [ Uncaught TypeError: Cannot read property 'inputcompte' of undefined ] . It happens to all my variables

jQuery not hiding elements

Here's my code, what I'm trying to do is have javascript check a form and then submit it to a PHP script via AJAX that will log the user in.
<!DOCTYPE html>
<html>
<head>
<title>RPEMS: Login</title>
<link rel="stylesheet" type="text/css" href="../main.css"></link>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
<script type='text/javacript'>
$(function()
{
$('.error').hide();
$('.button').click(function()
{
$('.error').hide();
var filter=/^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
var email = $('input#email').val();
var pass = $('input#pass').val();
var err = false;
if (!email)
{
$('label#emErr').show();
$('input#email').focus();
err = true;
}
if (!filter.test(email))
{
$('label#emValErr').show();
$('input#email').focus();
err = true;
}
if (!pass)
{
$('label#passErr').show();
$('input#pass').focus();
err = true;
}
if (err) return false;
var dataString = 'email=' + email + '&pass=' + pass;
$.ajax({
type: "POST",
url: "log.php",
data: dataString,
success: function(result)
{
if (result.success == true) window.location('../');
else $('p#phpErr).html(result.message).show();
}});
}
});
</script>
</head>
<body>
<div id="header">
<img id="logo" src="../img/logo.png"></img>
<ul id="navBar">
<li class="navLink">
Home
</li>
<li class="navLink">
About/Contact Us
</li>
<li class="navLink">
Calendar
</li>
<li class="navLink">
Login
</li>
</ul>
</div>
<form method='post' action=''>
<fieldset>
<label for='email'>Email: </label>
<input name='email' id='email' type='text'></input>
<br class='error'></br>
<label for='email' class='error' id='emErr'>This field is required</label>
<label for='email' class='error' id='emValErr'>Invalid email adress</label>
<br class='error'></br>
<label for='pass'>Password: </label>
<input name='pass' id='pass' type='password'></input>
<br></br>
<label for='pass' class='error' id='passErr'>This field is required</label>
<br class='error'></br>
<p class='error' id='phpErr'></p>
<input type='submit' name='submit' id='submit_btn' value='Submit'></input>
</fieldset>
</form>
Sadly when I load the page though, the errors aren't hidden, any idea why?
You have a Uncaught SyntaxError: Unexpected token ) in your code. Please make sure you are always checking your console in the browser. See jsfiddle
Here is your working jsfiddle. You are missing a single quote in your line else $('p#phpErr').html(result.message).show(); as well as a closing ); before your document.ready
Please always check your console as this will help you out with errors like this... If you dont know how to use the console. Check this out
you have illegal MIME-type for your script (missing s)
<script type='text/javacript'>
That is why browser even does not attempt to execute it
Change to correct type="text/javascript"
Also at last lines of your script there is several syntax errors, fix to this:
else $('p#phpErr').html(result.message).show(); //missing quote here
}});
}); //missing ) here
});

Categories

Resources