Better way to temporarily disable ajax submission on ajaxForm plugin - forms

I'm using the jQuery malsup ajaxForm plugin on a form. I've got a bunch of POST vars that get submitted and this is working fine, I want to use the same post vars to perform an Export to file option. This means using the same form for both submission types.
Because you can't download Files through an AJAX submission, I'm using .unbind('submit').submit() on the form to prevent the previously assigned ajax event handlers from firing.
After this unbinding occurs, I then have to re-run the ajaxForm constructor when the user wants to change the filters using AJAX (not for the export).
Before I invest more time in fixing the edge cases and a couple of bugs, I wondered if there was a cleaner way to do this?

Use custom events and trigger()!
First, put a radio button on your form to allow the user to switch between AJAX/Export to file. Let's say the name of this field is submitAction
Second, your submit listener acts only to decide what happens next based upon the value of the submitAction radio. This is where you fire the custom events (we define them in step 3):
$('form.specialform').on('submit',function(e){
e.preventDefault();
var checked = $(this).closest('[name="submitAction"]').filter(':checked');
if(checked.val() == 'ajax'){ //ajax!
$(this).trigger('submitAJAX');
} else { //export to file!
$(this).trigger('submitExport');
}
});
Third, define your custom events with two event listeners:
$('form.specialform').on('submitAJAX',function(e){
//do AJAX call here
});
$('form.specialform').on('submitExport',function(e){
//do file export here
});
As you can see, doing it this way allows you to avoid the mess of unbinding and rebinding the same event handlers a bunch of times.
Does that help?

Thanks a lot to Jonathan for the above answer. We too were faced with similar problem and triggering custom events did the trick for us.
Also i would add that if malsup ajaxForm plugin is being used, we should invoke 'ajaxSubmit' instead of ajaxForm as ajaxForm doesn't submit the form.
$('form.specialForm').on('submitAJAX',function(e) {
$(this).ajaxSubmit({
target: '#query_output',
beforeSubmit: showLoading,
success: hideLoading
});
});

Related

AEM: Display an Alert box after server side validation

I have a form in AEM. When the submit button is clicked control goes to forward.jsp. I have done some validations in forward.jsp and would like to generate on alert on the page once the validation is failed. How can I pass the alert to the page?
if(condition){
// validation success
} else{
// code for alert
}
FormsHelper.redirectToReferrer(slingRequest, slingResponse);
If you want to do the validation server-side, but show an alert client-side, I recommend you use JavaScript to make an AJAX call. You could change your submit button so that when it is clicked, it fires an AJAX call instead of submitting a form. See http://api.jquery.com/jquery.ajax/ for a description of how this could be done using jQuery, but other options would also work for making the AJAX request.
In the response to that AJAX request you can put whetever you need. It can be a status code, a string of JSON, or a blurb of HTML. You then would write client-side JavaScript to handle the response and do whatever is appropriate based on the given response--such as show an alert on the page.
An example of this sort of approach if seen at http://michaelsoriano.com/how-to-ajax-validate-forms/
This topic is more complicated that you might think. Basically you can see sample implementation in the foundation components such as /libs/foundation/components/form/text/text.jsp. They all use the com.day.cq.wcm.foundation.forms.LayoutHelper#printErrors method to check if they are errors on field. This is happening over the com.day.cq.wcm.foundation.forms.ValidationInfo class which is set as request attribute in order to transfer the field state between the different classes. You can check also the com.day.cq.wcm.foundation.forms.FieldHelper class which performs actually the validation. Putting some sort of logic in the forward.jsp is the wrong ways

How do I correctly Implement an event on successful form Submission using Google Tag Manager and Sitecore's Web Forms for Marketers?

