I have a setCookie function which fires correctly in more instances but doesn't seem to fire with this very specific instance.
The setCookie function works correctly within the HTML file, but fails the fire from an external app.js file even though the parent storeSelection function works fine. I've tested by placing a console.log message within setCookie and can confirm doesn't run when triggered from $('.store-select').change
index.html
function getCookie() {
//cookie function
}
function setCookie() {
//cookie function
}
function storeSelection(region) {
setCookie("geo-location-v3", region, 365);
});
var region = getCookie('geo-location-v3');
if (region == "") {
if (location == 'us') {
region = 'us';
} else {
region = 'au';
}
//This CORRECTLY fires storeSelection function which fires setCookie function and saves the cookie
storeSelection(region);
}
In an external javascript file I have:
app.js:
$('.store-select').change(function(){
region = 'au'
//This DOESNT fire setCookie function
setCookie("geo-location-v3", region, 365);
//This CORRECTLY fires storeSelection function, but DOESNT fire the setCookie function within storeSelection
storeSelection(region)
});
Related
Here is a quick example that should (but it doesn't work for some reason).
function clearSave()
{
var c = confirm("Are you sure you want to reset the current game?");
if (c==true)
{
localStorage.setItem("saved","false");
location.reload();
}
}
function save()
{
localStorage.setItem("saved","true");
setTimeout(save,1000);
}
function load()
{
if (localStorage.getItem("saved") == "true")
{
alert("Game Loaded");
}
else {
save();
}
}
When the page loads the load function is called. And when the user clicks a button to reset stuff the clearSave function is called.
But after the page is reloaded after the clearSave function is called the alert shows, meaning that the "saved" item is set to "true" somehow.
Any clues?
setTimeout(save,1000);
The above code is causing the error, you need to use some other strategy based on your needs
function save()
{
localStorage.setItem("saved","true");
//Below line needs to be updated
setTimeout(save,1000);
}
Essentially what I need is to run some JavaScript after a record has been saved. This will pick up a guid from a field which has been populated by a plugin. My code looks like;
Xrm.Page.data.entity.save();
var newguid = Xrm.Page.getAttribute("new_copyguid").getValue();
Xrm.Utility.openEntityForm("new_myentity", newguid);
The problem is the code runs past the call to save() and continues executing before a plugin has populated the "new_copyguid" field. Is there a way to wait for the plugin to complete before continuing with the javascript? I have tried AddOnSave() without success. Any javascript callback seems to execute before the plugin finishes as well. The plugin is set to run synchronously.
I am performing this javascript from a button on the form. The button sets a field value and then saves the record, triggering the plugin. The button is a "Copy Entity" button which creates a clone. I need to open this new record in the browser.
I have read that this does not work either, as it happens before the save;
Xrm.Page.data.refresh(save).then(successCallback, errorCallback);
Any pointers would be great!
I think you'll have to run your logic in the OnLoad section. The save should force a refresh and your onload logic will run again. You'll need to do some check to see if the modified on date is within a certain time frame.
Other option is you perform the update manually through a rest call or Soap call, then you can read the value from the plugin in another call.
You can just wait for some seconds by putting this code.
function YourFunction()
{
Xrm.Page.data.entity.save();
OpenForm();
}
Its a new function.
function OpenForm()
{
setTimeout(function () {
var newguid = Xrm.Page.getAttribute("new_copyguid").getValue();
Xrm.Utility.openEntityForm("new_myentity", newguid);
}, 3000);
}
Try this:
function onPageLoad() {
var formType = Xrm.Page.ui.getFormType();
if (formType == 0 || formType == 1) { // 0 = Undefined, 1 = Create
// If form is in Create Mode then
if (Xrm.Page.data != null && Xrm.Page.data.entity != null) {
Xrm.Page.data.entity.addOnSave(onSaveDoThis);
}
}
}
function onSaveDoThis() {
setTimeout(onFormSaveSuccess, 300);
}
function onFormSaveSuccess() {
var newguid = Xrm.Page.getAttribute("new_copyguid").getValue();
if (newguid == "") {
onSaveDoThis();
} else {
// Don't need to trigger the function onSaveDoThis anymore
Xrm.Page.data.entity.removeOnSave(onSaveDoThis);
Xrm.Utility.openEntityForm("new_myentity", newguid);
}
}
Try this:
function OpenForm()
{
setTimeout(function () {
var newguid = Xrm.Page.getAttribute("new_copyguid").getValue();
Xrm.Utility.openEntityForm("new_myentity", newguid);
}, 3000);
}
I have an ajax call in my javascript that returns and loads a partial view into a div. This function used to work but then all the sudden it stopped. I do not think I changed any code or anything that would cause issue but obviously something is going on. The Ajax call will work on the first time when you click on the button in which it is called but never again until you reload the page. I have tried adding more parameters and moving the javascript around but it still did not work. Is there any reason why this could happen?
I have tried moving the javascript out of the onOpen event and the same thing still happens. I have also put an alert call to make sure it is getting to the success call and the alert is called. I have also installed fiddler to check the call and the call is never made except on the first click of the button. This is a very frustrating error and all help is much appreciated.
Here is my Javascript:
#section scripts
{
<script type="text/javascript">
$(document).ready(function () {
$("#assets-button").on("click", function ()
{
$('#assets-container').bPopup(
{
modal: true,
onOpen: function () {
$.ajax({
type: 'GET',
url: '#Url.Action("EmployeeAssets", "Employee",new { id = Model.ID, empNo = Model.EmployeeNumber, username = Model.UserName })',
success: function (data) {
$('#assets-container').html(data);
}
});
},
onClose: function () {
var f = $('#assets-container').children('form');
var serializedForm = f.serialize();
var action = '#Url.Action("EmployeeAssets","Employee",new {empNo = Model.EmployeeNumber})';
$.post(action, serializedForm);
}
});
});
});
</script>
}
Here is the action that I am trying to call:
[HttpGet]
public ActionResult EmployeeAssets(int id, int empNo, string username = null)
{
var assets = _employeeDb.EmployeeAssets.FirstOrDefault(e => e.EmpNo == empNo);
if (assets == null)
{
var firstOrDefault = _employeeDb.EmployeeMasters.FirstOrDefault(e => e.EmployeeNumber == empNo);
if (firstOrDefault != null)
{
username = firstOrDefault.UserName;
}
var newasset = new EmployeeAsset()
{
EmpNo = empNo,
UserName = username
};
_employeeDb.EmployeeAssets.Add(newasset);
_employeeDb.SaveChanges();
assets = newasset;
}
return PartialView(assets);
}
You may try using the cache property of the settings object you are passing to the AJAX call. According to the jQuery documentation for .ajax the default for cache is set to true, so I wonder whether your browser is accessing a cached copy of the result after the first request. Looks like you could also set the dataType, and that will default the cache back to false.
Also, I would suggest putting your alert inside of the onOpen event handler in addition to the success handler just to be sure that's also being called. So that may help you debug a bit further.
I have a series of buttons that execute different functions when clicked. The function checks whether the user is logged in, and if so proceeds, if not it displays an overlay with ability to log in/create account.
What I want to do is re-execute the button click after log-in, without the user having to reclick it.
I have it working at the moment, but I'm pretty sure that what I'm doing isn't best practice, so looking for advice on how I can improve...
Here's what I'm doing: setting a global variable "pending_request" that stores the function to be re-run and in the success part of the log-in ajax request calling "eval(pending_request)"
Example of one of the buttons:
jQuery('#maybe_button').click(function() {
pending_request = "jQuery('#maybe_button').click()"
var loggedin = get_login_status();
if (loggedin == true) {
rec_status("maybe");
}
});
.
success: function(data) {
if(data === "User not found"){
alert("Email or Password incorrect, please try again");
}else{
document.getElementById('loginscreen').style.display = 'none';
document.getElementById('locationover').style.display = 'none';
eval(pending_request);
pending_request = "";
}
}
Register a function to handle the click and then invoke that func directly without eval().
jQuery('#maybe_button').on('click', myFunction)
This executes myFunction when the button is clicked. Now you can "re-run" the function code every time you need it with myFunction().
And btw since you are using jQuery you can do $('#loginscreen').hide() where $ is an alias for jQuery that's auto defined.
EDIT
Please, take a look at the following code:
var pressedButton = null;
$('button1').on('click', function() {
if (!isLoggedIn()) {
pressedButton = $(this);
return;
}
// ...
});
And, in your success handler:
success: function() {
// ...
if (pressedButton) pressedButton.trigger('click');
// ...
}
I am writing a short application for exporting events to Google calendar. (Events are obtained from code processing information from my website.) However, when I click the button, the script I wrote is giving me a strange error. The error I get the first time I click the button is: Uncaught TypeError: Cannot call method 'setApiKey' of undefined. However, the second time I click the button without refreshing the page, the error disappears and the code runs perfectly.
Here is my code, as you can see I defined the api key before setting it:
var exportCalendarToGoogle = function() {
var clientId = '38247913478902437.google#user...';
var scope = 'https://www.googleapis.com/auth/calendar';
var apiKey = 'JDKLSFDIOP109321403AJSL';
var withGApi = function() {
gapi.client.setApiKey(apiKey);
gapi.auth.init(checkAuth);
}
var checkAuth = function() {
gapi.auth.authorize({client_id: clientId, scope: scope, immediate: false}, handleAuthResult);
}
var handleAuthResult = function(authResult) {
if(authResult) {
gapi.client.load("calendar", "v3", exportCalendar);
} else {
alert("Authentication failed: please enter correct login information.");
}
}
//functions to format the calendar json input to Google calendar...
Sounds like gapi has not been fully loaded
http://code.google.com/p/google-api-javascript-client/wiki/GettingStarted
There are two callbacks:
1) In the URL to load the gapi code:
<script src="https://apis.google.com/js/client.js?onload=handleClientLoad"></script>
2) You can also supply a callback function that will let you know when a specific API has loaded:
gapi.client.load('plus', 'v1', function() { console.log('loaded.'); });
I think your problem is 1)