Control flow not reaching a line of code - javascript

I have a simple function to submit a POST request to an ASP.NET MVC url.
The control does not even reach the last line of code where the form is submitted. Please help. Here's the function I invoke at the click of a hyperlink.
function submitNewAccountInfo() {
debugger;
var newAccountInfo =
{
FullName: $("#NewUserAccountInfo_FullName").val(),
Email: $("#NewUserAccountInfo_Email").val(),
PasswordHash: md5($("#NewUserAccountInfo_Password").val())
};
debugger;
// The control does not even come here. What am I doing wrong?
$("#frmCreateNewAccount").submit(newAccountInfo);
}
Create my account

I fixed my problem. There were a couple of issues with my code:
I wasn't using jQuery to bind/wire up event handlers with events. As a result, the short-cut onclick that I took was attaching an event handler and not an event listener.
This meant that I had to handle all browser incompatibilities and also get hold of the event object to prevent its default behavior, none of which I was doing and all of which jQuery makes it very easy to do.
I changed my code to bind/wire up an event listener using jQuery and my code is now working. Here's the working code.
$(document).ready(function () {
$("#lnkCreateMyAccount").click(submitNewAccountInfo);
});
function submitNewAccountInfo(event) {
event.preventDefault();
var newAccountInfo =
{
FullName: $("#NewUserAccountInfo_FullName").val(),
Email: $("#NewUserAccountInfo_Email").val(),
PasswordHash: $("#NewUserAccountInfo_Password").val()
};
$("#frmCreateNewAccount").submit(newAccountInfo);
}

Related

How to get this form to submit only when it should

