Javascript behaves differently when called from custom ribbon button vs onSave - javascript

I'm trying to add versioning functionality to a custom entity, MFAs, and I'm running into a very odd problem. I have a javascript webresource being called from two places: an onSave event on the form, and as the action of a custom ribbon button. Specifically, the onSave event calls captureSave, while the ribbon button calls makeARevision.
When called from the save button/event, everything works as expected; all information, including the new changes, are pulled to a new record and saved there, while the original record is closed without the changes being saved, and without a prompt to save. However, when called via the custom ribbon button, any unsaved changes do not get brought over to the new record, and the old record prompts for saving. Furthermore, even if the user chooses to save the changes to the old record, the changes are not saved, and the form doesn't automatically close.
The following code is the webresource in question. company_MFASaveOrRevise is just an html page that asks the user whether they want to save the record or create a new revision. Any ideas on what's causing the differences or how to resolve them is appreciated.
function captureSave(executionContext) {
if (Xrm.Page.ui.getFormType() != 1 && Xrm.Page.data.entity.getIsDirty()) {
var retVal = showModalDialog(Xrm.Page.context.getServerUrl() + '/Webresources/company_MFASaveOrRevise', null, 'dialogWidth: 300px; dialogHeight: 100px');
if (retVal == "Revise") {
executionContext.getEventArgs().preventDefault();
makeARevision();
}
else if (retVal == "Save") {
}
}
}
function createLookupValue(oldLookup) {
var lookupVal = new Object();
lookupVal.Id = oldLookup.id;
lookupVal.LogicalName = oldLookup.entityName;
lookupVal.Name = oldLookup.Name;
return lookupVal;
}
function makeARevision() {
var revisedMFA = {};
revisedMFA['company_mfaname'] = Xrm.Page.data.entity.attributes.get('company_mfaname').getValue();
revisedMFA['company_mfadate'] = Xrm.Page.data.entity.attributes.get('company_mfadate').getValue();
revisedMFA['company_estimatedliqdate'] = Xrm.Page.data.entity.attributes.get('company_estimatedliqdate').getValue();
revisedMFA['company_actualliqdate'] = Xrm.Page.data.entity.attributes.get('company_actualliqdate').getValue();
revisedMFA['company_mfanumber'] = Xrm.Page.data.entity.attributes.get('company_mfanumber').getValue();
revisedMFA['company_revisionno'] = Xrm.Page.data.entity.attributes.get('company_revisionno') == null ? 0 : Xrm.Page.data.entity.attributes.get('company_revisionno').getValue() + 1;
revisedMFA['company_requester'] = createLookupValue(Xrm.Page.data.entity.attributes.get('company_requester').getValue()[0]);
revisedMFA['company_mfapreviousrev'] = Xrm.Page.data.entity.attributes.get('company_totalmfatodate').getValue();
revisedMFA['company_contract'] = createLookupValue(Xrm.Page.data.entity.attributes.get('company_contract').getValue()[0]);
$.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
datatype: 'json',
url: getODataUrl() + '/' + 'company_mfaSet',
data: JSON.stringify(revisedMFA),
beforeSend: function (XMLHttpRequest) {
//Specifying this header ensures that the results will be returned as JSON.
XMLHttpRequest.setRequestHeader('Accept', 'application/json');
},
success: function (data, textStatus, request) {
Xrm.Utility.openEntityForm("company_mfa", data.d.company_mfaId.toUpperCase());
var attributes = Xrm.Page.data.entity.attributes.get();
for (var i in attributes) {
attributes[i].setSubmitMode('never');
}
Xrm.Page.ui.close();
},
error: function (request, textStatus, errorThrown) {
alert(errorThrown);
//alert("There was an error creating the revision");
}
});
}
Edit: I had debugger; inserted in various places and was using VS2012 debugger, and found that the attributes were being properly set not to submit, but apparently that didn't stop the confirmation dialog from popping up (even though it works when the webresource is called through the save button). Additionally, Xrm.Page.data.entity.attributes.get(attributeName) returns the post-changes values when called during onSave event, but pre-change values when called from the ribbon. I still don't know why or how to fix it though. Is there something else I should look for?

Use F12 to debug your code when being called from the ribbon (just remember since it is in the ribbon, your javascript code will be in a dynamic script / script block).

Related

SAPUI5: How to show a loading dialog box while pushing data to OData Service?