I am attempting to track successful form Submissions using an event in Google Analytics via Google Tag Manager. My current setup successfully tracks when users submit the form. However, the event still fires even when the form submission is invalid and does not submit (ie a user hasn't filled out all of the required fields, clicks the submit button, the form attempts to validate, but comes back to the user with errors instead of submitting). I have the Check Validation feature on my listener checked which theoretically should keep the tag from firing if the form submission is prevented, so it's not the obvious error.
The form in question is created with Sitecore's Web Forms for Marketers. Colleagues of mine have had similar unsolved issues with their WFFM forms.
This particular form is used to gate content so that only users who fill out the form will have access to the content resource. So for example if I go to www.mydomain.com/resource I will be redirected to www.mydomain.com/form where if I fill out all of my information correctly and submit it I will then be redirected to the resource that I was originally attempting to view at www.mydomain.com/resource.
Here's my setup:
Tag 1
Name: Form Submission Listener
Type: Form Submit Listener
Wait For Tags: Checked
Max Wait Time: 2000 milliseconds
Check Validation: Checked
No advanced Settings
Firing Rule: On form pages by URL
Tag 2
Name: Event Form Submission
Type: Universal Analytics
Tracking ID: UA-.....
Enable Display Advertising Features: Checked
Track Type: Event
Category: Form
Action: Submission
Label: {{Form resource URL}}
Non-Interaction Hit: False
No More Settings
No Advanced Settings
Firing Rules: {{event}} equals gtm.formSubmit
Theoretically the Check Validation check box should prevent the tag from firing if the form does not successfully submit, but in the case of this form it does not. The tag fires regardless of whether the form submits or not.
Apologies that I cannot link to the form as it is for a client and behind security.
We were able to find an answer to our question via the Sitecore forums, but I wanted to pass it along for your benefit.
From Sitecore:
The Web Forms module provides the double level validation, 1-client validation, 2-server validation.
By default, the client validation is disable for the Required Field validator. So, when you press Submit, the form posts to the server, and returns with the validation error. It's a possible reason why Google Analytics considers that as a form submit.
Find the following item in the Master database:
/sitecore/system/Modules/Web Forms for Marketers/Settings/System/System Validation/NotEmpty
Find the "Enable Client Script" checkbox and enable it.
Save and publish the item.
Check whether the issue was fixed.
This fixed the issue for all of our text based fields. It did not fix the issue for the one checkbox on the form. I've followed up with sitecore on this, but I figured that I'd update here in the meantime.
With only the checkbox remaining I was also able to use a a macro and add to my original firing rule in google tag manager so that the event would not fire if the checkbox was not checked.
I created a Custom Javascript Macro called Radio Button Checked (not sure it's the best, but it worked), and added a new condition to my original Form Submission Rule: {{Radio Button Checked}} equals true
The macro:
function() {
var radioName = "radioButtonName";
try {
var buttons = document.getElementsByName(radioName);
for (var i = 0;i < buttons.length;i++){
if(buttons[i].checked) {
return true;
}
}
} catch(e) {}
return false;
}
EDIT: Sitecore got back to me about the checkbox issue.
From Sitecore:
Currently the CheckBox field type doesn't have the client-side validation. I registered it as a bug for the WFFM module. I'll let you know as soon as it's fixed.
They let me know also that this isn't something that will be fixed near-term so I need to continue using my GTM workaround for the check box field.
The Google Chrome plugin "Tag Assistant" is super helpful in debugging these sorts of issues. It will show you what (if any) structural or implementation issues exist on a given page that might be preventing your intended tracking behavior (https://chrome.google.com/webstore/detail/tag-assistant-by-google/kejbdjndbnbjgmefkgdddjlbokphdefk?hl=en)
My gut feel is that this issue is not specifically related to WFFM, but may be due to the implementation of the Tag Manager code on the page. I seem to recall having an issue like this when the Tag Manager include code gets dumped inside the auto-generated .NET tag when using WebForms in general. Google's docs (https://developers.google.com/tag-manager/quickstart) say to put it immediately after the opening tag, and I recall that being my issue with tracking form submits.
This is all from memory, so I could be wrong, but it's something else to check.
Good luck!

Incoming Phone call to make a Popup inside of SugarCRM?

Hello I am trying to make a module that will make a popup window inside of SugarCRM when we receive a phone call. I have seen that some others have accomplished this already (expensive paid modules) and I am hoping to get some insight on the actual popup triggering part....
Our phone system has an API that sends an HTTP post to a URL when we have an incoming phone call.
Inside of SugarCRM, in my Modules code, I am not sure how I can use this HTTP POST from my Phone to do the Popup, the reason is I do not see how it can be fast enough, If I were to set a Cron job to check a page every 1 minute, that would still be too slow.
So does anyone have any ideas how the other similar Phone integration modules are doing it and having the Popup happen almost immediately as the phone call comes in?
Any ideas on how to do such a task? I am planning to do a Desktop application that just sits in the Tray and waits for the POST but seeing others have been able to get the same result inside of SugarCRM without a separate program really interests me.
I am working in a company that has created a expensive paid module to accomplished this, but I can give you hints for 2 ways to achieve this ;-)
1) With GenericHook
in custom/modules create a logic_hooks.php and a YOURCHOICEHERE.php
in the logic hooks create an after ui hook
$hook_array['after_ui_frame'] = Array();
$hook_array['after_ui_frame'][] = Array(1, 'Display Javascript for Telephone','custom/modules/YOURCHOICEHERE.php','GenericHooks', 'displayTelephoneJS');
and in YOURCHOICEHERE.php
class GenericHooks {
function displayTelephoneJS() {
if(!$_REQUEST['to_pdf']) echo '<div id=\"telephone_div\"></div>
<script type=\"text/javascript\" src=\"custom/somewherewhereyouwant/Telephone.js\"/></script>';
// you yould also add a stylesheet here
}
}
in the Telephone.js you can do what ever you want for example:
function Telephone_poll() {
$.post("some.php?poll=1,function(data){
if(data != 0)
{
var result= JSON.parse(data);
//HERE you can do manipulate your telephone_div and populate it with response data "result" from the call to some.php
$('#telephone_div').html("<span>HELLO<span>");
$('#telephone_div').show();
//Here you can also add styles and so on
}
setTimeout("Telephone_poll()", 1000); //restart the function every 1000ms
});
}
Telephone_poll(); //initial start of script
2) An other approach would be creating a demon/service from a php file that reruns itself.
Here you would need some way to identify users and Phones to ensure the popup is displayed for the correct user/phone.

