Request parameter getting null in ajax jquery validation engine in java - jquery-validation-engine

jqueryvalidationengine-en.js :
"ajaxUserCall": {
"url": "ajaxValidateFieldUser",
// you may want to pass extra data on the ajax call
"extraData": "name=eric",
"alertTextOk":"* This user name can be used and is available",
"alertText": "* This user is already taken",
"alertTextLoad": "* Validating..., please wait"
}
xyz.html:
<input class="validate[ajax[ajaxUserCall]] text-input" type="text" name="requir" id="requir" title="Text value is required"/>
function beforeCall(form, options){
if (console)
console.log("Right before the AJAX form validation call");
return true;
}
// Called once the server replies to the ajax form validation request
function ajaxValidationCallback(status, form, json, options){
if (console)
console.log(status);
if (status === true) {
alert("the form is valid!");
// uncomment these lines to submit the form to form.action
// form.validationEngine('detach');
// form.submit();
// or you may use AJAX again to submit the data
}
}
jQuery(document).ready(function(){
jQuery("#formID").validationEngine({
ajaxFormValidation: true,
onAjaxFormComplete: ajaxValidationCallback,
onBeforeAjaxFormValidation: beforeCall
});
});
Above is my html and jqueryengine-en.js code
And in servlet i am getting request.getParameter("requir") is null.
Please post me your answers regarding the above problem as i was unable to find much about Jquery validation engine on net and please share some link from where i can study more of it.
Please help me in getting requestParameter("requir") with form text box value.
Thanx in advance.

Related

POST FORM in node and receive data response back to same webpage

I have a webpage that takes form details, POSTS the data and should then show the results. I'm using express for my routing.
This all works fine by resending the data with the HTML template after the POST but I think there must be a better way by hiding the "results" HTML section then just showing it once the data is known from the form. I've shown a cutdown version of my pages below.
On first load, the page says "your result is undefined", which I would expect but is ugly.
I could remove the "result" section and create a 2nd HTML page to resend from the POST route with it in which would work but I think there must be a better way.
I want to hide the result section on 1st page load then make it appear on the button submit with the result data. I can get the section hide/unhide but I can't get the data results back to display them. On button submit the form results just appear in the weburl www.mywebsite.com/?data almost like a GET request
I have tried using FormData and npm 'form-data' in a POST but can't get it working following these examples https://javascript.info/formdata and https://www.npmjs.com/package/form-data.
My structure in Node is
Router.js file
return res.send(htmlFormTemplate({}));
});
router.post('/css',
[],
async (req, res) => {
let {data} = req.body;
///
result= do some calculation on {data}
///
return res.send(htmlFormTemplate({result}));
});
The htmlFormTemplate is a js file
module.exports = ({result}) => {
return `
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form class="box" method ="POST">
<inputname="data" />
<button>Submit</button>
</form>
<script>
///tried form processing here
</script>
<section id="Results">
<ul><li>Your result is ${result}</li></ul>
</section>
</body>
</html>
`;
};
I'm self-taught and new so hope this makes sense and thanks for any help/ideas
You can check if the result variable is null before it gets to the section div:
${ result === null ? '' :
`<section id="Results">
<ul><li>Your result is ${result}</li></ul>
</section>`}
Like this, it wont show the result div if result if null.
There is a very simple to solve this problem,
just use some templating engine for ex EJS, its very easy to use and will help you better,
and your result is undefined because your using a promise and it might have happened that the response might have not come and you loaded the page. Just use await
return await res.send(htmlFormTemplate({result}));

Get Subtitles data of a Youtube video using api in nodejs

