I've create a form using jQuery and I want to submit it into my SQL SERVER Database by AJAX. but It won't submit, I don't know where the problems comes. I create this site with ASP.
Here is the javascript to submit:
$("#reg_tr_new").click(function(){
$("#refresh_tr").submit();
});
$("#refresh_tr").validate({
debug: false,
rules: {
deskripsi: "required"
},
messages: {
deskripsi: {
required: 'Deskripsi harus diisi'
}
},
success: "valid",
submitHandler: function(form) {
$("#right-container").hide();
$("#add_no").show();
.post('trx_menu/queries/svTR_.asp', $("#refresh_tr").serialize(), function(data) {
$('#refresh_tr_show').html(data);
});
}
});
Here is the code in trx_menu/queries/svTR_.asp:
<%
noTrx=request.form("noTrx")
deskripsi=request.form("deskripsi")
from=request.form("from")
tos=request.form("tos")
user_input=Session("ss_ckduser")
BankTrx=request.form("BankTrx")
Dim tgl_inpt
tgl_inpt=Now
strsql="select count(*)+1 as idtrbaru from "& dbweb &".dbo.trmitrareghd"
set qdata = conn.execute(strsql)
idbaru = qdata("idtrbaru")
strsql="insert into "& dbweb &".dbo.trmitrareghd values('"& idbaru &"','"& noTrx &"','"&BankTrx&"','"& deskripsi &"','"&date()&"','"&date()&"','0','"& user_input &"','"& tgl_inpt &"')"
set qdata = conn.execute(strsql)
'response.write strsql
%>
You have the validation plugin debug option set to true which blocks form submittal while you ...debug!
You are also missing a $ before post
.post('trx_menu/queries/svTR_.asp'......
Should be:
$.post('trx_menu/queries/svTR_.asp'......
Use a browser console to check script and syntax errors as well as to inspect the request itself.
Related
Currently I am doing laravel and my submit somehow takes a long time loading (for like 5 seconds) because I am sending an email
I would like to add a loader while its still submitting just like in ajax, but I am not using ajax for this. I used a form submit here
index.blade.php
<form id="form-contact" name="form-contact" action="{{route('inquiries.submit')}}" method="post" enctype="multipart/form-data">
// some fields
</form>
Route
Route::post('/contact/inquiries', 'ApiController#contactForm')->name('inquiries.submit');
Controller
public function contactForm(Request $request)
{
$data['fname'] = $request->fname;
$data['lname'] = $request->lname;
$data['body'] = $request->body;
$data['recipient_email'] = $request->email;
$data['type'] = 'Inquiry';
//some email sending code
Session::put('inquirySuccess', 'Task successfully added!');
$this->emailSent->create($data);
return redirect()->back();
}
inquiry.js
angular.module('app').controller('inquiryController', function($scope, $http, $window) {
if ($('#inquiry-success').length) {
swal({
title: "Inquiry Sent!",
text: "",
type: "success",
showCancelButton: false,
confirmButtonColor: '#DD6B55',
confirmButtonText: 'OK',
})
}
});
How do I add loader while until the submission is completed? I am using laravel 1.4
You will not be able to do that without ajax call. Because if you submit a form, you are gone from the current page. So make the form submission Ajaxify and show a loader until you get a response from server.
This is probably pretty strange but I have a form page with various elements that are being checked for validation when I hit submit. Unfortunately I also have a management side of the page that performs its own Ajax actions.
One of these items has a select list that when I select an option it turns green. I don't really need/want the green validation on this select list as it isn't tied to my postback action at all.
Any ideas on how to turn it off with jQuery? (I'm currently just using $("#form").validate({ ... ...}) to validate my other fields and I think it is taking over for this element too)
Current Validation:
$(function () {
// Validation
$("#edit-opp-prod-form").validate({
// Rules for form validation
rules: {
Opportunity: {
required: true
},
CommissionAmount: {
required: true,
currency: ["", false]
}
},
// Messages for form validation
messages: {
Opportunity: {
required: "An Opportunity name is required."
},
ComissionAmount: {
required: "A Commission Amount must be set."
}
},
// Do not change code below
errorPlacement: function (error, element) {
error.insertAfter(element.parent());
}
});
});
The Select List I don't want to be validated,
<section class="col col-5">
<div>
#Html.Label("ProductID", "Products", new { #class = "label" })
#Html.Action("ProductSelectList", "Products", new { unmappedProducts = true})
</div>
</section>
This produces this when I inspect,
<select id=ProductID" name="ProductID">Products</label>
<option value="...">...</option>
...
<option value="...">...</option>
</select>
How do you create a simple, custom rule using the jQuery Validate plugin (using addMethod) that doesn't use a regex?
For example, what function would create a rule that validates only if at least one of a group of checkboxes is checked?
You can create a simple rule by doing something like this:
jQuery.validator.addMethod("greaterThanZero", function(value, element) {
return this.optional(element) || (parseFloat(value) > 0);
}, "* Amount must be greater than zero");
And then applying this like so:
$('validatorElement').validate({
rules : {
amount : { greaterThanZero : true }
}
});
Just change the contents of the 'addMethod' to validate your checkboxes.
$(document).ready(function(){
var response;
$.validator.addMethod(
"uniqueUserName",
function(value, element) {
$.ajax({
type: "POST",
url: "http://"+location.host+"/checkUser.php",
data: "checkUsername="+value,
dataType:"html",
success: function(msg)
{
//If username exists, set response to true
response = ( msg == 'true' ) ? true : false;
}
});
return response;
},
"Username is Already Taken"
);
$("#regFormPart1").validate({
username: {
required: true,
minlength: 8,
uniqueUserName: true
},
messages: {
username: {
required: "Username is required",
minlength: "Username must be at least 8 characters",
uniqueUserName: "This Username is taken already"
}
}
});
});
// add a method. calls one built-in method, too.
jQuery.validator.addMethod("optdate", function(value, element) {
return jQuery.validator.methods['date'].call(
this,value,element
)||value==("0000/00/00");
}, "Please enter a valid date."
);
// connect it to a css class
jQuery.validator.addClassRules({
optdate : { optdate : true }
});
Custom Rule and data attribute
You are able to create a custom rule and attach it to an element using the data attribute using the syntax data-rule-rulename="true";
So to check if at least one of a group of checkboxes is checked:
data-rule-oneormorechecked
<input type="checkbox" name="colours[]" value="red" data-rule-oneormorechecked="true" />
addMethod
$.validator.addMethod("oneormorechecked", function(value, element) {
return $('input[name="' + element.name + '"]:checked').length > 0;
}, "Atleast 1 must be selected");
And you can also override the message of a rule (ie: Atleast 1 must be selected) by using the syntax data-msg-rulename="my new message".
NOTE
If you use the data-rule-rulename method then you will need to make sure the rule name is all lowercase. This is because the jQuery validation function dataRules applies .toLowerCase() to compare and the HTML5 spec does not allow uppercase.
Working Example
$.validator.addMethod("oneormorechecked", function(value, element) {
return $('input[name="' + element.name + '"]:checked').length > 0;
}, "Atleast 1 must be selected");
$('.validate').validate();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.14.0/jquery.validate.min.js"></script>
<form class="validate">
red<input type="checkbox" name="colours[]" value="red" data-rule-oneormorechecked="true" data-msg-oneormorechecked="Check one or more!" /><br/>
blue<input type="checkbox" name="colours[]" value="blue" /><br/>
green<input type="checkbox" name="colours[]" value="green" /><br/>
<input type="submit" value="submit"/>
</form>
Thanks, it worked!
Here's the final code:
$.validator.addMethod("greaterThanZero", function(value, element) {
var the_list_array = $("#some_form .super_item:checked");
return the_list_array.length > 0;
}, "* Please check at least one check box");
You can add a custom rule like this:
$.validator.addMethod(
'booleanRequired',
function (value, element, requiredValue) {
return value === requiredValue;
},
'Please check your input.'
);
And add it as a rule like this:
PhoneToggle: {
booleanRequired: 'on'
}
For this case: user signup form, user must choose a username that is not taken.
This means we have to create a customized validation rule, which will send async http request with remote server.
create a input element in your html:
<input name="user_name" type="text" >
declare your form validation rules:
$("form").validate({
rules: {
'user_name': {
// here jquery validate will start a GET request, to
// /interface/users/is_username_valid?user_name=<input_value>
// the response should be "raw text", with content "true" or "false" only
remote: '/interface/users/is_username_valid'
},
},
the remote code should be like:
class Interface::UsersController < ActionController::Base
def is_username_valid
render :text => !User.exists?(:user_name => params[:user_name])
end
end
Step 1 Included the cdn like
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>
Step 2 Code Like
$(document).ready(function(){
$("#submit").click(function () {
$('#myform').validate({ // initialize the plugin
rules: {
id: {
required: true,
email: true
},
password: {
required: true,
minlength: 1
}
},
messages: {
id: {
required: "Enter Email Id"
},
password: {
required: "Enter Email Password"
}
},
submitHandler: function (form) { // for demo
alert('valid form submitted'); // for demo
return false; // for demo
}
});
}):
});
I am trying to submit an aria template form http://ariatemplates.com/,the submission is done to a Spring MVC controller/servlet.
The form is getting submitted all right but i am not able to get the values of the aria elements like date picker,text box etc in the controller.
Request.getParameter is of no use.
Any Help will be appreciated.
Here is my sample tpl file,js file and the Spring Controller.
TPL File
{Template {
$classpath:'view.Turnover',
$hasScript : true
}}
{macro main()}
<form action="test.do" method="POST" id="turnoverform">
<div style="float:left;padding-top: 3em;padding-bottom: 3em;padding-right: 3em;">
{#aria:Div {
sclass : "basic",
width : 740,
height : 300
}}
<p style="font-family:Arial,Helvetica,sans-serif;font-size: medium;">Create Turnover Report</p>
<hr />
{#aria:DatePicker {
label: " begin date:",
labelWidth:190,
width:330,
helptext:"Type date or select",
}/}
{#aria:DatePicker {
margins:"x x x 20",
label: "end date:",
labelWidth:190,
helptext:"Type date or select",
width:330,
}/}
<br/>
<br/>
<br/>
{#aria:TextField {
label : "User id",
labelPos : "left",
helptext : "ID",
width : 250,
block : true,
labelWidth : 80,
bind : {
"value" : {
inside : data,
to : 'value' }
}
}/}
<br />
{/#aria:Div}
<br />
{#aria:IconButton {
icon: "std:confirm",
label:"Create",
width : 300,
tooltip : "Click on this to create a Report",
block: true,
onclick : {
fn : buttonClick
}
} /}
</div>
</form>
{/macro}
{/Template}
Javascript File :
Aria.tplScriptDefinition({
$classpath : "view.TurnoverScript",
$prototype : {
/**
* Callback for the click event on the first button.
* #param {aria.DomEvent} evt Click event
*/
buttonClick : function (evt) {
aria.core.IO.asyncFormSubmit({
formId : "turnoverform",
callback : {
fn : this.onSuccess,
onerror : this.onError,
scope : this
}
});
},
onSuccess : function (evt, args) {
alert("The Template has been created");
//this.$json.setValue(["view:Dialog"], "dialogOpen", true);
},
onError : function (evt, args) {
alert("The Template has not been created due to some Error");
}
}
});
in Aria Templates you don't work normally with DOM elements but with the data model.
The way to achieve what you want is to bind those values to the datamodel using the bind property
{#aria:DatePicker {
label: " begin date:",
labelWidth:190,
width:330,
helptext:"Type date or select",
bind : {
value : {
inside : data,
to : "begin_date"
}
}
}/}
Your datamodel would now contain those values, try to modify those values and see the content of this.data in your template script.
To submit the data you have two options,
Template Script through aria.core.Io.asyncRequest (or maybe the RequestMgr, depending on your application complexity).
This method takes a data string that in case of POST requests is the message body. It has to be a string so you can use aria.utils.json.JsonSerializer.serialize() to convert your datamodel into a string.
aria.utils.json.JsonSerializer.serialize(this.data, config)
In the previous snippet of code config is optional, if provided it should match this bean.
Module controller through submitJsonRequest
The good thing about using a controller is that you separate the logic of connecting to a server from the template and that you can send directly an object as data, serialization is done internally.
The drawback is that you'll probably have to configure your UrlService to convert actions to actual URL. Few more info here
Ok this is driving me crazy. I have a user account page. Where you have the option to change your password. I want a conditional jquery validation that if the user types in a new password in the new password box the box that confirms the password as well as the box that asks for the old password is turned into a required element. here is my ragtag code so far:
$("#aspnetForm").validate({
rules: {
<%=CurrentPass.UniqueID %>: {
required: <%=NewPass1.UniqueID %>:specified}
<%=NewPass2.UniqueID %>: {
required: <%=NewPass1.UniqueID %>:specified}
}, messages:{}
});
Just to clear something up. I am using :specified because if the filed is filled. Maybe some other condition?
I think you want to use equalTo for the confirmation password, with the current password required if the new password has data in it.
$('form').validate({
rules: {
<%= CurrentPass.UniqueID %>: {
required: '#<%= NewPass1.ClientID %>:filled'
},
<%= NewPass2.UniqueID %>: {
equalTo: '#<%= NewPass1.ClientID %>'
}
}
});
Those selectors need to be strings using :filled (unless :specified is a custom selector you made) and found by ID instead of name, like this:
$("#aspnetForm").validate({
rules: {
<%=CurrentPass.UniqueID %>:{
required: "#<%=NewPass1.ClientID %>:filled"}
<%=NewPass2.UniqueID %>:{
required: "#<%=NewPass1.ClientID %>:filled"}
}, messages:{}
});
});