Field and Form Validation with ember.js

I've integrated Boronine's excellent field validation code for ember.js from jsfiddle. While that is wonderful, I still need to perform form level validation, to ensure that when the user submits the form, everything is okay.
What's the best way to do that? Is there a way that I can mark a field as having been validated, so that the form handler can simply walk the fields to see what has been validated or not?
MP.SignUpFormView = Em.View.extend({
submitLogin:function (event) {
// walk through object fields to perform validation here, but how?!
}
});
Edit:
For clarity, I am using Handlebars and binding, not trying to walk DOM objects or the like.
The pattern you're trying to use makes sense in applications that follow a document-scripting pattern, which Ember does not. You can force this work, but you'll find each next step in the application will get harder and harder.
In Ember display is backed by data objects so form fields in an Ember application are bound to a property on some object and as changes are made, the values are updated immediately. You don't even really need a <form> except maybe for styling.
When a user wants to take some action on this object (like persisting it to a server) the application's current state will answer the question "what happens when a user wants to take this action right now?" A user clicking a button here doesn't mean "now serialize the data in the form and do something" it means "I'm done changing the properties of this object and would like to do something else in the application now."
Your handlebars template would look something like this:
{{view Ember.Textfield valueBinding="name"}}
{{view Ember.Textfield valueBinding="age"}}
<button {{action save content}}>Save</button>
And a possible state in your application where this can be handled
Ember.Route.extend({
save: function(router, event){
if (event.context.validate()){
router.transitionTo('someNewState')
}
}
})

Yii - How to call external javascript on every CActiveForm validation?

I would like to make a "preview container" for form values in Yii. (so every time the user finishes entering data, the "preview container" below the form will display them, to let the user knows how the item actually looks like).
To achieve this, the only way is to call a Javascript function to update the "preview container" (using jQuery). The CActiveForm is:
<?php
$form = $this->beginWidget('CActiveForm', array(
'id'=>'item-form',
'enableAjaxValidation'=>true,
));
?>
How do we modify it to call a javascript function each time the fields are validated?
(Note: whenever we switch between the input fields, the fields are validated dues to enableAjaxValidation=>true)
Thanks in advanced.
With jQuery you can define your own listener functions for the fields you want to update, which is probably going to be cleaner than trying to hook into the validation functions.You could monitor onchange or blur or whatever is most appropriate to your data.
The js can be loaded via Yii's registerScript function or, again, whatever is most appropriate for your app. A listener function would normally be loaded on DOM ready, i.e., with the POS_READY attribute for registerScript.
You can search the tutorials as well as this basic tutorial for more info.