I am trying to post a form using dojo.xhrPost. Below code works fine in chrome but does not work at all in Firefox. When I say it doesn't work I see that page reloads again and nothing happens. I tried to use dojo.stopEvent(event); but doesn't seem to work in Firefox.
Can you please suggest me what could be my mistake. I feel the issue is more with the form than with xhrPost.
HTML Looks like below:
<div data-dojo-type="dijit/form/Form" data-dojo-id="myform" id="loginform"
encType="multipart/form-data" action="" method="post">
<script type="dojo/method" data-dojo-event="onSubmit">
if(this.validate()){
senddata(); //calling the javascript function
}else{
alert('Form contains invalid data. Please correct first');
return false;
}
return true;
</script>
<table cellspacing="10">
<tr>
<td><label for="name">Username:</label></td>
<td><input type="text" id="username" name="username"
required="true" placeholder="Your UserName" data-dojo-
type="dijit.form.ValidationTextBox"/></td>
</tr>
<tr>
<td><label for="password">Password:</label></td>
<td><input type="password" id="password" name="password"
required="true" placeholder="Your Password"
data-dojotype="dijit.form.ValidationTextBox"/></td>
</tr>
</table>
<div id="response" style="float: right"></div>
<button data-dojo-type="dijit.form.Button" type="submit" name="submitButton"
value="Submit" style="float: right;">Submit</button>
</div>
My Javascript code is below:
function senddata(){
dojo.stopEvent(event);
obj = {};
obj.user_name =dijit.byId("username").get("value");
obj.password =dijit.byId("password").get("value");
var xhrArgs = {
url: "./script/php/validatelogin.php",
postData: obj,
handleAs: "json",
load: function(data){
//alert('success');
if(data.success==true){
window.location = data.message;
dojo.byId("response").innerHTML = "Form posted.";
}else{
dojo.byId("response").innerHTML = "login Failed";
}
},
error: function(error){
console.log("error occured!!!");
dojo.byId("response").innerHTML = "Failed to Post the Form..";
}
};
//alert('starting');
var deferred = dojo.xhrPost(xhrArgs);
//alert('done');
return false;
}
First, change the data-dojo-type into path format. E.g.: dijit/form/ValidationTextBox
Second, fix your typing mistake in password field of data-dojo-type. You entered data-dojotype, missing the - b=in between 'dojo' & 'type'
More information about dojo.byId() & dijit.byId().
Here is the result:
<div data-dojo-type="dijit/form/Form" data-dojo-id="myform" id="loginform" encType="multipart/form-data" action="" method="post">
<script type="dojo/method" data-dojo-event="onSubmit">
if(this.validate()){
senddata(); //calling the javascript function
}else{
alert('Form contains invalid data. Please correct first');
return false;
}
return true;
</script>
<table cellspacing="10">
<tr>
<td><label for="name">Username:</label></td>
<td><input type="text" id="username" name="username" required="true" placeholder="Your UserName" data-dojo-type="dijit/form/ValidationTextBox" /></td>
</tr>
<tr>
<td><label for="password">Password:</label></td>
<td><input type="password" id="password" name="password" required="true" placeholder="Your Password" data-dojo-type="dijit/form/ValidationTextBox" /></td>
</tr>
</table>
<div id="response" style="float: right"></div>
<button data-dojo-type="dijit/form/Button" type="submit" name="submitButton" value="Submit" style="float: right;">Submit</button>
</div>
<script>
function senddata(){
dojo.stopEvent(event);
obj = {};
obj.user_name =dijit.byId("username").get("value");
obj.password =dijit.byId("password").get("value");
var xhrArgs = {
url: "./script/php/validatelogin.php",
postData: obj,
handleAs: "json",
load: function(data){
//alert('success');
if(data.success==true){
window.location = data.message;
dojo.byId("response").innerHTML = "Form posted.";
}else{
dojo.byId("response").innerHTML = "login Failed";
}
},
error: function(error){
console.log("error occured!!!");
dojo.byId("response").innerHTML = "Failed to Post the Form..";
}
};
//alert('starting');
var deferred = dojo.xhrPost(xhrArgs);
//alert('done');
return false;
}
</script>
Related
I've gone through dozens of articles, docs, and stack overflow questions (even the one with a similar intro)regarding the same issues but it still persists.
I've tried this with putting the functions in the .cshtml.cs page and on the .cshtml page, named and unnamed handler names, different framework for sending emails, and adding an empty action field in the form along with other fixes but the issue seems to be that the handler method itself is not firing while the form is submitting. Any and all help is appreciated and please let me know if more information is needed.
My HTML form:
<form method="POST" asp-page-handler="email">
<!-- Name input-->
<div class="form-floating mb-3">
<input class="form-control" name="clientName" type="text" placeholder="Enter your name..." required/>
<label for="name">Full name*</label>
</div>
<!-- Email address input-->
<div class="form-floating mb-3">
<input class="form-control" name="clientEmail" type="email" placeholder="name#example.com" required/>
<label for="email">Email address*</label>
</div>
<!-- Phone number input-->
<div class="form-floating mb-3">
<input class="form-control" name="clientPhone" type="tel" placeholder="(123) 456-7890"/>
<label for="phone">Phone number</label>
</div>
<!-- Message input-->
<div class="form-floating mb-3">
<textarea class="form-control" name="clientMessage" type="text" placeholder="Enter your message here..." style="height: 10rem" required></textarea>
<label for="message">Message*</label>
</div>
<!-- Submit Button-->
<div class="d-grid"><button class="btn btn-primary btn-xl" type="submit" value="submit">Submit</button></div>
</form>
My functions as they are currently:
public void OnPostEmail()
{
var clientEmail = Request.Form["clientEmail"];
var clientName = Request.Form["clientName"];
var clientPhone = Request.Form["clientPhone"];
var clientMessage = Request.Form["clientMessage"];
sendEmail(clientEmail, clientName, clientPhone, clientMessage);
}
public void sendEmail(string clientEmail, string clientName, string clientPhone, string clientMessage)
{
var errorMessage = "";
try
{
// Initialize WebMail helper
WebMail.SmtpServer = "smtp.google.com";
WebMail.SmtpPort = 587;
WebMail.UserName = "***#gmail.com";
WebMail.Password = "MYPASSWORD";
WebMail.From = "***#gmail.com";
WebMail.EnableSsl = true;
// Send email
WebMail.Send(to: clientEmail,
subject: $"Request from: + {clientName}",
body: $"{clientMessage}\nPhone: {clientPhone}\nEmail: {clientEmail}"
);
}
catch (Exception ex)
{
errorMessage = ex.Message;
}
}
I'm having some strange behaviour when using the datepicker. When I load the page, and directly click on the datepicker input, nothing happens. When I click again, nothing happens. But when I click on another input field and then try again the datepicker field, it'll show up.
The issue showed up, after I put the datepicker trigger into a live function, because I have input which will be dynamically generated.
This is my code:
$(".date").on('click', function() {
$(this).datepicker({
dateFormat: "dd.mm.yy",
altField: $(this).closest("td").find(".dateFormated"),
altFormat: "yy-mm-dd"
})
})
Edit: I have seen that live() is deprecated as of 1.7. I therefore switched live() for on(). Didn't solve the issue though.
Whole Html
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="content-type" content="text/html" />
<meta name="author" content="gencyolcu" />
<title>Untitled 1</title>
<link rel="stylesheet" href="http://localhost:8082/ivy/page/designer/ZWM$1/css/cupertino/jquery-ui-1.9.2.custom.css" />
<script type="text/javascript" src="http://localhost:8082/ivy/page/designer/ZWM$1/jquery.min.js"></script>
<script type="text/javascript" src="http://localhost:8082/ivy/page/designer/ZWM$1/js/jquery-ui-1.9.2.custom.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
counter = 0;
$("#addRow").click(function() {
counter++;
rowHtml = '\
<tr class="datarow" id="row' + counter + '">\
<td><input type="text" class="date" /><input type="text" class="dateFormated" /></td>\
<td><input type="text" class="from" /></td>\
<td><input type="text" class="to" /></td>\
<td>\
<select class="type">\
<option value="1">Typ 1</option>\
<option value="2">Typ 2</option>\
</select>\
</td>\
<td class="removeRow" id=' + counter + '>X</td>\
</tr>';
$('#submitButton').before(rowHtml);
})
$(".removeRow").live("click", function() {
id = $(this).attr("id");
$("#row" + id).remove();
})
$("[name=formZeitdaten]").submit(function(i) {
values = "";
$(".datarow").each(function(j) {
tr = $(this);
date = tr.find('td').find('.date').val();
from = tr.find('td').find('.from').val();
to = tr.find('td').find('.to').val();
type = tr.find('td').find('.type').val();
values = values + date + ',' + from + ',' + to + ',' + type + ';';
})
console.log(values);
$("[name=dataset]").val(values);
})
$("#slider").slider({
range: true,
min: 0,
max: 1440,
step: 15,
values: [30, 210],
slide: function(event, ui) {
$(".date").val(ui.values[0] + ":" + ui.values[1]);
}
});
$(".date").on('click', function() {
$(this).datepicker({
dateFormat: "dd.mm.yy",
altField: $(this).closest("td").find(".dateFormated"),
altFormat: "yy-mm-dd"
})
})
});
</script>
</head>
<body>
<span id="test"></span>
<form name="formZeitdaten" method="post">
<table id="zeitdaten">
<tr>
<td>Datum</td>
<td>Von</td>
<td>Bis</td>
<td>Typ</td>
<td id="addRow"><input type="button" value="Hinzufügen" /></td>
</tr>
<tr class="datarow">
<td><input type="text" class="date" /><input type="text" class="dateFormated" /></td>
<td><input type="text" class="from" /></td>
<td><input type="text" class="to" /></td>
<td>
<select class="type">
<option value="1">Typ 1</option>
<option value="2">Typ 2</option>
</select>
</td>
<td></td>
</tr>
<tr id="submitButton">
<td><input type="submit" /></td>
</tr>
</table>
</form>
<div id="slider"></div>
</body>
</html>
In your addRow function, add:
$("#row"+counter+" .date").datepicker({
dateFormat: 'dd-mm-yy',
minDate: 0,
showButtonPanel: true,
showAnim: 'show'
});
after you add the element to the DOM. You can then get rid of the $(".date").on('click',...) statement later.
This should work for you
$('.date').datepicker({
dateFormat: 'dd-mm-yy',
minDate: 0,
showButtonPanel: true,
showAnim: 'show'
});
I have a problem with Google Geocoder API.
I have a form where the user type a full address. When the form is submited, I want to extract the city from this address and put this city in a hidden field.
So here is what I've done...
HTML :
<form id="new_post" name="new_post" method="post" action="" onSubmit="codeAddress()">
<p>
<label for="adresse_de_depart">Adresse de départ</label><br />
<input type="text" id="adresse_de_depart" value="" tabindex="1" size="20" name="adresse_de_depart"/>
</p>
<input type="hidden" id="ville_depart" name="ville_depart" value=""/>
<p align="right">
<input type="submit" value="Publish" tabindex="6" id="submit" name="submit" />
</p>
</form>
JS :
<script>
var geocoder;
$(document).ready(function(){
geocoder = new google.maps.Geocoder();
});
function codeAddress() {
var adresse = document.getElementById("adresse_de_depart").value;
console.log(geocoder);
alert(adresse_de_depart);
geocoder.geocode( { 'address': adresse}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
alert("OK");
document.getElementById("ville_depart").value=results;
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}</script>
The first "alert" works but after the page is reloaded (and the form is submited). But I have no alert related to the geocode method...
Have you got an idea ?
Thanks !
I have a form within a modal that i am trying to validate before the form gets submitted to ajax db etc.
I am trying to validate the form $("#new_request_form").validate({ on the save button. if it validate then submit the form.
Can anybody tell me what i am missing?
Thanks in advance!
$(document).ready(dialogForms);
function dialogForms() {
$('a.menubutton').click(function() {
var a = $(this);
$.get(a.attr('href'),function(resp){
var dialog = $('<div>').attr('id','formDialog').html($(resp).find('form:first').parent('div').html());
$('body').append(dialog);
dialog.find(':submit').hide();
dialog.dialog({
title: a.attr('title') ? a.attr('title') : '',
modal: true,
buttons: {
'Save': function() {
$("#new_request_form").validate({
submitHandler: function(form) {
submitFormWithAjax($(this).find('form'));
$(this).dialog('close');
}
});
},
'Cancel': function() {$(this).dialog('close');}
},
close: function() {$(this).remove();},
width: 600,
height: 500,
show: "fade",
hide: "fade"
});
var $ac_start_date = '<?php echo $ac_end_date ?>',
$ac_start_date_flip = '<?php echo $ac_end_date_flip ?>',
$ac_start_parsed = Date.parse($ac_start_date),
_today = new Date().getTime();
// For Opera and older winXP IE n such
if (isNaN($ac_start_parsed)) {
$ac_start_parsed = Date.parse($ac_start_date_flip);
}
var _aDayinMS = 1000 * 60 * 60 * 24;
// Calculate the difference in milliseconds
var difference_ms = Math.abs($ac_start_parsed - _today);
// Convert back to days and return
var DAY_DIFFERENCE = Math.round(difference_ms/_aDayinMS);
// do initialization here
$("#startdate").datepicker({
dateFormat: 'dd-mm-yy',
changeMonth: true,
changeYear: true,
yearRange: '0:+100',
minDate: '+1d',
maxDate: '+' + (DAY_DIFFERENCE + 1) + 'd'
});
// do initialization here
$("#enddate").datepicker({
dateFormat: 'dd-mm-yy',
changeMonth: true,
changeYear: true,
yearRange: '0:+100',
minDate: '+1d',
maxDate: '+' + (DAY_DIFFERENCE + 1) + 'd'
});
}, 'html');
return false;
});
}
function submitFormWithAjax(form) {
form = $(form);
$.ajax({
url: form.attr('action'),
data: form.serialize(),
type: (form.attr('method')),
dataType: 'script',
success: function(data){
$(this).dialog('close');
// Refresh table
}
});
return false;
}
FORM
<?php
require_once("../config.php");
include_once("scripts/connection.php");
?>
<p class="validateTips">All form fields are required.</p>
<div>
<form id="new_request_form" action="insert_new_request.php" method="POST" class="new_request">
<fieldset>
<legend><p class="subheadertext">Request Holiday</p></legend>
<table width="100%" border="0">
<?php
$username = $USER->firstname.' '.$USER->lastname;
$is_academic_result = mysql_query('SELECT * FROM holiday_entitlement_academic WHERE employee = \'' . $username . '\'');
if($is_academic = mysql_fetch_array($is_academic_result)) {
switch($is_academic['units']) {
case 'days':
echo'<tr>
<td width="150px" valign="middle"><label for="days">Days:</label></td>
<td valign="top">
<select id="days" name="days">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
</td>
</tr>
<tr>
<td width="150px" valign="middle"><label for="startdate">Start Date:</label></td>
<td valign="top"><input type="text" name="startdate" id="startdate" class="required" readonly="readonly"/></td>
</tr>';
break;
case 'hours':
echo'<tr>
<td width="150px" valign="middle"><label for="days">Hours:</label></td>
<td valign="top"><input type="text" name="hours" id="hours" class="required" /></td>
</tr>
<tr>
<td width="150px" valign="middle"><label for="startdate">Start Date:</label></td>
<td valign="top"><input type="text" name="startdate" id="startdate" class="required" readonly="readonly"/></td>
</tr>
<tr>
<td width="150px" valign="middle"><label for="startdate">End Date:</label></td>
<td valign="top"><input type="text" name="enddate" id="enddate" class="required" readonly="readonly"/></td>
</tr>';
break;
default:
break;
}
}
?>
</table>
<input type="hidden" id="acyear" name="acyear" value="<?php echo $academic_start_date; ?>"/>
<input type="hidden" id="user" name="user" value="<?php echo $USER->id; ?>"/>
<input type="hidden" id="employee" name="employee" value="<?php echo $USER->firstname.' '.$USER->lastname; ?>"/>
</fieldset>
</form>
</div>
EDIT - What it does
with the following when you click save it does not do anything, the modal stays up and even if you fill the form it does not do anything:
'Save': function() {
$("#new_request_form").validate({
submitHandler: function(form) {
submitFormWithAjax($(this).find('form'));
$(this).dialog('close');
}
});
},
With the following the form gets submitted and works as expected just no validation:
'Save': function() {
submitFormWithAjax($(this).find('form'));
$(this).dialog('close');
},
I guess when calling submitHandler function, you have passed the wrong selector. $(this) represent the form itself so there is no need to find the form in it.
So Replace this code
submitFormWithAjax($(this).find('form'));
With
submitFormWithAjax($(this));
Or Alternately
submitFormWithAjax($("#new_request_form"));
This will fix you problem.
Hello guys is it possible to have multiple forms on single jsp and also with a single button?
Here is my jsp page where i hava two forms, i know this way it is, it only save the second form.
<html>
<head>
<title>Update General Info</title>
<script type="text/javascript">
function validateForm()
{
var name=document.getElementById("name").value;
var surname=document.getElementById("surname").value;
var email=document.getElementById("email").value;
var amka=document.getElementById("amka").value;
if (name.length == 0)
{
alert("Name must be filled out");
return false;
} else if(surname.length == 0){
alert("Surname must be filled out");
return false;
}else if(email.length == 0){
alert("Email must be filled out");
return false;
}else if(amka.length == 0){
alert("Amka must be filled out");
return false;
}
}
</script>
</head>
<body>
<h1>Update General Info</h1>
<c:if test="${!empty user}">
<c:url var="saveArticleUrl" value="/articles/updateGeneralSave.html" />
<form:form onsubmit="return validateForm()" modelAttribute="user" method="POST" >
<table bgcolor="DBEADC" border=1>
<tr>
<th>Id</th>
<th>Team</th>
<th>Name</th>
<th>Surname</th>
<th>Username</th>
<th>Password</th>
<th>Email</th>
<th>AMKA</th>
<th>Status</th>
<th>Department</th>
</tr>
<tr>
<td><form:input readonly="true" path="id" value="${user.id}"></form:input></td>
<td><form:input readonly="true" path="team" value="${user.team}"></form:input></td>
<td><form:input id="name" path="name" value="${user.name}"></form:input></td>
<td><form:input id="surname" path="surname" value="${user.surname}"></form:input></td>
<td><form:input readonly="true" path="username" value="${user.username}"></form:input></td>
<td><form:input type="password" readonly="true" path="password" value="${user.password}"></form:input></td>
<td><form:input id="email" path="email" value="${user.email}"></form:input></td>
<td><form:input id="amka" path="amka" value="${user.amka}"></form:input></td>
<td><form:input id="status" path="status" value="${user.status}"></form:input></td>
<td><form:select path="department">
<c:forEach items="${departments}" var="dep">
<c:if test="${dep.dep_name==user.department }">
<OPTION selected VALUE="${dep.dep_name}"><c:out value="${dep.dep_name}"/></OPTION>
</c:if>
<c:if test="${dep.dep_name!=user.department }">
<OPTION VALUE="${dep.dep_name}"><c:out value="${dep.dep_name}"/></OPTION>
</c:if>
</c:forEach>
</form:select></td>
</tr>
</table>
</form:form>
</c:if>
<c:if test="${!empty phones}">
<c:url var="saveArticleUrl" value="/articles/updatePhoneSave.html" />
<form:form onsubmit="return validateForm()" modelAttribute="updatePh" method="POST" action="${saveArticleUrl}">
<table bgcolor="DBEADC" border=1>
<tr>
<th>Id</th>
<th>Phone</th>
<th>Mobile</th>
<th>Fax</th>
</tr>
<tr>
<td><form:input readonly="true" path="id" value="${phones.id}"></form:input></td>
<td><form:input id="phone" path="phone" value="${phones.phone}"></form:input></td>
<td><form:input id="mobile" path="mobile" value="${phones.mobile}"></form:input></td>
<td><form:input path="fax" value="${phones.fax}"></form:input></td>
</tr>
</table>
<input type="submit" value="Update" />
</form:form>
</c:if>
</body>
</html>
and the controllers
RequestMapping(value = "updateGeneral" , method = RequestMethod.GET)
public ModelAndView updateGeneral(#ModelAttribute("user") Users user ,#ModelAttribute("updatePh") Phone updatePh, #RequestParam("id")Integer id){
Map<String, Object> model = new HashMap<String, Object>();
model.put("user", articleService.getUser(id));
model.put("departments", articleService.listDepartments());
//twra mpike
model.put("phones", articleService.getPhones(id));
return new ModelAndView("updategeneral",model);
}
//evala akoma ena modelattri
#RequestMapping(value = "updateGeneralSave" , method = RequestMethod.POST)
public ModelAndView updateGeneralSave(#ModelAttribute("user") Users user){
articleService.updateUser(user);
return new ModelAndView("redirect:/articles/listusers.html");
}
#RequestMapping(value = "updatePhoneSave" , method = RequestMethod.POST)
public ModelAndView updatePhonesave(#ModelAttribute("updatePh") Phone updatePh){
articleService.updatePhone(updatePh);
return new ModelAndView("redirect:/articles/listusers.html");
}
You can have multiple forms in a JSP, but you can NOT send both at the same time.
You should mix both forms and both actions, retrieve all information in the action/controller and save phone and user information. Another options would be to use Ajax to send one of the form and send the other as usually.
By the way, your problem has nothing to do with Spring.
yes of courses, you can make your button to submit both your forms. But you have do it with ajax.
You need to loop through the forms on the webpage using document.forms[i] and with each form individually call the submit
Your only option is doing for ajax, you have to realize that if you Controller method will render a page after the first submit your second submit doing by HTTP will never take effect.
function submitForm(form, index){
$.ajax({
dataType: "json",
method: "POST",
url: "your controller url",
data:$('#form').serialize(),
success: function (data) {
if(index > 0){
submitForm(form+=1, index--)
}
}
});
}
You can do following trick like
Instead of sumbit button have only normal button as
<input type="button" value="Update" onClick="submit2forms();"/>
and on click of this button call below javascript method as
<script language="javascript">
function submit2forms() {
document.getElementById("form1").submit();
document.getElementById("form2").submit();
}
</script>