Probably an idiotic question but I find this really tricky:
I am trying to make a form submit only when it specifically should.
The script below executes every time I submit any other form in my page.
How can I make it not execute, unless it is called for?
$('#nurturing_pop_up_form').validate({
rules: {
emailaddress: {
required: true,
email: true
},
board_meeting: {
required: {
depends: function () {
return $('input[name=in_12_months]').is(':checked')==false && $('input[name=in_6_months]').is(':checked')==false
}
}
}
},
submitHandler: function(form) {
var url_remind = 'http://example.com';
var data_remind = $('#nurturing_pop_up_form').serializeArray();
$.ajax({
type: "POST",
url: url_remind,
data: data_remind,
success: function(){
$('.nurturing_pop_up').fadeOut();
}
});
}
});
Should I add something like this?
$('#nurturing_pop_up_form').submit(function(e){
e.preventDefault();
$('#nurturing_pop_up_form').validate({
rules: {
//the rest like above
Help is very very appreciated!
I am trying to make a form submit only when it specifically should.
This process is handled automatically by jQuery Validate. You should not be doing anything special to force this.
The script below executes every time I submit any other form in my page.
The script "below", .validate({...}), is simply the plugin's initialization routine. Within the code you've shown, you are only initializing ONE form with id="nurturing_pop_up_form". Other forms on the page would be completely unaffected. Perhaps you have invalid HTML, additional instances of .validate(), other submit handlers, or some erroneous code you have not shown us.
How can I make it not execute, unless it is called for?
I think your question is based on an erroneous assumption of what's happening. .validate() is only supposed to be called ONCE on page load (DOM ready handler) to initialize the plugin on your form. The plugin then automatically captures the click, validates the data, and handles the submit.
Should I add something like this?
$('#nurturing_pop_up_form').submit(function(e){
e.preventDefault();
$('#nurturing_pop_up_form').validate({...
Absolutely not. You should never put .validate() within a .submit() handler for the same form. It's completely unnecessary, delays the plugin's initialization, and interferes with the built-in submit handler.
Nothing you've shown can explain how/why other forms would be affected.

Telerik Kendo UI grid loses custom command event handler after persisting (and restoring) its state

I have isolated the issue, see and try the full source here.
Steps to reproduce:
Press Ctrl+Enter to run the snippet
Click on 'Say Hello' custom command button, and check if the event
handler runs
Click on top left 'Save State' button
Click on 'Load State' button, and restore the previous state.
Now click again on 'Say Hello' button and demonstrate the event handle will not run, instead something weird is happening.
Notes: Please do not search for the solution around the localStorage. The issue can be reproduced by using different server side state persisting solution. (as my original app does)
Any idea where to patch? ... or workaround?
Hopefully this will help you out.
http://dojo.telerik.com/EDUCO/4
I have added the following piece of code for you:
dataBound: function (e) {
$(".k-grid-SayHello").on('click', function (a) {
console.log(e);
a.preventDefault();
alert('Hello');
});
},
When the rebind occurs I suspect that it is losing the connection to the event handler so all I have done if looked for the button based on it's class name and reattached it.
Obviously you can adapt the solution to meet your needs but this is something I do for my projects when I need to "invoke" custom actions on buttons/ dynamically create things on the fly.
Any issues let me know.
To keep function references after calling grid.setOptions()
I added the function references back to the deserialized configuration object before passing it to the setOptions method.
( http://docs.telerik.com/kendo-ui/api/javascript/ui/grid#methods-setOptions )
$(document).ready(function () {
var grid = $("#myGrid").data("kendoGrid");
var originalOptions = grid.getOptions();
var savedOptions = JSON.parse(localStorage["myGrid-options"]);
if (savedOptions) {
var detaylarFunc = originalOptions.columns[3].command[0].click;
savedOptions.columns[3].command[0].click = detaylarFunc;
grid.setOptions(savedOptions);
} else {
grid.dataSource.read();
}
});
//Custom command
function Detaylar(e) {
e.preventDefault();
var grid = $("#myGrid").data("kendoGrid");
options = grid.getOptions();
localStorage["myGrid-options"] = kendo.stringify(grid.getOptions());
}

SuccessCallback firing immediately in Xrm.Page.data.save

I am writing javascript code to change the form of a entity in Dynamics CRM based on the value of a field on each form.
To change the form, the user has to change the value of the field.
Then during the onChange event, my js comes in, triggers saving, has to wait for the result and then change the form. (If you save and change at the same time, there is still a window shown asking the user to confirm leaving unsaved changes)
Now there should be a way to do that:
Xrm.Page.data.save(saveOptions).then(successCallback, errorCallback)
as it is described on msdn:
Saves the record asynchronously with the option to set callback functions to be executed after the save operation is completed.
I am using it as such:
var campaignType = Xrm.Page.getAttribute('typecode').getValue();
if (xxx.Forms.hasOwnProperty(campaignType)) {
Xrm.Page.data.save().then(function () { xxx.redirectToForm(xxx.Forms[campaignType]); }, null);
But the form change is still triggered immediately during the save.
What am I doing wrong?
I faced a similar problem while trying to update the process bar.
Xrm.Page.data.save().then
(function () {
window.location.reload(true);
},
function () {
windows.alert("broken");
}
);
I strongly suggest you to try to apply the logic on a vanilla CRM, for me what was breaking the logic was a third party component called N52 Rules, their code was interfering with the callback forcing the refresh of the page before the save event. Your code seems correct.
Hey the Save and Refresh Calls are Asynchronous! that is why it hits the success handler immediately.
What you can try is using SDK.REST.js file for CRM
function updateFunction(entityId) {
var campaignType = Xrm.Page.getAttribute('typecode').getValue();
if (xxx.Forms.hasOwnProperty(campaignType)) {
var entity= {};
entity.typecode= campaignType;
SDK.REST.updateRecord(
entityId,
entity,
entityName, //"Account"
function () {
writeMessage("The record changes were saved");
xxx.redirectToForm(xxx.Forms[campaignType]);
},
null
);
}
}
https://msdn.microsoft.com/en-us/library/gg334427(v=crm.7).aspx
Here you can call updateFunction given above onChange and in the onSuccess handler you can try calling the form you want to call. I haven't tried it the way you want, but let me know if it works.
check this link out as well
https://msdn.microsoft.com/en-us/library/gg334720.aspx#BKMK_entityOnSave

Which of these event handlers should work to trigger a custom function on window close?

Okay, I have the data pipeline working fine, If I map the event handler to an input click trigger it sends the data via Jquery/Ajax to the PHP processing file and that writes the data to the SQL db.
However, none of the methods I have tried to trigger the Ajax send on window/page close seem to be working. I do not want to return an alert box, however all of the examples I have found online seem to demonstrate only the use of the onbeforeunload, beforeunload, and unload events to display an alert box. They also say you can launch a custom event, but I have not found a reliable example of such an event.
What am I doing wrong guys? Here is the code. All of my attempted triggers are near the top commented out except for the latest, so you guys can see what I have already tried.
var formData;
$(document).ready(function() {
//$("#driver").click(function() {
//$('a[rel!=ext]').click(function() { window.onbeforeunload = null; });
//$('form').submit(function() { window.onbeforeunload = null; });
//window.onbeforeunload = function() {
//jQuery(window).bind("beforeunload",function() {
//$(window).unload(function() {
$(window).bind("beforeunload", function() {
var date=new Date();
var formData = $("#testform :input[id!='card-type'][id!='paymentSelection_0']"+
"[id!='ccSelectedRadio'][id!='card-number'][id!='card-exp-month'][id!='card-exp-year'][id!='card-cvv'][id!='billing-first-name']"+
"[id!='billing-last-name'][id!='billing-company'][id!='billing-address1'][id!='billing-address2'][id!='billing-city']"+
"[id!='billing-state'][id!='billing-zip'][id!='billing-phone'][id!='billing-country'][id!='useShippingRadio'][id!='useBillingRadio']"+
"[id!='ppSelectedRadio'][name!='miscDS.shopperEmailAddress_ymixval'][name!='miscDS.shopperEmailAddress_ymixlabel']"+
"[name!='miscDS.shopperEmailAddress_secname'][name!='paymentSelectionDS.paymentSelection_ROW0_paymentPPSelected']").serializeArray();
$.post("jquery/process.php",
{
mydata: formData,
orderSubTotal: orderSubTotal,
orderTotal: orderTotal,
numOfItems: numOfItems,
items: items,
ids: ids,
codes: codes,
qtys: qtys,
price: price,
orderTax: orderTax,
orderShipping: orderShipping,
appliedPromoIdList: appliedPromoIdList,
coupon: coupon,
storeId: storeId,
activeShipPromotionCount: activeShipPromotionCount,
itemImages: itemImages,
date: date
}
);
});
});
Any method of attachment you've shown here is fine, as far as attaching events goes. The problem isn't your attachment approach, per se, but rather that your function performs an asynchronous task which takes "too long" to finish before the situation changes.
When a page unloads, any pending AJAX requests are cancelled. Because ajax requests are asynchronous by default, your request won't have a chance to even connect to the server before the browser cancels it.
The only route, for this use case, is to use a synchronous request. This may cause an undesired effect, though: while your request is pending, the browser interface will appear and behave as though it is "locked".
That is why an alert WILL work, because it is by nature a synchronous, "blocking" situation. The alert box effectively stops the entire browser UI to wait for input.
See also: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Synchronous_and_Asynchronous_Requests

jquery, binding order/wait for callback

I wrote a jquery plugin for validating forms. It bounds itself to the $('element').Submit event to trigger the validation (the bind is inside the plugin). Somehow like this:
// pseudocode
jquery.rdy {
$('form').validate(); //binding the plugin
}
Inside of the validate plug I bind the validation to the submit
//pseudocode
[...]
$().submit(function () {
validating... //returning true/false
if (false) {
return false //prevent submit form
}
}
[...]
So and now my question is how can I bind (in other js scripts for example) other stuff to the submit but just if a validation is done.
so like this
$('form').submit(function () {
if (validate plugin was executed) {
//do stuff like check if validation was returning a true and now do something else
}
}
Hopefully I descriped it right ...my english is not the best but I tryed to be as concrete s possible (and i hope, pseudocode is a right approach as well)
// EDIT: make the problem more concrete:
I'm trying to figure out a way to solve the following problem: (its very out of the context but the problem is exactly there..)
I have a submit event which is doing something depending on some code triggered in a another decleration.
$('element').submit(function () {
if ($(this).hasClass('foo')) {
// do something
}
});
$('element').submit(function () {
$(this).addClass('foo');
});
And now the first function is doing nothing cause it has been triggered before the second one. Is there a clean way to solve this. Maybe I need a timeout event (even I hate them)?
If you are using jQuery.Validate (which it looks like you are with the .validate() syntax), you can just call the isValid() method:
if (validate plugin was executed) {
can then be
if ($('form').isValid()) {
You can bind more functions to the form element with custom names.
$('form').bind('after_validation',function(){ console.log('hello'); });
And trigger them in your submit form function when you need it:
$('form').trigger('after_validation');
http://api.jquery.com/trigger/
Update:
You cannot change the order of your bound submit events without removing them .unbind('submit') and re-applying in the correct order. What you can do is use custom binds (see above) and trigger them exactly when you need it - like.. inside the submit function.
$('form').submit(function () {
//run validation
$('form').trigger('validation');
//did it pass validation?
if($(this).data('invalid')){
console.log('did not pass validation');
return false;
}
//passed validation - submit the form
return true;
});
//add validation to the "form"
$('form').bind('validation',function () {
//do validation on form...
if(false){
$(this).data('invalid',true);
}
});
//add another validator to the form, etc.
$('form').bind('validation',func...
Im using .data() to store variables to the 'form' element so you can access them down the chain.
This is the basis of what you need and can be applied to a custom jquery plugin to form custom named functions. eg. $().validator().
http://docs.jquery.com/Plugins/Authoring

Categories