remoteFunction grails - ajax

Hi I have a textArea and I have added a onkeyup event to it. When the event is triggered I want to update another element, by taking the input of the textArea and manipulating it in a javascript function. Here is my textArea tag:
<g:textArea name="translation" id="2" cols="40" rows="5" value="${domainInstance?.translation}"
onkeyup="${remoteFunction(
controller: 'domain',
action: 'ajaxChangeTranslation',
params:'\'text=\'+this.value',
onComplete:'updateEntry(e)')}" />
and here is my stub javascript function:
<g:javascript>
function updateEntry(e){
alert("Hi");
}
</g:javascript>
My javascript function is never getting called. I never see the alert when I type something into the textArea. If I place an alert outside of the function the alert shows up. Why is my javascript function not getting called. When I ran it with the chrome debugger I didn't get any errors.

Try this:
<g:textArea name="translation" id="2" cols="40" rows="5" value="${domainInstance?.translation}"
onkeyup="${remoteFunction(
controller: 'domain',
action: 'ajaxChangeTranslation',
params:'\'text=\'+this.value',
onComplete :'updateEntry(XMLHttpRequest,textStatus)')}" />

Related

Get name from textChange event in nativescript-vue

have this code:
<TextField
v-model="lastname"
#textChange="ontextChange"
name="lastname"
/>
and i want get name from event:
ontextChange(args){
console.log(args.name)
}
but i thing it's wrong.
You are accessing the wrong attribute in the arguments. It's of type EventData, you must be looking for args.eventName.
Update:
If you want to access the actual TextField which triggered the event, args.object should work.

SAPUI5 sam.m.Input.submit() does not work

Currently I want to create a function to handle when user press Enter on Input field (sap.m.Input). I found this suitable function submit() in the API.
However it didn't work, I tried but nothing happen. I pressed enter but it does not call the responding function.
Here my code:
App.view.xml
<mvc:View controllerName="Test.controller.App" xmlns:html="http://www.w3.org/1999/xhtml" xmlns:mvc="sap.ui.core.mvc" xmlns="sap.m">
<App>
<pages>
<Page title="{i18n>title}">
<content>
<Input submit='onSubmit'/>
</content>
</Page>
</pages>
</App>
</mvc:View>
App.controller.js:
sap.ui.define([
"sap/ui/core/mvc/Controller"
], function(Controller) {
"use strict";
return Controller.extend("Test.controller.App", {
onSubmit: function(oEvent){
console.log("Submitted");
}
});
});
I pressed enter but nothing showed in the console.
I'm looking for help from your expert experience. Is the submit() function does not work anymore? Is there another function to solve my question?
First of all submit is not a function, it's an event.
This event is fired when user presses the Enter key on the input.
So, function to be called when event is fired should be specified as this event's value in view.
View code:
<Input submit='onSubmit'/>
Controller code:
onSubmit: function(oEvent) {
console.log("Submitted");
}

How to clear jquery validate errors

