I am creating a list using REST APIs. In my JavaScript code I have written something like this:
// If I declare 'waitDialog' then it is not get closed by
// calling 'waitDialog.close()'. Without any declaration it works.
var waitDialog;
function createList() {
// Show wait dialog
waitDialog = SP.UI.ModalDialog.showWaitScreenWithNoClose("Please wait...", "Please wait...", 100, 300);
jQuery.ajax({
// List data
},
success: doSuccess,
error: doError
});
}
function doSuccess(data) {
waitDialog.close(); // Close wait dialog
}
function doError(data, errorCode, errorMessage) {
waitDialog.close(); // Close wait dialog
}
If I declare waitDialog with statement var waitDialog; then it does not work by calling waitDialog.close(). Without any declaration it works and the dialog is closed. I found this question which elaborates on the difference between using var, but nothing which would clarify this case.
Any idea why does it work without declaration and not with declaration?
I could not recreate your declaration issue.
One thing I noticed... I believe you need to pass the SP.UI.DialogResult enumerable to the close method
waitDialog.close(SP.UI.DialogResult.OK);
//show and hide waiting on it javascript
function waitMessage() {
window.parent.eval("window.waitDialog = SP.UI.ModalDialog.showWaitScreenWithNoClose('Processing...', '', 90, 300);");
}
function closeMessage() {
if (window.frameElement != null) {
if (window.parent.waitDialog != null) {
window.parent.waitDialog.close();
}
}
}
Related
I am using an already defined function and now want to add a pollServer function to it so that this functions runs over and over. I keep getting errors when I try to wrap the existing function in another. Is there a better way to do this?
function callD(id) {
jQuery('document').ready(function pollServer(){
window.setTimeout(function () {
var ab = document.getElementById('a')
console.log(ab);
var bod = document.getElementById(+id)
if (ab == null) {
bod.style.background='green'
} else {
bod.style.background='blue'
}
}, 1200);
})
}
callD();
pollServer();
pollServer isn't defined where you're calling it. Also id isn't being passed to callD, and you also have a +id which doesn't make sense in a document.getElementByid, since if there's any non-number in the ID, that would be NaN. You're also not polling a server, you're setting a timeout once and doing some work that doesn't involve a server. You would want setInterval for regular polling, or to call the function again on some condition like a failure.
$(document).ready(function () {
var intervalId;
function callD(id) {
function pollServer() {
intervalId = window.setInterval(function () {
var ab = document.getElementById('a')
console.log(ab);
var bod = document.getElementById(id)
if (ab == null) {
bod.style.background='green'
} else {
bod.style.background='blue'
}
}, 1200);
}
pollServer();
}
callD('some-id');
// on some condtion eventually:
clearInterval(intervalId);
})
Yeah, jQuery can make things pretty gnarly with all the nested callbacks. To make the code cleaner and easier to understand, I like to split my functions up and define them all at the top-most level of the script, then compose them together like so:
/**
* this function will check for the existing elements
* and update styles
*/
function setBodyStyle(id) {
var ab = document.getElementById('a');
console.log(ab);
var bod = document.getElementById(+id);
if (ab == null) {
bod.style.background='green';
} else {
bod.style.background='blue';
}
}
/**
* this function will create a timeout or interval
* which will in turn run setBodyStyle()
*/
function pollServer() {
// I think you want setInterval here if you're polling?
// setInterval will run _every_ 1200ms,
// setTimeout only runs once after 1200ms
window.setInterval(function() {
// not sure where you're getting id from,
// but you'll want to pass it here
setBodyStyle();
}, 1200);
}
// when the document is ready, run pollServer()
jQuery(document).ready(pollServer);
Having small functions that do one thing is just best-practice for the reasons I mentioned above. This will help your script be more understandable, which will help you find bugs.
For example, two things I don't understand about your code above:
where does the id variable come from? I don't see you passing it to your function from anywhere
how does your script poll the server? I don't see the code for that anywhere either.
Seemed you mean run the function pollServer every 1.2 sec. If so, you'd need to do two things
Use setInterval rather than setTimeout
Delete the last line for the pollServer function, because it is not accessible from outside the ready function block.
I've declared a new function. Then I'm calling that function later. How do I run code only if the function I'm calling has completed.
this is my code
var callLogin = function() {
$(document).ready(function() {
if(document.getElementById("userLoggedIn") === null) {
$(".cover").fadeIn(200);
$(".sixPinInputContainer").fadeIn(200);
$("#pageBody").css("overflow", "hidden");
$('.sixPinInput').first().focus();
};
})
};
Then This is where I call It. The problem is that it's running the .load before it calls my pin container so even if pin is incorrect it runs code.
if (startBtn) {
callLogin()
$("#" + rowID).load("eventHandlersPHP/updateStart.php", {
roomID: id }, function(data, status) {
$("#notStartedCount").load("eventHandlersPHP/jobsNotStartedCount.php");
})
};
This is documented pretty well here. You could create some sort of action that'll trigger the one function, then it can call the other. Also, this will probably be a more helpful place for what it is you're trying to do.
-Gonzo
A script I'm loading is misbehaving. It's got a structure like this:
function bad_function() {
...
}
/* randomly generated stuff */
bad_function();
How do I modify the behavior of bad_function if it's called immediately at the end of the script? I thought of creating a silently read-only property on window before loading the script, but this throws a TypeError: Identifier 'bad_function' has already been declared exception when the above script is executed:
Object.defineProperty(window, 'bad_function', {
value: function() {
/* my monkey-patched code */
}
});
How do I monkey-patch this function?
While this isn't an answer to my question in general, I was able to monkey patch my specific function by patching a global function like encodeURIComponent that was called inside of my function, performing the necessary changes, and throwing an exception to prevent the rest of the original function from running.
var old_encodeURIComponent = window.encodeURIComponent;
window.encodeURIComponent = function() {
// If this function is used in multiple places, look for variables in
// the current scope to determine if this is the right spot to start
// monkey patching.
if (typeof a === 'undefined' || typeof b === 'undefined') {
return old_encodeURIComponent.apply(this, arguments);
}
// You now have access to the variables in the scope of your target
// function. If your monkey patching is just a simple tweak, you're all set
// Otherwise, do what you need to do and throw an exception to stop the
// rest of the code from running
throw 'goodbye';
};
It's not nice, but all I can think to do is to load the script via ajax instead of putting it in a <script> tag, manipulate the result string to call your own version of the function (or "rename" bad_function so it doesn't override your version), then put that in a <script> tag and append it to your page:
An example using jQuery for simplicity:
function good_function() {
alert("I am good");
}
$.ajax({
url: '/echo/html/',
type: 'POST',
data: {
html: "function bad_function() { alert('hahaha'); } bad_function();",
delay: 0
},
success: function(data) {
console.log(data);
// comment this line to see the original
data = data.replace('bad_function();', 'good_function();')
var newScript = $('<script type="text/javascript" />').text(data);
$('body').append(newScript);
}
});
Working JSFiddle
I'm creating a Phonegap application that will perform differently on first run. The way that I am detecting the first run is by seeing of one of the database tables exists. As you can probably tell from the code below, I am checking for the error that is (probably) indicating that the table already exists, thus proving that this is not the application's first run.
function databaseExists(){
var exists;
database.transaction(function(tx){
tx.executeSql('CREATE TABLE GLOBAL (uid, property, value)');
}, function(err){
exists = true;
}, function(){
exists = false;
});
return exists;
}
My problem, however, is that the asynchronous execution of the Javascript code means that the function returns its value before the success (or error) function has set it's value.
This function is called in the initialising stage of the application:
if (databaseExists()){
// Do Something
}
And therefore must return the value rather than execute the function in the success callback of the transaction.
Is there a way to force the execution to wait until the database transaction is complete or return the value through the database.transaction object?
Thanks in advance,
Jon
You need to write it in callback form:
var dataBaseExists(yep, nope) {
database.transaction(function(tx) {
tx.executeSql('CREATE TABLE GLOBAL (uid, property, value)');
}, function(){
if (yep) {
yep.apply(this, arguments);
}
}, function(){
if (nope) {
nope.apply(this, arguments);
}
});
};
var itDoes = function() {
console.log("great");
};
var itDoesNot = function() {
console.log("what a pity");
};
databaseExists(itDoes, itDoesNot);
You need callbacks, but if don't need checking existment of your tables, you can do that easily with localStorage.
e.g.
if(localStorage.getItem('init') === null){
//init
localStorage.setItem('init', true);
}
You will avoid dealing with database.
and maybe this gonna be helpful "CREATE TABLE IF NOT EXISTS..."
I know there's gonna be programmers don't like my solution, but I love it!
var myfEspereti=false;
function Espereti(pStatus)
{
if (pStatus==="wait")
{
myfEspereti = true;
while(myfEspereti)
{
}
}
else if (pStatus==="go")
{
myfEspereti=false;
}
}
and then call Espereti ("wait") when you want to wait for an async call. Inside the async call, when it's finish, call Espereti ("go") and that's it!
I dunno guys, this is a really weird one, but I might just be making a simple mistake and not even realizing it.
I'm sort of a newbie to Javascript, so I'm attempting to write a script that gets content from a PHP script (which returns only a number) and write that data to a div... but Javascript had other ideas. I'm testing on Chrome on Mac OS X, although it doesn't work on Safari either.
The following block is giving me problems:
function getContent() {
window.setInterval(function () {
$.get("get.php", function (data) {
$('#img').slideUp();
$('#div').html(data);
$('#div').slideDown();
}
}
}
Which is failing with:
Uncaught SyntaxError: Unexpected token }
on line 51, or line 8, for the purposes of this example.
Does anyone know why it would fail like this? Don't I need to close the brackets I open?
Your curly braces are OK, but you're missing a few parentheses:
function getContent() {
window.setInterval(function () {
$.get("get.php", function (data) {
$('#img').slideUp();
$('#div').html(data);
$('#div').slideDown();
}); //get - end statement
}, 4000); // setInterval - need another parameter, end statement
}
You're not closing the parentheses for your function calls. As Kobi said, you also need a third parameter for setInterval.
function getContent() {
window.setInterval(function () {
$.get("get.php", function (data) {
$('#img').slideUp();
$('#div').html(data);
$('#div').slideDown();
});
}, 1000);
}
The window.setInterval function has a following syntax:
window.setInterval(functionRef, timeout);
In your case the setInterval and $.get() function call are missing the closing parentheses ). It would be clear for you to write this in the following way:
function getContent() {
// success handler
var success = function() {
// declare the function first as "changeUI"
var changeUI = function() {
$('#img').slideUp();
$('#div').html(data);
$('#div').slideDown();
};
// call the setInterval passing the function
window.setInterval(changeUI, 2000);
};
// get the resource and call the "success" function on successful response
$.get("get.php", success);
}
your window.setInterval is missing a ) after the } on the second to last line