I am building a new SAPUI5 application without pursuing any template approach. What I'm building is just a little form with two fields and a button. AHHhh... "the button".
What about the button? The button has the following code:
<Button text="OK" width="100%" id="__button1" press="insertIntoOData"/>
With that, I expect that when I press the button, the insertIntoOData function is called. And guess what!? It is!
Fantastic!
But the problem is that in the insertIntoOData I want it to show a dialog (which is built with a fragment - check this link) while the OData model handles the insertion of a record. Unfortunately, I haven't managed to get the dialog to be shown. It looks like the insertIntoOData function is called synchronously, and won't show the dialog until the function is done.
When the OData Model finish handling the insertion, a response is processed and the dialog is shown only for a moment because, as you may notice in the following code of insertIntoOData, the navigation is redirected to the master (main) page.
insertIntoOData: function(evt) {
/*
* to prevent namespace issues, reserve 'this' into 'that',
* so the ajax will know who to call inside its scope
*/
var that = this;
//declare the dialog
if (!that._dialog) {
that._dialog = sap.ui.xmlfragment("valac.view.requestloading", null);
that.getView().addDependent(that._dialog);
}
// open dialog
jQuery.sap.syncStyleClass("sapUiSizeCompact", that.getView(), that._dialog);
that._dialog.open();
// get the csrf token from the service url
var csrfToken = this.getCSRFToken("/valacDestination/sap/c4c/odata/v1/c4codata/ValacObjectCollection");
// get the values from the 'form'
var name_var = this.byId("tSubjectInput").getValue();
var description_var = this.byId("tDescriptionArea").getValue();
// create the entry that will be sent with the request
var oEntry = {};
// the description list
oEntry.requestDescription = [];
// the description item that goes inside the list
var entryOfRequestDescription = {};
entryOfRequestDescription.Text = description_var;
oEntry.requestDescription.push(entryOfRequestDescription);
// name is a complex object that needs to be built. Content and language.
oEntry.Name = {};
oEntry.Name.content = name_var;
oEntry.Name.languageCode = "EN";
// fetch the model schema
var oModel = new sap.ui.model.odata.ODataModel("/valacDestination/sap/c4c/odata/v1/c4codata/");
sap.ui.getCore().setModel(oModel);
/* create the entry into the model schema via ajax
* return to the master page if there's a success response
* put a message on the master page.
*/
oModel.create('/ValacObjectCollection', oEntry, null, function(response){
that._dialog.close();
sap.ui.core.UIComponent.getRouterFor(that).navTo("master");
sap.m.MessageToast.show("Object Persisted!", {
duration: 30000000
});
},function(){
that._dialog.close();
sap.m.MessageToast.show("ERROR!", {
duration: 30000000
});
});
}
My question is: How can I show the dialog before the insertIntoOData ends or calls the oModel.create function?
when you enter the insertIntoOData method.
before calling the service set
that._dialog.setBusy(true);
after getting service responce (sucess or error don't matter )set as
that._dialog.setBusy(false);
You can do global busy indicator or component busy indicator, show before oModel.create and hide into the success or error function:
sap.ui.core.BusyIndicator.show(0); <- Parameter is delay time.
sap.ui.core.BusyIndicator.hide(); <- hide
link docs: https://sapui5.hana.ondemand.com/1.44.18/explored.html#/sample/sap.ui.core.sample.BusyIndicator/preview
Only the Dialog show busy.
that._dialog.setBusy(true); <- Show
that._dialog.setBusy(false); <- hide
I've managed to show the busyIndicator.
I rebuilt the insertIntoOData function to be as the following:
insertServiceRequestIntoOData: function(evt) {
var that = this;
var token = null;
var serviceUrl = "URL";
var name_var = this.byId("tSubjectInput").getValue();
var description_var = this.byId("tDescriptionArea").getValue();
var oEntry = {};
/*
* oEntry building process omitted
*/
this.oModel = new sap.ui.model.odata.ODataModel(serviceUrl);
sap.ui.getCore().setModel(this.oModel);
/*
* This is where the magic happens:
* 1) ajax async request to get the token and to show the busy indicator on the screen
* 2) when it's over, make a post to the oData service with the data.
* 3) when it's over, hide the busy indicator and go to the correct page (success or error).
*/
$.ajax({
url: serviceUrl + "/MyCollection";
type: "GET",
async: true,
beforeSend: function(xhr) {
sap.ui.core.BusyIndicator.show(0);
xhr.setRequestHeader("X-CSRF-Token", "Fetch");
},
complete: function(xhr) {
token = xhr.getResponseHeader("X-CSRF-Token");
// begin of odata send
that.oModel.create("/MyCollection", oEntry, null, function(response){
sap.ui.core.BusyIndicator.hide();
sap.ui.core.UIComponent.getRouterFor(that).navTo("insertConfirmation");
that.clearInputs();
},function(){
sap.ui.core.BusyIndicator.hide();
sap.ui.core.UIComponent.getRouterFor(that).navTo("insertErrorConfirmation");
that.clearInputs();
});
}
});
}

Ajax sends duplicate headers

Well I have stumbled upon a weird problem.
First time I send the form the server recieves 1. If I send another without reloading the page it sends 2 exact same posts, if I send it again it sends 3 and so on. If I would to send 9 forms it would send 9 exact same posts on the last.
Here's my code:
$('#AskACounsel .btn-ask-question').bind("click", function (e) {
e.preventDefault();
var textbox = $('#AskACounselQuestion');
var question = textbox.val();
var product = textbox.data('productid');
if (question.length > 0) {
var params = { question: question, productid: product };
var url = '/FAQService/AddQuestion';
$.ajax({
url: url, success: function (result) {
var infoDiv = $('#AskACounselThankYouView .counsel-info').html(result.Message);
var backDiv = $('#AskACounselThankYouView .counsel-footer .btn-return');
if (result.Success) {
textbox.val("");
backDiv.hide();
} else {
backDiv.show();
}
$('#AskACounselDefaultView').hide();
$('#AskACounselThankYouView').show();
},
type: 'POST',
data: params
});
}
});
Its likely that the code you have is passed through many times, i.e. you have a function that has the code and calling it to handle the click event. The rule of thumb is that binding should happen ONLY ONCE, since it's a binding, not just an event handler like "on".
See answer from https://stackoverflow.com/a/8065685/696034
If you want to continue using bind, then unbind before that code through $('#AskACounsel .btn-ask-question').unbind("click"); otherwise, bind the event in the initialization section of your code ONCE.

Delayed submit results in multiple continuous submits

I have the following jQuery code, the point of this code is to create a short time delay, so the AJAX request gets time to execute properly:
$('#form_id').submit(function(e) {
e.preventDefault();
$submit_url = $(this).data('submitUrl');
$submit_url = $submit_url.replace('http://','').replace(window.location.host,'');
if ($(this).data('toBeAjaxSubmitted') == true) {
$.ajax($submit_url, {
type : $(this).attr('method'),
data : $(this).serialize(),
complete : function(data) {
$(this).data('toBeAjaxSubmitted', false);
$('#form_id').submit();
}
});
}
});
What happens is, the form starts off with a submit url that I need to submit to in order for the component to save an entry to the database. But I also need user input to submit directly to a payment gateway URL where the user then makes a payment.
The code above creates the AJAX request, but does not return to normal postback behaviour (via $('#form_id').submit()).
It keeps submitting the form over and over, but never posts to the gateway URL or redirects out.
What am I doing wrong?
The following worked for me after some more debugging:
$('#chronoform_Online_Submission_Step8_Payment').submit(function(e) {
var form = this;
e.preventDefault();
$submit_url = $(this).data('submitUrl');
$submit_url = $submit_url.replace('http://','').replace(window.location.host,'');
if ($(this).data('toBeAjaxSubmitted') == true) {
$.ajax($submit_url, {
type : $(this).attr('method'),
data : $(this).serialize(),
complete : function(data, status) {
}
}).done(function() {
form.submit();
});
}
});
What really put me on the wrong path was that in Chrome's Developer Tools I had the following option enabled 'Disable cache (while DevTools is open)' and this was causing some headaches with inconsistent behaviour between Safari, Firefox (which worked) and Chrome which did not.
What about some fiddling with this approach?
$('#form_id').submit(function(e) {
// closures
var $form = $(this);
var fAjaxComplete = function(data) {
// don't send the ajax again
$form.data('toBeAjaxSubmitted', 'false');
// maybe do some form manipulation with data...
// re-trigger submit
$form.trigger('submit');
};
var oAjaxObject = {
type : $form.attr('method'),
data : $form.serialize(),
complete : fAjaxComplete
};
var sSubmitUrl = $form.data('submitUrl');
// scrub url
sSubmitUrl = sSubmitUrl.replace('http://','').replace(window.location.host,'');
// if ajax needed
if ($form.data('toBeAjaxSubmitted') != 'false') {
// go get ajax
$.ajax(sSubmitUrl, oAjaxObject);
// don't submit, prevent native submit behavior, we are using ajax first!
e.preventDefault();
return false;
}
// if you got here, go ahead and submit
return true;
});

Jquery too many ajax request fired

I have the following code build using jquery. When a user copies and pastes a a youtube url, i am suppose to extract the video id is the getVideoId(str) method in jquery. Using the id, i get the video image picture title and contents.
When the textbox->("#url") has a length more than 10, i will make a ajax request. Thus the ajax request is working. But now i have another problem. The very first time when the textbox has more than 10 characters, there is two ajax request being fired (tested using firebug). Than when the user enters more characters, there are many ajax request fired.
Thus this will slow down the process of the last ajax request. I just want to get the data of the youtube link and show a suggest where the user can add the title and content. It is like how the old facebook video video link is. Anyone has a better suggest in improving the codes?
jQuery(document).ready(
function(){
$("#url").keyup(function() {
var $t1 = $("#url").val();
var $length = $t1.length;
var $data;
$("#title").val($length);
$("#content").val($t1);
if($length==0){
alert('zero value');
return;
}
if($length>10){
$data = $.ajax({
url: '<?php echo $this->Html->url(array("action" => "retrieveVideoFeed"));?>',
dataType: "json",
data: {
vid: getVideoId($t1)
},
success: function(data) {
alert('success in getting data');
}
});
return;
}
});
function getVideoId(str) {
var urlRegex = /(http|https):\/\/(\w+:{0,1}\w*#)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%#!\-\/]))?/;
if (urlRegex.test(str) && str.indexOf('v=') != -1)
{
return str.split('v=')[1].substr(0, 11); // get 11-char youtube video id
} else if (str.length == 11) {
return str;
}
return null;
}
}
);
You could cache the calls and use blur event and not keyup: you are firing a lot of AJAX call because keyup() fires an event each time a key is pressed, you should use blur that fires an event when an input loses focus.
If you cache the calls in an object you can avoid a lot of repeated calls
var cacheUrl = {};
$("#url").blur(function() {
var $t1 = $("#url").val();
var $length = $t1.length;
var $data;
$("#title").val($length);
$("#content").val($t1);
if($length==0){
alert('zero value');
return;
}
if(cacheUrls[$t1] !== undefined && $length>10){
$data = $.ajax({
url: '<?php echo $this->Html->url(array("action" => "retrieveVideoFeed"));?>',
dataType: "json",
data: {
vid: getVideoId($t1)
},
success: function(data) {
//save the data to avoid a future call
cacheUrls[$t1] = data;
alert('success in getting data');
}
});
return;
}elseif ($length>10){
//you already have the data in cacheUrls[$t1]
}
});
EDIT if you want to use the submit key to start the search you could trigger the blur event when you press enter like this:
$("#url").keypress(function(e){
if(e.which == 13){
$(this).blur();
return false;
}
});
I think many ajax requests are fired because you are using $("#url").keyup(function()
so that for every key event in url input the particular funciton will exectue.So, as per i know better to use focusout method instead of keyup.
If you stay with the keyup-Event you maybe want to use an ajaxmanager-plugin for jQuery which can manage queues or limits the number of simultaneous requests.
$.manageAjax.create('myAjaxManager', {
queue: true,
cacheResponse: false,
maxRequests: 1,
queue: 'clear'
});
....
if($length>10){
$data = $.manageAjax.add({ ...
This will prevent having alot of ajaxrequests active at the same time when the user is typing. As soon as he stops the request will not aborted and the results will show up.

Chrome doesn't displays the dynamic css propery change by Jquery before Ajax sync call

I have a tricky problem with Google Chrome Browser.
I have the folowing HTML node:
<div class="result-req-chat pointer float-right" onclick="chat.addUser(this/*, other vars*/)" ><img src="/images/profile_icon_4.png" alt="" /></div>
On the click event it triggers the chat object's method
this.addUser = function(trigger_node, id, is_silent, session, show_block_message){
if(trigger_node){
this.bk_trigger_node.html = trigger_node.innerHTML;
this.bk_trigger_node.cn = trigger_node.className;
trigger_node.innerHTML = '';
jQuery(trigger_node).addClass("loader");
jQuery(trigger_node).removeClass("bpurple");
jQuery(trigger_node).removeClass("bgray");
jQuery(trigger_node).removeClass("button");
}
//alert('if this is executed then it displays the previous changes of the node');
if(trigger_node.innerHTML == ''){
this.addUserToChat(id, is_silent, session, show_block_message);
}
if(trigger_node){
trigger_node.innerHTML = this.bk_trigger_node.html;
trigger_node.className =this.bk_trigger_node.cn;
}
}
addUserToChat():
this.addUserToChat = function (id, is_silent, session, show_block_message){
var response = this.chat_tabs.addTab(id, null);
if(response.error){
callUrl("/me/chat/remove-session/id/"+id);
this.chat_tabs.removeTab(id);
if(show_block_message) alert(response.message);
}else{
this.createTabsBar();
if(!is_silent){
this.switchTab(id);
this.resetContainer(is_silent);
}
if(id == this.chat_tabs.active_tab){
this.active_chat_obj.refresh(session);
}
if(this.closed){
if(this.stop_check){
return;
}
this.resetContainer();
this.switchTab(id);
}
callUrl("/me/chat/add-session/id/"+id);
}
}
chat_tabs.addTab():
// creates and adds the a tab
this.addTab = function(id,name,user_data,session){
var exists = this.getTab(id);
if(!exists){
if(session){
var user_session_id = session.id;
var user_session_data = session.data;
}else{
var session = this.createSession(id);
if(session.error){
return session;
}
var user_session_id = session.id;
var user_session_data = session.data;
}
if(name){
var user_name = name;
}else{
var user_name = this.getName(id);
}
if(user_data){
var user_data = user_data;
}else{
var user_data = this.getData(id);
}
var ob = new Object({
user_id: id,
user_name: user_name,
user_data: user_data,
user_session_id: user_session_id,
user_session_data: user_session_data,
has_new:false,
chat_screen: new ChatScreen(session, id, user_name, user_data, this.main_user_id, this.main_user_photo)
});
this.chat_users.push(ob);
return ob;
}else{
return exists;
}
}
callUrl():
function getUrl(url){
return jQuery.ajax({ type: 'GET', url: url, async: false }).responseText;
}
The point is that the method addUserToChat() contains a syncronous Ajax call.
The problem with Chrome is that the trigger_node changes aren't displayed. If you watch with the built-in JS debuger then everithing goes ok ( even with displaying ) .Also if you uncomment the alert.
It runs on Mozilla ( latest version ).Also the Crome is the latest version.
I can observe that in the time that it waits for the ajax response, the page is unresponsive to events like hovers, tips etc.
Do you have any suggestions for this? How can I implement a workarround method?
Synchronous Ajax calls are bad practice! They stop the browser for the entire duration and fool the user into thinking something crashed. You really should change this.
To your question why you don't see the latest DOM changes:
When you change something in JavaScript the browser will not immediately change the DOM, because painting a ui element is far more expensive than painting a dozen. So modern browsers will try to change the DOM as lazy as possible.
There are, apart from performance other upsides, like
$('p').hide();
can hide all p elements at the same time although jQuery will select each and than change the css.
I cant't give you any hind of a workaround without understanding your code better, sorry. Thanks!
UPDATE:
After reading your code, I would think about adding some closures to the application. A basic concept of javascript is that functions are first class types. I personally think, that your program flow is less than ideal, and this is the area of improvement. the calls to call url should look something like this:
var callUrl = function(url, callback, interactionStoped) {
if(typeof interactionStoped != 'undefined' && interactionStoped == true) {
//add code to display some loading animation
}
jQuery.ajax({ type: 'GET', url: url, success: function(data) {
callback(data);
//remove loading animation here
} });
}
as a start. Then you refactor your getUrl calls.
Funny thing is in your code example you never use the response, so I don't know what your app is waiting for. Assuming it is something important you must handle the response always in your callback.
Try looking at your app as if it were a tree. A Parent Function or Object will call itself some child functions that handle different tasks, wich themselves will invoke other functions. Build methods that are small and do only one thing on a really small set of data / parameters.
I can't rewrite your complete code, but I hope this helps anyway.
When do you try to display/fill the trigger_node variable?
It seems a bit like you aren't executing this action in the callback-function of the AJAX-request. Note that if the request is still running while you try to check for trigger_node, it won't of course show your changes.

Categories

Resources