I'm hijaxing an existing form and POSTing to the server. jQuery validate does most of the validation but if validation fails on the server we return the errors to the client as JSON.
Below is the code that does that:
<script type="text/javascript">
$(function () {
$("form").submit(function (e) {
var $form = $(this);
var validator = $form.data("validator");
if (!validator || !$form.valid())
return;
e.preventDefault();
$.ajax({
url: "#Url.Action("index")",
type: "POST",
data: $form.serialize(),
statusCode: {
400: function(xhr, status, err) {
var errors = $.parseJSON(err);
validator.showErrors(errors);
}
},
success: function() {
// clear errors
// validator.resetForm();
// just reload the page for now
location.reload(true);
}
});
});
});
</script>
The problem is I can't seem to clear the validation errors if the POST is successful. I've tried calling validator.resetForm() but this makes no difference, the error messages added by the showError() call, are still displayed.
Note I'm also using the jQuery.validate.unobtrusive plugin.
You posted this a while ago, I don't know if you managed to solve it? I had the same problem with jQuery validate and the jQuery.validate.unobtrusive plugin.
After examining the source code and some debugging, I came to the conclusion that the problem comes from the way the unobtrusive plugin handles error messages. It removes the errorClass that the jQuery.validate plugin sets, and so when the form is reset, jQuery validate cannot find the error labels to remove.
I did not want to modify the code of the plugins, so I was able to overcome this in the following way:
// get the form inside we are working - change selector to your form as needed
var $form = $("form");
// get validator object
var $validator = $form.validate();
// get errors that were created using jQuery.validate.unobtrusive
var $errors = $form.find(".field-validation-error span");
// trick unobtrusive to think the elements were succesfully validated
// this removes the validation messages
$errors.each(function(){ $validator.settings.success($(this)); })
// clear errors from validation
$validator.resetForm();
note: I use the $ prefix for variables to denote variables that contain jQuery objects.
$("#form").find('.field-validation-error span').html('')
In .NET Core I have the form inside a builtin Bootstrap modal.
For now I'm manually removing the error message spans from their containers, once the modal is starting to show, by using the additional .text-danger class of the error message container like so:
$('#my-form').find('.text-danger').empty();
so that I don't rely on container .field-validation-error that might have been already toggled to .field-validation-valid.
The min.js versions of the libraries jquery.validate and jquery.validate.unobtrusive are loaded via the partial view _ValidateScriptsPartial.cshtml, so I played with them to see what resetForm() / valid() and native html form reset() do.
So in my case $('#my-form').data("validator").resetForm() only resets some validator internals, not the form and it doesn't trigger the onReset() function in the unobtrusive library. The $('#my-form').valid() indeed removes the errors in the modal, but only if the modal is fully shown and valid. The native html form reset() is the only one that triggers both onReset() of unobtrusive library, and then the resetForm() of the validator. So it seems like we need to trigger the native html form document.querySelector('#my-form').reset() to activate the reset functions of both libraries/plugins.
The interesting thing is that the unobtrusive library runs the simple jQuery empty() on the .field-validation-error class (the container of the error span message) only in its onSuccess() function, and not onReset(). This is probably why valid() is able to remove error messages. The unobtrusive onReset() looks like it's responsible only for toggling .field-validation-error class to .field-validation-valid. Hense we are left with a <span id="___-error">The error message</span> inside the container <span class="text-danger field-validation-error">...</span>.
May be I am wrong to clear the errors like this:
function clearError(form) {
$(form + ' .validation-summary-errors').each(function () {
$(this).html("<ul><li style='display:none'></li></ul>");
})
$(form + ' .validation-summary-errors').addClass('validation-summary-valid');
$(form + ' .validation-summary-errors').removeClass('validation-summary-errors');
$(form).removeData("validator");
$(form).removeData("unobtrusiveValidation");
$.validator.unobtrusive.parse($(form));
};
I tried answer given in the comment by AaronLS but not got the solution so I just do it like this.
Maybe helpful to someone.
Here's the code I ended up using to clear/reset all errors. It's possible there's some redundancy in there, but it's working for me.
function removeValidationErrors(frmId) {
var myform = $('#' + frmId);
myform.get(0).reset();
var myValidator = myform.validate();
$(myform).removeData('validator');
$(myform).removeData('unobtrusiveValidation');
$.validator.unobtrusive.parse(myform);
myValidator.resetForm();
$('#' + frmId + ' input, select').removeClass('input-validation-error');
}
The reason this is still an issue (even 6 years on) is that jQuery Validation doesn't have an event handler for when your form is valid; only for when it's invalid.
Unobtrusive Validation taps into the Invalid handler to add your errors to your Validation Summary elements. (Specifically, any element with data-valmsg-summary=true.) But because there's no Valid handler, there's no way for Unobtrusive Validation to know when they can be cleared.
However, jQuery Validation does allow you to supply your own showErrors method, which is called after every validation check, whether the result is valid or invalid. Thus, you can write a custom function that will clear those validation summary boxes if your form is valid.
Here's a sample that will apply it globally. (You could apply it to specific instances of your validators by using settings, but since I always want this functionality, I just put it in the defaults object.)
$.validator.defaults.showErrors = function () {
if (!this.errorList.length) {
var container = $(this.currentForm).find("[data-valmsg-summary=true]");
container.find("ul").empty();
container.addClass("validation-summary-valid").removeClass("validation-summary-errors");
}
// Call jQuery Validation's default showErrors method.
this.defaultShowErrors();
};
This also has the benefit of clearing the validation summary box the moment your form is valid, instead of having to wait for the user to request a form submission.
I couldn't find this documented anywhere, but you should be able to reset the form by triggering a specific event, reset.unobtrusiveValidation, to which unobtrusive listens.
Example here:
.validation-summary-valid, .field-validation-valid { display: none; }
.field-validation-error { display: block; color: #dc3545 }
.input-validation-error { border: 1px solid #dc3545 }
.validation-summary-errors { background-color: #dc3545; color: #fff; margin-bottom: .5rem; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.5/jquery.validate.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validation-unobtrusive/4.0.0/jquery.validate.unobtrusive.js"></script>
<form id="testForm">
<div class="validation-summary-valid" data-valmsg-summary="true">
Validation Summary:
<ul><li style="display:none"></li></ul>
</div>
<div>
<label for="first_name">first name:</label>
<input data-val="true" data-val-required="the 'first name' field is required" name="first_name" id="first_name" />
<span class="field-validation-valid" data-valmsg-for="first_name" data-valmsg-replace="true"></span>
</div>
<div>
<label for="last_name">last name:</label>
<input data-val="true" data-val-required="the 'last name' field is required" name="last_name" id="last_name" />
<span class="field-validation-valid" data-valmsg-for="last_name" data-valmsg-replace="true"></span>
</div>
<button type="submit">Submit form (click first)</button>
<button type="button" onclick="$('#testForm').trigger('reset.unobtrusiveValidation')">Reset form (click second)</button>
</form>

Is it possible to render json data into a javascript variable while making an ajax call in grails?

Is it possible to render json data into a javascript variable while making an ajax call in grails?
I am using the submitToRemote inorder to make an ajax call from my grails view to an action in my grails controller. The action returns a json variable/value. I need to to assign this value to a javascript variable for further usage on my web page. Is this possible to achieve? Any leads will be helpful.
submitToRemote have the onSuccess option that you can use to retrieve the json data. From the docs:
onSuccess (optional) - The JavaScript function to call if successful
An example of how doing it can be seen in this blog post.
You could use the onSuccess callback of submitToRemote to read the result of your request and pass them into a javascript variable.
<script type="text/javascript">
function passResult(result) {
yourVariable = result.responseText
}
</script>
<g:form action="show">
Login: <input name="login" type="text" />
<g:submitToRemote update="updateMe" onSuccess="passResult(result)"/>
</g:form>
<div id="updateMe">this div will be updated with the form submit response</div>
The code above is untested but should work.

Read iframe content after submit a form in the iframe

i'm trying to upload a file trough iframe.
i create the iframe in this way:
<iframe frameBorder="0" height="50px" width="100%" id="iframe-upload"/>
after this i append the iframe to the DOM:
$('#iframe-upload').contents().find('body').append('<form method="post" action="admin/images/upload" enctype="multipart/form-data" id="form-upload-image"><input name="data[image]" type="file" id="image-upload" /><input type="button" id="btn"></form>').appendTo("#formupload");
to submit i act like this:
$("#iframe-upload").contents().find('#btn').bind('click', function(){
$("#iframe-upload").contents().find('#form-upload-image').submit()
})
now, i cannot figure out WHEN i have to call:
console.log($("#iframe-upload").contents());
to get the content.
The problem is sync between my contents() request and iframe refresh, actually jquery goes first, and AFTER the iframe refreshes. In this way i cannot reach the real response.
p.s.
i've tried live(), on(), change() con the frame content, but all these events fires up only one time ( when i select the file before submitting the form ) and so are useless
thank you in advice
You should be able to grab the contents from the iframe before submitting the form. To achieve this, you can bind a function to the form's onSubmit event.
$('#form-upload-image').bind('submit', function (event) {
event.preventDefault();
console.log($("#iframe-upload").contents());
this.submit();
});
or possibly
$('#form-upload-image').submit( function () {
console.log($("#iframe-upload").contents());
});
This is just off the top of my head.
Check the contents after the iframe is loaded.
$('#iframe').load(function () {
$(this).contents();
});

Resources