[UPDATED]
I am not sure how to add a custom (html) message to my async knockout validator.
Below is a simple form. You can see that there is already some isModified and isValid validation in-place, but it is not async. (I am not sure if this complicates or simplifies the solution.)
<form
method="post"
action="Registration()"
novalidate
data-bind="submit: onRegister">
<div
class="input-wrapper email"
data-bind="
validationOptions: {
messageTemplate: 'emailCollisionTemplate'
},
validationElement: EmailAddress,
css: { 'validation-success': EmailAddress.isModified() && EmailAddress.isValid() }">
<input
type="email"
id="registerModalEmail"
data-bind="
value: EmailAddress,
ariaInvalid: EmailAddress"
aria-describedby="email-address-error"
required />
</div>
<div
class="validation-error-message"
id="email-address-error"
data-bind="validationMessage: EmailAddress">
</div>
</form>
<script type="text/html" id="emailCollisionTemplate">
<span>This email is already registered. Please sign in.
</span>
</script>
And then some js:
self.EmailAddress = ko.observable().extend({
required: {
params: true,
message: 'required'
)
},
pattern: {
params: '#',
message: 'match'
)
},
validation: {
async: true,
validator: function (val, parms, callback) {
$.ajax({
url: 'myUrl/isEmailAllowed',
data: { 'EmailAddress': val },
type: 'POST',
success: function (results) {
if (results) {
callback(true);
}
},
error: function (xhr) {
callback(false);
}
});
}
}
});
(isModified and isValid is handled elsewhere, so I have not included it.)
How do I configure the messageTemplate to show? I've looked at examples, but none of them seem to match what I'm doing here. I've put the validationOptions into the data-bind like it seems to say, but that's not working.
I should point out two confounding aspects here:
There are other validators on this same field (i.e.required and pattern)
There are other fields in this form with validation. (The configuration object says the messageTemplate should be 'id of the script that you want to use for all your validation messages'. I only want it for this one field.)
Related
I'm trying to send multiple selected options to my controller but i can't
Code
route
Route::post('/spacssendto/{id}', 'ProductController#spacssendto')->name('spacssendto');
ajax
$("body").on("click", ".sendspacsdatato", function(e){
e.preventDefault();
var id = $("#product_id").val();
$.ajax({
type: "post",
url: '{{ url('admin/spacssendto') }}/'+encodeURI(id),
data: {
'_token': $('input[name=_token]').val(),
'product_id': $('#product_id').val(),
'subspecification_id': $('.subspecifications').val(),
},
success: function (data) {
alert(data);
},
error: function (data) {
alert(data);
}
});
});
controller
public function spacssendto(Request $request, $id) {
dd($request->all());
}
my form (output)
<form method="POST" action="http://sieffgsa.pp/admin/products/15" accept-charset="UTF-8">
<input name="_token" value="DLrcOa0eOm90e4aaGSYp2uCeiuKtbGCT9fCOUP16" type="hidden">
<input name="product_id" id="product_id" value="15" type="hidden">
<div class="col-md-4">ram</div>
<div class="col-md-6">
<select class="subspecifications form-control tagsselector" id="subspecifications" name="subspecifications[]" multiple="multiple">
<option value="3">2gig</option>
<option value="4">4gig</option>
</select>
</div>
<div class="col-md-2">
<label for="">Actions</label><br>
<button type="button" id="sendspacsdatato" class=" sendspacsdatato btn btn-xs btn-success">Save</button>
</div>
</form>
PS: This form printed by Ajax in my view so it means there is several
more forms involved (the same way) that's why i mostly used classes
and not id's. Yet when I hit save button I will get 3 times repeat in
network (if i have 3 form)
Errors
Error 500 in network
dd result:
array:3 [
"_token" => "DLrcOa0eOm90e4aaGSYp2uCeiuKtbGCT9fCOUP16"
"product_id" => "15"
"subspecification_id" => null
]
Question
How can I pass my multiple options (selected) to controller?
UPDATE
Thanks to Seva Kalashnikov I fixed the problem just for helping others I'll publish final results here so you can have full code, hope it helps.
javascript
$(document).ready(function() {
$("body").on("click", ".sendspacsdatato", function(e){
var form = $(this).closest('form');
var id = form.find('input[name="product_id"]').val();
// e.preventDefault();
$.ajax({
type: "post",
url: '{{ url('admin/spacssendto') }}',
data: {
'_token': $('input[name=_token]').val(),
'product_id': id,
'subspecifications': $(this).closest('form').find('select.subspecifications').val()
},
success: function (data) {
alert('Specifications added successfully.').fadeIn().delay(6000).fadeOut();
},
error: function (data) {
console.log('Error!');
}
});
});
});
controller
public function spacssendto(Request $request) {
$this->validate($request, array(
'product_id' => 'required',
'subspecifications' => 'required',
));
$product = Product::find($request->product_id);
$product->subspecifications()->sync($request->subspecifications, false);
}
You need to get select with css class subspecifications inside the same form element
'subspecification_id': $(this).closest('form').find('select.subspecifications').val()
Try this code:
$('.sendspacsdatato').click(function() {
var form = $(this).closest('form');
var id = form.find('input[name="product_id"]').val();
$.ajax({
type: "post",
url: '{{ url('admin/spacssendto') }}/'+encodeURI(id),
data: {
'_token': form.find('input[name=_token]').val(),
'product_id': id,
'subspecification_id': form.find('select.subspecifications').val(),
},
success: function (data) {
alert(data);
},
error: function (data) {
alert(data);
}
});
});
I'm trying to add a delete-button to my edit-form but have not found anything that works. Suggestions I've seen, is using AJAX, but I don't know how to make it.
I don't like to make another form below the existing one for "update" but it looks impossible to have the delete-button to the right of the update-button.
Any one having an idea...?
I tested this:
$( document ).ready( function() {
$('#delete_prod').on('click',function(event) {
alert('DELETE!!!');
var id=$(this).data('id');
var url="${createLink(controller: 'prodBuffer',action:'delete')}/"+id
$.ajax({
type: 'POST',
url: url,
success: function(data){
$('#results').html(data);
}
});
});
});
</script>
<span id="delete_prod" data-id="1">Delete<span>
But the alert will not be hit.
A button within existing form will act as submit button, you can look into <g:actionSubmit and submit it as a delete action that you then control in the contorller or use something like this - make something behave as a button then action it using ajax
<span id="deleteButton" data-id="${instance.id}">Delete<span>
<script>
$('#deleteButton').on('click',function() {
var id=$(this).attr('data-id');
var url="${createLink(controller: 'controller',action:'delete')}/"+id
$.ajax({
type: 'POST',
url: url,
success: function(data){
$('#results').html(data);
}
});
})
<script>
You could do the following.
Change your span to an <a> tag. It might be easier to handle the
different states it has, and easier to style if you use bootstrap or
similar frameworks.
Now to the code:
<form id="myForm">
<!-- your form fields here-->
<div>
<button type="submit">My update button</button> <!-- The normal buttons you´d use-->
Delete button <!-- your actual delete button -->
</div>
</form>
<div id="results"></div>
The html is quite simple and quite similar to what you might have. The difference being that I would prefer to reference my <a> via class instead of ID. Using <a> instead of <span> might make your code more manageable.
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script>
$(document).ready(function(){
$('.delete-button').on('click', function(event){
event.preventDefault(); //1
var deleteTarget = $(this).prop('href'); //2
if(confirm("Are you sure?")){ //3
$.post( //4
deleteTarget,
function successhandler(responseData){
$('#results').html(responseData);
}
);
}
});
});
</script>
As for the javascript, the following applies:
Prevent the default action for your <a>
Obtain the href of the clicked link
Add a confirmation, just in case
Send your data and manage your response
You can use a button group (bootstrap) and a single javascript ajax call to handle both buttons. We're using the id of the button to distinguish which action to call.
Your form will be different with regard to the data present, I've just used a hidden id field as an example below.
<script type="text/javascript">
$( document ).ready( function() {
$( '.itemAction' ).click(function (event) {
if ( confirm( 'Are you sure?' )) {
$.ajax({
url: "/prodBuffer/" + this.id,
type: "POST",
data: $( '#myForm' ).serialize(),
success: function ( data ) {
$( '#resultdiv' ).html( 'Success' );
window.setTimeout( function(){ location = '/prodBuffer/index' }, 2000 )
},
error: function(j, status, eThrown) { console.log( 'Error ' + eThrown ) },
complete: function() { console.log( 'Complete' ) }
});
}
});
});
</script>
<div id="resultdiv"></div>
<g:form name="myForm">
<g:hiddenField name="id" value="1" />
<div class="btn-group" role="group">
<button type="button" name="myUpdate" id="myUpdate" value="Update" class="itemAction btn btn-primary">Update</button>
<button type="button" name="myDelete" id="myDelete" value="Delete" class="itemAction btn btn-danger">Delete</button>
</div>
</g:form>
Controller:
def myUpdate() {
myService.update( params )
render (['success'] as JSON )
}
def myDelete() {
myService.delete( params )
render (['success'] as JSON )
}
I think you do not need to use Ajax for deletion, you can make a Delete button and code on your Domain's show page and controller (for show) like below which also give you a confirm alert. this call the delete method. Have a look.
Show page Code (show.gsp)
<g:form>
<fieldset class="buttons">
<g:hiddenField name="id" value="${prodBufferInstance?.id}" />
<g:link class="edit" action="edit" id="${prodBufferInstance?.id}"><g:message code="default.button.edit.label" default="Edit" /></g:link>
<g:actionSubmit class="delete" action="delete" value="${message(code: 'default.button.delete.label', default: 'Delete')}" onclick="return confirm('${message(code: 'default.button.delete.confirm.message', default: 'Are you sure?')}');" />
</fieldset>
</g:form>
Controller Code (for show page)
def show(Long id) {
def prodBufferIns = ProdBuffer.get(id)
if (!prodBufferIns) {
flash.message = message(code: 'default.not.found.message', args: [message(code: 'prodBufferIns.label', default: 'CustMeterReadingTemp'), id])
redirect(action: "list")
return
}
[prodBufferInstance: prodBufferIns]
}
Controller Code (Delete method)
def delete(Long id) {
def prodBufferIns= ProdBuffer.get(id)
if (!prodBufferIns) {
flash.message = message(code: 'default.not.found.message', args: [message(code: 'prodBuffer.label', default: 'prodBuffer'), id])
redirect(action: "list")
return
}
try {
prodBufferIns.delete(flush: true)
flash.message = message(code: 'default.deleted.message', args: [message(code: 'prodBuffer.label', default: 'prodBuffer'), id])
redirect(action: "list")
}
catch (DataIntegrityViolationException e) {
flash.message = message(code: 'default.not.deleted.message', args: [message(code: 'prodBuffer.label', default: 'prodBuffer'), id])
redirect(action: "show", id: id)
}
}
I am trying to submit a from with Ajax and use query validation plugin to validate it . I write code below :
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="jquery.validate.js"></script>
</head>
<body>
<form id="myForm">
<input type="text" name="name" />
<br/>
<input type="text" name="school" />
<br/>
<input type="submit" />
</form>
<div id="result"></div>
<script>
$(document).ready(function () {
$("#myForm").validate({
onkeyup: false,
rules: {
name: {
required: true,
minlength: 5
},
school: {
required: true,
minlength: 5
}
}
});
event.preventDefault();
$("#result").html('');
var values = $(this).serialize();
$("#myForm").ajaxForm({
url: "add_admin.php",
type: "post",
data: values,
beforeSubmit: function () {
return $("#myForm").valid();
},
success: function(){
//alert("success");
$("#result").html('Submitted successfully');
},
error:function(){
// alert("failure");
$("#result").html('There is error while submit');
}
});
});
</script>
</body>
but it didn't work . Made I any mistake here ?
can any one help me ?
some text some text some text some text some text
Update : Use following option as it works on all circumstances giving you power of ajax
JSFiddle here
Check in your NET tab under Inspect element or Firebug
$("#myForm").validate({
rules: {
school: {
required: true,
minlength: 5
}
},
submitHandler: function(form) {
//Your code for AJAX starts
jQuery.ajax({
url:'ajax.php',
type: "post",
data: $(form).serialize(),
success: function(){
//alert("success");
$("#result").html('Submitted successfully');
},
error:function(){
// alert("failure");
$("#result").html('There is error while submit');
}
//Your code for AJAX Ends
});
}
});
Bottomline -> Use jQuery validate's own mechansim of posting form via AJAX inside submitHandler.
This might help you...
<form id="myForm">
<input type="text" name="name" />
<br />
<input type="text" name="school" />
<br />
<input type="submit" id="BTNTest" />
</form>
<div id="result"></div>
<script>
$(document).ready(function () {
$("#myForm").validate({
onkeyup: false,
rules: {
name: {
required: true,
minlength: 5
},
school: {
required: true,
minlength: 5
}
}
});
event.preventDefault();
$("#result").html('');
var values = $(this).serialize();
$(document).on('click', '#BTNTest', function () {
$.ajax({
url: "add_admin.php",
type: "post",
data: values,
beforeSubmit: function () {
return $("#myForm").valid();
},
success: function () {
//alert("success");
$("#result").html('Submitted successfully');
},
error: function () {
// alert("failure");
$("#result").html('There is error while submit');
}
});
});
});
</script>
If i go through this code step by step in firebug it works, but it wont work on button press. Using a button outside form to call it works ok.....It seems that complete: line does not get executed at all.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#salji').click(function() {
var testing = false;
$.ajax({
type: "POST",
url: "https://mandrillapp.com/api/1.0/messages/send.json",
data: {
'key': 'Vv_8cJDX9*****',
'message': {
'from_email': 's****#gmail.com',
'to': [
{
'email': 'd*****#gmail.com',
'name': 'Test',
'type': 'to'
}
],
'autotext': 'true',
'subject': 'New subject',
'html': 'YOUR EMAIL CONTENT HERE! YOU CAN USE HTML!'
}
},
complete: function() {
testing = true;
$('#forma').attr('action', 'http://%SERVERIP%/signup1?%PARAMS%');
$('#forma').submit();
}
}
)
})
})
</script>
<div class="form1" align="center"><input class="button" value="#CONTINUE#" name="signup" type="submit" id="salji">
You don't have a form on the page, therefore .submit won't do anything.
Change your DIV to a form and give it the correct ID, "form1" is a class atm.
I have a text field(email) in my form which checks whether the entered value is valid, if so then it will have to validate the same again my DB.
The problem is that when I type wrong its not displaying the error message that I have configured under message, instead it chooses over the default msg.
$("#myform").validate({
rules: {
email:{
required: true,
email: true,
type: "post",
remote:{
url:"myservlet?verifyEmail=checkEmail",
/* data: "verifyEmail=checkEmail", */
type: "post",
}
},
messages:{
email:{
required: "Enter a valid email",
remote: "This user is already taken"
}
}
},
highlight: function(element){
$(element).closest('.control-group').removeClass('success').addClass('error');
},
success: function(element){
element
.closest('.control-group').removeClass('error')/* .addclass('error') */;
}
});
if(('#myform').validated())
('#myform').submit();
I tried to check the network traffic i dnt see any traffic due to this request. The bootstrap class configured under highlight and success is working fine. This is my first time using this plugin.
Update 1: Input controls
<div class="control-group">
<label class="control-label" for="email"> email:</label>
<div class="controls">
<input type="text" id="email" class="input-xlarge span2" name="email"/>
</div>
</div>
<tr>
<td></td>
<td><input type="button" Value="Refresh" /></td>
</tr>
Update 2:
I have modified my code. Now validation rules is working, but I am still facing issues with ajax request not being fired. Any heads up on that?
Try this - I've update the object structure slightly, messages is a sibling of rules, not a child:
$("#myForm").validate({
rules: {
email: {
required: true,
email: true,
type: "post",
remote: {
url: "myservlet?verifyEmail=checkEmail",
/* data: "verifyEmail=checkEmail", */
type: "post",
}
}
},
messages: {
email: {
required: "Enter a valid email",
remote: "This user is already taken"
}
}
});
DEMO