jQuery trigger function from code loaded by append - javascript

Is there anyway to call a function or trigger an event from html loaded from an append() call? I have a tag It is filled when a user licks on a list of things like this. in my index.html I have something like this:
function doThis(someData) {
$.get("/url/"+someData, function(htmlFromServer) {
$("#something").append(htmlFromServer);
});
}
function doSomething(moreData) {
alert(moreData);
}
I want to be able to do something like this in the returned html
<div>
<p>This is an important message</p>
<script>
doSomething("this message is different for each page");
</script>
</div>
I want to be able to call one function, but depending on what is returned, I alert a different message. I want the front end to call one endpoint, but what happens next is dynamic. I don't want to do a huge if block in my doThis(), or worse, a function for each possibility that "someData" may have.

You could pass a function to doThis. You also probably meant to concatenate the someData.
function doThis(someData, cb) {
$.get("/url/" + someData, function(htmlFromServer) {
$("#something").append(htmlFromServer);
cb()
});
}
doThis('somepath', () => console.log('append successful'));

I got this to work by defining all my functions in a javascript file and import like usual.
I then make a decision on the back end that all of the possible html that is returned by the jQuery get() call, has a hidden form field with the id of "x" and the value being the function name I want to call after the .append(htmlFromServer) is done.
So i have this function in a .js file defined int the head as usual. I then do this:
$.get("/url/"+someData, function(htmlFromServer) {
$("#myDiv").append(htmlFromServer).append(function() {
var functionToCall = $("#x").val(); // x is the id of the element
window[functionToCall]();
});
}
And I now have a generic way of handling different data depending on the server response without a big if block.

Related

Ajax call in "for" loops skips odd/even iterations

If I am here asking it is because we are stuck on something that we do not know how to solve. I must admit, we already searched in StackOverflow and search engines about a solution.. but we didn't manage to implement it / solve the problem.
I am trying to create a JavaScript function that:
detects in my html page all the occurrences of an html tag: <alias>
replaces its content with the result of an Ajax call (sending the
content of the tag to the Ajax.php page) + localStorage management
at the end unwraps it from <alias> tag and leaves the content returned from ajax call
the only problem is that in both cases it skips some iterations.
We have made some researches and it seems that the "problem" is that Ajax is asynchronous, so it does not wait for the response before going on with the process. We even saw that "async: false" is not a good solution.
I leave the part of my script that is interested with some brief descriptions
// includes an icon in the page to display the correct change
function multilingual(msg,i) {
// code
}
// function to make an ajax call or a "cache call" if value is in localStorage for a variable
function sendRequest(o) {
console.log(o.variab+': running sendRequest function');
// check if value for that variable is stored and if stored for more than 1 hour
if(window.localStorage && window.localStorage.getItem(o.variab) && window.localStorage.getItem(o.variab+'_exp') > +new Date - 60*60*1000) {
console.log(o.variab+': value from localStorage');
// replace <alias> content with cached value
var cached = window.localStorage.getItem(o.variab);
elements[o.counter].innerHTML = cached;
// including icon for multilingual post
console.log(o.variab+': calling multilingual function');
multilingual(window.localStorage.getItem(o.variab),o.counter);
} else {
console.log(o.variab+': starting ajax call');
// not stored yet or older than a month
console.log('variable='+o.variab+'&api_key='+o.api_key+'&lang='+o.language);
$.ajax({
type: 'POST',
url: my_ajax_url,
data: 'variable='+o.variab+'&api_key='+o.api_key+'&lang='+o.language,
success: function(msg){
// ajax call, storing new value and expiration + replace <alias> inner html with new value
window.localStorage.setItem(o.variab, msg);
var content = window.localStorage.getItem(o.variab);
window.localStorage.setItem(o.variab+'_exp', +new Date);
console.log(o.variab+': replacement from ajax call');
elements[o.counter].innerHTML = content;
// including icon for multilingual post
console.log(o.variab+': calling multilingual function');
multilingual(msg,o.counter);
},
error: function(msg){
console.warn('an error occured during ajax call');
}
});
}
};
// loop for each <alias> element found
//initial settings
var elements = document.body.getElementsByTagName('alias'),
elem_n = elements.length,
counter = 0;
var i = 0;
for(; i < elem_n;i++) {
var flag = 0;
console.info('var i='+i+' - Now working on '+elements[i].innerHTML);
sendRequest({
variab : elements[i].innerHTML,
api_key : settings.api_key,
language : default_lang,
counter : i
});
$(elements[i]).contents().unwrap().parent();
console.log(elements[i].innerHTML+': wrap removed');
}
I hope that some of you may provide me some valid solutions and/or examples, because we are stuck on this problem :(
From our test, when the value is from cache, the 1st/3rd/5th ... values are replaced correctly
when the value is from ajax the 2nd/4th .. values are replaced
Thanks in advance for your help :)
Your elements array is a live NodeList. When you unwrap things in those <alias> tags, the element disappears from the list. So, you're looking at element 0, and you do the ajax call, and then you get rid of the <alias> tag around the contents. At that instant, element[0] becomes what used to be element[1]. However, your loop increments i, so you skip the new element[0].
There's no reason to use .getElementsByTagName() anyway; you're using jQuery, so use it consistently:
var elements = $("alias");
That'll give you a jQuery object that will (mostly) work like an array, so the rest of your code won't have to change much, if at all.
To solve issues like this in the past, I've done something like the code below, you actually send the target along with the function running the AJAX call, and don't use any global variables because those may change as the for loop runs. Try passing in everything you'll use in the parameters of the function, including the target like I've done:
function loadContent(target, info) {
//ajax call
//on success replace target with new data;
}
$('alias').each(function(){
loadContent($(this), info)
});

How to run a long script and send constant feedback to an html dialog

In a Google Spreadsheet, I have a long script that permorms many actions in steps, like:
function MyLongScript()
{
var Results1 = Action1();
//send feedback 1
var Results2 = Action2(Results1);
//send feedback 2
var Results3 = Action3(Results2);
//send feedback 3
//end code
}
And I want to show the users a dialog box that tells them that script is running and updates each step of the scritp, like "Action1 complete", ..., "Action2 complete" and so on.
So, I have the HTML interface which contains some table rows with these steps. The question is: how do I make the dialog see that the code performed a certain step?
Right now I'm trying to start the code from the dialog after it loads:
$(function() {
google.script.run
.withSuccessHandler(MainCodeSuccess)
.withFailureHandler(MainCodeFailure)
.MyLongScript();
}
And the dialog is called with the UI and HtmlService:
function CallDialog()
{
var ui = HtmlService.createTemplateFromFile('FeedbackWindow')
.evaluate()
.setWidth(300)
.setHeight(500);
SpreadsheetApp.getUi().showModalDialog(ui, "Dialog Title");
}
What I need is either a getStatus() in the dialog scritp or a sendStatus() in the server script.
What is the best way of achieving this?
You can run multiple google.script.run calls to the server simultaneously. You can't have one server call send multiple success calls back. You could have your MyLongScript() run, save progress status somewhere, and just keep that running, then have a second google.script.run executing on a loop every certain time period. You can use a JavaScript setInterval(): window.setInterval("javascript function", milliseconds); I don't think that there is a jQuery equivalent.
So it might (roughly) look like this:
$(function() {
google.script.run
.withSuccessHandler(MainCodeSuccess)
.withFailureHandler(MainCodeFailure)
.MyLongScript();
window.setInterval("statusChecker()", milliseconds);
}
window.statusChecker = function() {
google.script.run
.withSuccessHandler(statusCheckSuccess)
.withFailureHandler(onFailure)
.StatuChecker();
};
window.statusCheckSuccess = function(returnStatus) {
if (returnStatus !== false) {
//To Do - show msg to user
document.getElementById('idMsgToUser').textContent = returnStatus;
};
};
Your MyLongScript() might need to be saving the state of the current status to a file. I'm not sure if the subsequent, and simultaneous google.script.run calls wipes out the data in a global variable. If a global variable would hold the data even with all the simultaneous server scripts running, you could save the current status to a global variable. You'd need to experiment with that, or maybe someone knows the answer to that question.

Office 2013 Javascript API - Pass Variable to Callback of ".BindingDataChanged"

Background
I am writing a sidebar app for Excel 2013, and I have a wrapper function which updates the view of the sidebar. I need to trigger that function (and so trigger an update of the view) from multiple events, one of which is when the data in a bound area changes.
The problem I'm having is that I need to pass along a variable to that wrapper function. It needs data which I want to be able to save in a Setting and then load just once.
Code
Current Code:
Office.select("bindings#"+bindingID).addHandlerAsync(Office.EventType.BindingDataChanged, onBindingDataChanged);
function onBindingDataChanged(eventArgs) {
searchThroughData(eventArgs.binding.id);
}
function searchThroughData(bindingID) {
//repaint view
}
The above works to trigger the repaint. But it doesn't include the passed variable. What I'd expect is for the code to be something like this:
Attempted, Doesn't Work:
Office.select("bindings#"+bindingID).addHandlerAsync(Office.EventType.BindingDataChanged, onBindingDataChanged(eventArgs,data));
function onBindingDataChanged(eventArgs,data) {
searchThroughData(eventArgs.binding.id,data);
}
function searchThroughData(bindingID,data) {
//repaint view
}
This doesn't work, however.
Question
Any ideas how I can pass along this variable?
In your attempted solution, you are calling the onBindingDataChanged function instead of making it available for the handler to call. You'd need to do something like this (assuming that the variable "data" is available beforehand)
Office.select("bindings#"+bindingID).addHandlerAsync(Office.EventType.BindingDataChanged, onBindingDataChanged(data));
function onBindingDataChanged(data) {
return function(eventArgs) {
searchThroughData(eventArgs.binding.id, data);
};
}
function searchThroughData(bindingID,data) {
//repaint view
}
If data is a global variable, you can just do
Office.select("bindings#"+bindingID).addHandlerAsync(Office.EventType.BindingDataChanged, onBindingDataChanged(data));
function onBindingDataChanged(eventArgs) {
searchThroughData(eventArgs.binding.id, data);
}
function searchThroughData(bindingID,data) {
//repaint view
}

jQuery/JavaScript Execution Order

I have some items that I'd like the user to be able to filter using jQuery. The user selects their filter criteria and hits submit, and I make a call to my database. When this call completes, I fade out the existing containers with this function:
function clearGrid() {
var theseDivs = $('.grid-item');
$('.grid-item').fadeOut('fast', function() {
$(theseDivs).remove();
});
}
and then I append my new data with the following function:
function repopulate() {
<% #stuff.each do |gb| %>
$('#grid').append('<%= escape_javascript(render "/stuff", :gb => gb) %>');
<% end %>
resizeGrid();
}
The resizeGrid() function does some absolute positioning based on the other elements in the Grid. It seems like repopulate() is being called BEFORE the other elements are removed with clearGrid(), and thus the positioning of the new elements is off, and they're rendered as if the old elements are still there.
Is there a way to ensure that my repopulate() function doesn't get called until the other elements are well out of the way?
You should allow the clearGrid() function to call a callback once it's completed, and then pass it repopulate as that callback. Change clearGrid() to look like this:
function clearGrid(callback) {
var theseDivs = $('.grid-item');
theseDivs.fadeOut('fast', function() {
theseDivs.remove();
if(callback) {
callback();
}
});
}
And then, assuming your current code to call those two looks like this:
clearGrid();
repopulate();
You can change it to look like this:
clearGrid( repopulate );
Note: repopulate should not have () after it because you want to pass a reference to it, not call it.
Second note: I also changed clearGrid() to just use theseDivs rather than call jQuery again. It's slightly faster this way, although you probably won't be able to notice the difference.
If you know that there will only ever be <div> tags that you're working with, you could change the selector to $('div.grid-item') for another small speedup.
Try slowing down the repopulate method with
setTimeout( function(){ repopulate(); }, 50 );

Creating a reusable jQuery function

Instead of re-writing a massive block of code each time, I'm trying to incorporate functions into my work but I'm having trouble making it work.
Basically, I've got a selection of radio buttons and I'm performing some stuff each time a radio button is clicked. (I'm actually loading an iFrame). However, I need to make the iFrame SRC different for each radio button so how would I cater for this within the function?
The function:
jQuery.fn.switchPreview = function () {
$('.liveDemoFrame').remove();
$('.liveDemoHand').append('<iframe class="liveDemoFrame" src="themes/src/' + themeName + '/" width="100%" height="300" scrolling="no"><p>Your browser does not support iframes.</p></iframe>');
$('.liveDemoHand').append('<div class="switchPreview"><div class="loadingPreview"></div></div>');
$('.liveDemoFrame').load(function() {
$('.switchPreview').fadeOut();
$('.switchPreview').remove();
$('.liveDemoFrame').fadeIn();
});
return this;
}
Within the iFrame SRC I have a variable called themeName. I need this to somehow change for each radio button. You can see within the code that calls the function I've tried to declare the variable each time but this still gives me an undefined error.
The code that calls it:
$('#cTheme1').click(function () {
$('input:radio[name=mgChooseTheme]:nth(1)').attr('checked',true);
var themeName = 'theme1';
$('.liveDemoFrame').switchPreview();
});
$('#cTheme2').click(function () {
$('input:radio[name=mgChooseTheme]:nth(2)').attr('checked',true);
var themeName = 'theme2';
$('.liveDemoFrame').switchPreview();
});
$('#cTheme3').click(function () {
$('input:radio[name=mgChooseTheme]:nth(3)').attr('checked',true);
var themeName = 'theme3';
$('.liveDemoFrame').switchPreview();
});
I'm sure this is something very simple but I'm still learning so little things always throw me off!
Pass in the themeName as an argument of the switchPreview function.
-Change the first line of the function to:
jQuery.fn.switchPreview = function (themeName) {
-For each of the three times you are calling the function, make sure you are passing in the argument, i.e:
$('.liveDemoFrame').switchPreview(themeName);
Why not just update the src tag of the iframe ...
$('#cTheme1').click(function () {
$('input:radio[name=mgChooseTheme]:nth(1)').attr('checked',true);
$('#liveDemoFrame').attr('src', <the new url>);
});
Then your iframe would already need to be part of the page :
<iframe id='liveDemoFrame' src='<default page>'></iframe>
i notice your using a CLASS attribute on your iFrame and accessing it using that - you really need to think about using the ID attribute if you are just wanting to refer to a single object. (as in my example above)

Categories