Here is some link which provides subtitle list of youtube video in xml format.
'https://www.youtube.com/api/timedtext?lang=en&v=6dlr-1Qk8Uc'
'http://video.google.com/timedtext?type=track&v=zenMEj0cAC4&id=0&lang=en'
But it is not applied for all videos.
Some videos have subtitle(cc) icon at bottom of video and on click this subtitle appears, but this links cannot return the subtitle data.
Then I have checked the respose data on click the cc icon , it return data of all videos which have subtitle.
But I cannot get how to call this api using node js.
Instead of use the YouTube Data API - caption1 for retrieve the captions of a video, you can also use an AJAX callback for get the captions.
1If you want use the YouTube Data API for query the captions, I advise you read the documentation carefully.
In this example, an AJAX callback is used for retrieve the captions from a given YouTube video.
Using the XML parser, the response of the previous AJAX callback is iterated in a for-loop for get the captions:
// Ajax callback to the YouTube channel:
$.ajax({
type: "GET",
url: "http://video.google.com/timedtext?type=track&v=zenMEj0cAC4&id=0&lang=en",
crossDomain: true,
}).done(function(data) {
getCaption(data);
});
// Variables.
var parser, xmlDoc;
var HTML_captions = "";
// Parse the AJAX response and get the captions.
function getCaption(data) {
try {
// Loop the results of the ajax:
for (var i = 0; i < data.getElementsByTagName("transcript")[0].childNodes.length; i++) {
HTML_captions += data.getElementsByTagName("transcript")[0].childNodes[i].innerHTML + "<br/>";
}
// Preparing captions...
fillData();
} catch (err) {
console.log(err);
alert('Error at getCaption function - see console form more details.');
}
}
// Fill the data "captions" in a HTML "div" control.
function fillData() {
try {
document.getElementById("demo").innerHTML = HTML_captions;
} catch (err) {
console.log(err);
alert('Error at fillData function - see console form more details.');
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<div class="infoVideo">
<span>These are the captions of the following YouTube video:</span>
<br/>
<span>Title: How Turbochargers Work</span>
<br/>
<span>URL: https://www.youtube.com/watch?v=zenMEj0cAC4</span>
</div>
<br/>
<div id="demo"><i>Loading captions...</i></div>

Bootstrap + jQuery validationEngine make custom ajax validation call onFieldSuccess to update feedback

I am using the jQuery Validation Engine plugin to validate my form. I am also using Bootstrap to give the user feedback (success/fail) of the given input.
Here is how I am initializing the plugin:
jquery
$.validationEngine.defaults.promptPosition = 'inline';
$.validationEngine.defaults.onFieldFailure = function (field) {
console.log('onFieldFailure called');
field.parent().removeClass('has-success').addClass('has-error');
field.nextAll('span').children().removeClass('fa-check').addClass('fa-remove');
};
$.validationEngine.defaults.onFieldSuccess = function (field) {
console.log('onFieldSuccess called');
field.parent().removeClass('has-error').addClass('has-success');
field.nextAll('span').children().removeClass('fa-remove').addClass('fa-check');
};
$form.validationEngine('attach');
I am using CodeIgniter to handle the form server-side. Everything is working great.
html/php
<div class="form-group has-feedback">
<label for="email"><i class="fa fa-asterisk"><span class="sr-only">This field is required</span></i> E-mail Address</label>
<input type="text" class="form-control" id="email" name="email"
data-validation-engine="validate[required, custom[email], ajax[email_exists]]"
data-errormessage-value-missing="This field is required"
data-errormessage="Invalid E-mail address"
value="<?php echo set_value('email'); ?>"
placeholder="your#email.com">
<span class="form-control-feedback"><i class="fa fa-remove"></i></span>
<?php echo form_error('email'); ?>
</div>
Here is my controller (how I'm returning a response):
php
public function ajax_email_exists() {
if ($this->user_model->email_exists($this->input->get('fieldValue'))) {
echo json_encode(array('email', FALSE));
} else {
echo json_encode(array('email', TRUE));
}
}
When the user blurs out of the email field, I do an ajax call email_exists which is working fine as well. Here is what that looks like. It is located in the jquery.validation-engine-en.js file as suggested in the docs.
jquery
'email_exists': {
'url': 'path-to-my-script.php',
'alertTextLoad': '<i class="fa fa-cog fa-spin"></i> Validating, please wait...',
'alertTextOk': '<i class="fa fa-check-circle"></i> E-mail address is valid',
'alertText': '<i class="fa fa-exclamation-triangle"></i> That Email-address already exists'
},
The validation itself is working great. I am getting correct response back - the problem I'm running into is I can't seem to figure out how to make the success of the ajax call to call the onFieldSuccess method. As soon as I blur out of the email field onFieldFailure is called and my input is red. When the ajax validation is complete, I am unable to get rid of the invalid style and apply my valid style. In essence, call the onFieldSuccess method to give the correct feedback.
A thought I had was maybe I need to look at using funcCall instead?
Thank you for your time & suggestions!
EDIT
I've updated my initialize method to add css classes to the elment(s). It seems i'm always getting to addFailureCssClassToField even when I am getting a success result back from the server.
Just in case anyone come across this thread, here is how I came up with a solution.
As mentioned before, all of my validation is/was working correctly. The problem was updating the feedback accordingly. I was unable to update the style(s) to reflect what was happening.
I have updated/cleaned up the plugin code itself so my line numbers are going to be off. That said, around line #1578, you will find this:
jquery
if (options.showPrompts) {
// see if we should display a green prompt
if (msg) {
methods._showPrompt(errorField, msg, "pass", true, options);
options.onFieldSuccess(errorField); // Added this line.
} else {
methods._closePrompt(errorField);
}
}
Because I was getting a success response, I needed to call onFieldSuccess. I am also passing in the field element (jQuery object) to render to.

Data validation in server by socket.io and node.js then POST a from

I have a form like this:
<form method='post' action='next' onsubmit="return validateMyForm();" >
<input type="text" id="data" />
<input type="submit" />
<p id="result"></p>
and this code for interact with node.js:
socket = io.connect();
function vlidateMyForm(){
var data = $('data').val();
socket.emit('login',{data: data}); // check dataBase in server
return false;
}
socket.on('responseLogin',function(result){
if(result){ // if data is valid
// submit form
}
else{ // data invalid
$('#result').html('field is not valid')
}
});
I want to submit my form, when the result is true. What should I do to solve this problem?
Change socket.on('responseLogin',function(result){... to socket.on('login',function(result){... should fix your problem
You can use Jquery submit to submit the form :
$("form#formID").submit();
Your form must have action attribute like action='url_to_post_to' for this.
Or if you like to use AJAX so that you can process the data, you can do :
$.ajax({
type: "POST",
url: 'url_to_post_to',
data: $("#formID").serialize(),
success: function(data)
{
alert(data);
}
});

SharePoint: commonModalDialogClose does not close cross-domain dialog

I have a page hosted in 'virtualcasa1' domain opening a modal dialog:
var options = {
title: "Repro",
width: 400,
height: 600,
url: http://domain2:999/sites/blank/_layouts/XDomainTest/XDomainTestTarget.aspx //[1]
//url: http://virtualcasa1/sites/blank/_layouts/XDomainTest/XDomainTestTarget.aspx [2]
};
SP.UI.ModalDialog.showModalDialog(options);
And I have this code to close it:
alert(document.domain);
SP.UI.ModalDialog.commonModalDialogClose(SP.UI.DialogResult.cancel, 'Cancelled clicked');
If both are in the same domain (case [2] above), the dialog closes well, no issues.
But - if target page hosted in the dialog (case [1] above), dialog does NOT close :-(
document.domain above shows the correct domain where page exists.
I suspect I'm facing a cross-domain issue here (duh), but how to fix it? Or am I wrong and issue is not XDomain-related?
Thanks much!
HTML5's postMessage is your answer.
https://developer.mozilla.org/en-US/docs/Web/API/Window.postMessage
Your parent window that initiates the dialog must have the following javascript:
function listener(event) {
//alert(event.data);
if (event.data == 'Cancel') {
SP.UI.ModalDialog.commonModalDialogClose(SP.UI.DialogResult.cancel, 'Cancel clicked');
}
else {
SP.UI.ModalDialog.commonModalDialogClose(SP.UI.DialogResult.OK, event.data);
}
}
if (window.addEventListener) {
addEventListener("message", listener, false)
} else {
attachEvent("onmessage", listener)
}
Javascript for OK and Cancel buttons in your popup:
<input type="button" value="OK" onclick="parent.postMessage('Message to be displayed by the parent', '*');" class="ms-ButtonHeightWidth" />
<input type="button" value="Cancel" onclick="parent.postMessage('Cancel', '*');" class="ms-ButtonHeightWidth" />
Ajay's answer from the 1st of August 2014 is good, but it needs a bit more explanation. The reason for the failure to close the dialog is simple. Cross site scripting security features of modern browsers disallow a few things, one of which is the use of window.frameElement from within the framed window. This is a read-only property on the window object and it becomes set to null (or with IE, it actually throws an exception when you try to access it). The ordinary Cancel event handlers in the modal dialog conclude with a call to window.frameElement.cancelPopup(). This will fail of course. The ordinary Save handler where the Save worked on the server side results in SharePoint sending back a single line as the replacement document, which is a scriptlet to call window.frameElement.commitPopup(). This also will not work, and it's a real pain to overcome because the page has been reloaded and there is no script available to handle anything. XSS won't give us access to the framed DOM from the calling page.
In order to make a cross domain hosted form work seamlessly, you need to add script to both the page that opens the dialog and the framed page. In the page that opens the dialog, you set the message listener as suggested by Ajay. In the framed form page, you need something like below:
(function() {
$(document).ready(function() {
var frameElement = null;
// Try/catch to overcome IE Access Denied exception on window.frameElement
try {
frameElement = window.frameElement;
} catch (Exception) {}
// Determine that the page is hosted in a dialog from a different domain
if (window.parent && !frameElement) {
// Set the correct height for #s4-workspace
var frameHeight = $(window).height();
var ribbonHeight = $('#s4-ribbonrow').height();
$('#s4-workspace').height(frameHeight - ribbonHeight);
// Finds the Save and Cancel buttons and hijacks the onclick
function applyClickHandlers(theDocument) {
$(theDocument).find('input[value="Cancel"]').removeAttr('onclick').on('click', doTheClose);
$(theDocument).find('a[id="Ribbon.ListForm.Edit.Commit.Cancel-Large"]').removeAttr('onclick').removeAttr('href').on('click', doTheClose);
$(theDocument).find('input[value="Save"]').removeAttr('onclick').on('click', doTheCommit);
$(theDocument).find('a[id="Ribbon.ListForm.Edit.Commit.Publish-Large"]').removeAttr('onclick').removeAttr('href').on('click', doTheCommit);
}
// Function to perform onclick for Cancel
function doTheClose(evt) {
evt.preventDefault();
parent.postMessage('Cancel', '*');
}
// Function to perform onclick for Save
function doTheCommit(evt) {
evt.preventDefault();
if (!PreSaveItem()) return false;
var targetName = $('input[value="Save"]').attr('name');
var oldOnSubmit = WebForm_OnSubmit;
WebForm_OnSubmit = function() {
var retVal = oldOnSubmit.call(this);
if (retVal) {
var theForm = $('#aspnetForm');
// not sure whether following line is needed,
// but doesn't hurt
$('#__EVENTTARGET').val(targetName);
var formData = new FormData(theForm[0]);
$.ajax(
{
url: theForm.attr('action'),
data: formData,
cache: false,
contentType: false,
processData: false,
method: 'POST',
type: 'POST', // For jQuery < 1.9
success: function(data, status, transport) {
console.log(arguments);
// hijack the response if it's just script to
// commit the popup (which will break)
if (data.startsWith('<script') &&
data.indexOf('.commitPopup()') > -1)
{
parent.postMessage('OK', '*');
return;
}
// popup not being committed, so actually
// submit the form and replace the page.
theForm.submit();
}
}).fail(function() {
console.log('Ajax post failed.');
console.log(arguments);
});
}
return false;
}
WebForm_DoPostBackWithOptions(
new WebForm_PostBackOptions(targetName,
"",
true,
"",
"",
false,
true)
);
WebForm_OnSubmit = oldOnSubmit;
}
applyClickHandlers(document);
}
});
})();
This solution makes use of the jQuery library, which our organization uses extensively. It is our preferred framework (chosen by me). I'm sure someone very clever could rewrite this without that dependency, but this is a good starting point. I hope someone finds it useful, as it represents a good two days work. Some things to note:
SharePoint does a postback on all sorts of events on the page, including putting the page into edit mode. Because of this, it makes more sense to trap the specific button clicks, both on the form and in the ribbon, rather than wholesale redefinition of, for example, the global WebForm_OnSubmit function. We briefly override that on a Save click and then set it back.
On any Save click event, we defeat the normal posting of the form and replace that with an identical POST request using AJAX. This allows us to discard the returned scriptlet when the form was successfully posted. When the form submission was not successful, perhaps because of blank required values, we just post the form properly to allow the page to be updated. This is fine, since the form will not have been processed. An earlier version of this solution took the resulting HTML document and replaced all of the page contents, but Internet Explorer doesn't like this.
The FormData api allows us to post the form as multipart-mime. This api has at least basic support in all modern browsers, and there are workarounds for older ones.
Another thing that seems to fail in the cross domain hosted dialog is the scrolling of the content window. For whatever reason, the height is not set correctly on the div with id s4-workspace, so we also set that in the solution.
EDIT:
Almost forgot. You may also need to add this control to your framed ASPX page, which can be done with SharePoint Designer:
<WebPartPages:AllowFraming runat="server"/>
I have exactly the same issue - a dialog opening a view page for an item works fine when opened from a site collection on the same web app/domain, but the Close button fails to work when opening the same item from a site collection hosted in a separate web application. I'm assuming it is a cross-domain thing so I've altered the solution to accomodate this restriction, however, I'm not 100% happy about it as it does make the overall solution a little awkward to use from a user-perspective. I've put the issue to one side for now due to project timescales, but I'm still curious as to why. The only things I can think of is the whole cross-domain thing causing it and that maybe it is there by design to prevent XSS security holes.

Resources