Detecting if a file is already open in javascript/hta - javascript

I'm trying to fix a .hta that someone at my company created 3 or 4 years ago. Right now if you open a file that someone else already has open, you'll lose any work you've done on it and will have to manually do it over again. So I was thinking just checking to see if the file is already open and then either locking editing, or just making a popup saying "hey, if you try to save you're gonna be disappointed". Is there an easy way to check to see if the file is already open in javascript?
The code to open the file is...
function FileOpen( strSetup )
{
if( ! strSetup )
{
strSetup = ShowDialog( "choose-setup", {"DialogTitle" : "Load Setup"} );
}
if( strSetup )
{
if( FileSystem.FileExists( App.Paths.Configs + "/" + strSetup + ".setup" ) )
{
var fFile = FileSystem.GetFile( App.Paths.Configs + "/" + strSetup + ".setup" );
App.Config = LoadXMLDocument( fFile.Path );
// SaveCurrentConfig();
RefreshView( "setup-summary" );
}
else
{
alert( "Could not find setup '" + strSetup + "'" );
}
}
}
and the code for LoadXMLDocument is...
//-----------------------------------------------------------------------------
// FUNCTION : LoadXMLDocument - Loads an XML document
// params : strPath - the path/file of the document to load
// : bCritical- if set true, we die if the document doesn't load
// returns : an XML dom object on success, false otherwise
//-----------------------------------------------------------------------------
function LoadXMLDocument( strPath, bCritical )
{
var xmlDoc = new ActiveXObject( "Msxml2.DOMDocument.3.0" );
xmlDoc.setProperty( "SelectionLanguage", "XPath" );
if( ! FileSystem.FileExists( strPath ) )
{
Error( "'" + strPath + "' is not a valid file path" );
if( bCritical ) Abort();
return( false );
}
var fFile = FileSystem.GetFile( strPath );
xmlDoc.load( fFile.Path );
if( xmlDoc.documentElement == null )
{
Error( "Could not load XML document '" + fFile.Path + "'" );
if( bCritical ) Abort();
return( false );
}
return( xmlDoc );
}

That's what revision control is all about. It's no different than other forms of the same issue that does not involve. hta files.

I see this is super old post but why not use VBS? If it's an HTA, they're supported with running together:
objFSO = CreateObject("Scripting.FileSystemObject")
strFilePath = "C:\test.txt"
If objFSO.FileExist(strFilePath) Then
MsgBox "I win"
End If

Related

CKfinder multiple image upload without CKEditor

I am using the ckfinder modal without CKEditor to upload multiple files to the form section.
I used the code provided in the documentation section,
CKfinder modal opens as expected, selected multiple file but i couldn't able to get all the images url. The response i got only the first image.
window.CKFinder = {
_popupOptions: {
'popup-1-config': { // Config ID for first popup
chooseFiles: true,
onInit: function( finder ) {
finder.on( 'files:choose', function( evt ) {
var file = evt.data.files.first();
var output = document.getElementById( 'output' );
output.innerHTML = 'Selected in popup 1: ' + file.get( 'name' ) + '<br>URL: <img src=" ' + file.getUrl() + '">';
} );
}
},
}
};
var popupWindowOptions = [
'location=no',
'menubar=no',
'toolbar=no',
'dependent=yes',
'minimizable=no',
'modal=yes',
'alwaysRaised=yes',
'resizable=yes',
'scrollbars=yes',
'width=800',
'height=600'
].join( ',' );
document.getElementById( 'popup-1-button' ).onclick = function() {
// Note that config ID is passed in configId parameter
window.open( 'http://foxhills.localhost/admin/ckfinder/ckfinder.html?popup=1&configId=popup-1-config', 'CKFinderPopup1', popupWindowOptions );
};
In the above code var file = evt.data.files.first(); is the reason why i am getting the first image. How i can change the code to get the all the urls as array.
For your event, try testing with this
finder.on( 'files:choose', function( evt ) {
var files = evt.data.files;
var chosenFiles = '';
files.forEach( function( file, i ) {
chosenFiles += ( i + 1 ) + '. ' + file.get( 'name' ) + '\n';
} );
alert( chosenFiles );
} );
Source: https://ckeditor.com/docs/ckfinder/ckfinder3/#!/api/CKFinder.Application-event-files_choose

Set a cookie for an iframe popup to keep it closed

I'm using TypeForm to handle my lead generation forms. The form I'm using has been embedded on the home page of my site. This embedding creates an iframe showing the popup every time the home page is loaded, even if the 'X' is clicked.
Having contacted TypeForm, I have been told that I would need to set a cookie to prevent the popup loading each time. In fact their reply was "To ensure the Typeform only appears once you will have to add cookies to your site in order to ensure a user only sees it one time. This isn't a feature we currently have but hopefully with more requests it's something we could add!"
Embed Code:
<a class="typeform-share button" href="https://example.typeform.com/to/fbPnzs" data-mode="drawer_left" data-auto-open=true target="_blank" style="display:none;"></a>
<script>
(function() {
var qs, js, q, s, d = document,
gi = d.getElementById,
ce = d.createElement,
gt = d.getElementsByTagName,
id = "typef_orm_share",
b = "https://embed.typeform.com/";
if (!gi.call(d, id)) {
js = ce.call(d, "script");
js.id = id;
js.src = b + "embed.js";
q = gt.call(d, "script")[0];
q.parentNode.insertBefore(js, q)
}
})()
</script>
The embed URL is example.typeform.com whereas the website where the form is to be embedded is not the same. Does consideration need to be made about same-origin?
What do I need to implement in terms of code to the functions.php file of my WordPress site to add a cookie that allows the popup to show only once and/or never show again if the 'X' is clicked?
Thank to Nicolas for his answer!
Having checked over the SDK, I've adapted Nicolas' snippet to cater to the left draw popup. This checks if a cookie exists, if it does not, it should set it and display the left draw TypeForm popup; if the cookie does exist, it won't show.
var url = "https://demo.typeform.com/to/njdbt5" // Update with your TypeForm URL
let params = new URLSearchParams( location.search );
url += "?utm_source=" + params.get( 'utm_source' ); // Replace with the hidden values you want to pass
var displayed = getCookie( "typeform_displayed" ); // Check for the cookie typeform_displayed
if ( displayed ) {
null
} else if ( !displayed && displayed === "" ) {
setCookie( "typeform_displayed", true, 365 ); // Set typeform_displayed cookie with a value of true and an expiry of 365 days
showEmbed();
}
//
function showEmbed() {
window.typeformEmbed.makePopup( url, {
mode: 'drawer_left',
autoOpen: true,
hideHeaders: true,
hideFooters: true,
} )
}
// Cookie Manipulation
// Source: https://www.w3schools.com/js/js_cookies.asp
function setCookie( cname, cvalue, exdays ) {
var d = new Date();
d.setTime( d.getTime() + ( exdays * 24 * 60 * 60 * 1000 ) );
var expires = "expires=" + d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
function getCookie( cname ) {
var name = cname + "=";
var decodedCookie = decodeURIComponent( document.cookie );
var ca = decodedCookie.split( ';' );
for ( var i = 0; i < ca.length; i++ ) {
var c = ca[ i ];
while ( c.charAt( 0 ) == ' ' ) {
c = c.substring( 1 );
}
if ( c.indexOf( name ) == 0 ) {
return c.substring( name.length, c.length );
}
}
return "";
}
I think this is totally doable using Typeform Embed SDK.
You will need to check if the cookie is already set. And depending on the value display or not the embed typeform.
I made a working example on Glitch, you can look at it here.
In code the logic would look like this:
var displayed = getCookie("displayed_typeform");
if (displayed){
embedElement.innerHTML="<h2>Typeform already displayed once.</h2>"
} else if (!displayed && displayed === "") {
setCookie("displayed_typeform", true, 365);
showEmbed();
}
Hope it helps :)

TaffyDB jquery for each loop runs twice

So I'm working on a project from a book where TaffyDB is used to create a collection of people. The project is a simple chatroom, where the list of users is generated as an html list of online users in the window. Currently I'm using fake data to test, and I have one for each loop (in jquery) that works correctly, printing five "avatars" to the screen.Yet, my each loop to print the online users runs twice: why is this? These two loops use the exact same setup, yet the second runs twice.
The for each that works:
people_db().each(function(person,idx){
var class_list;
if( person.get_is_anon() ){ return true; }
class_list = ['spa-avtr-box'];
if( person.id === chatee.id ){
class_list.push('spa-x-is-user');
}
$box = $('<div/>')
.addClass(class_list.join(' '))
.css( person.css_map )
.attr('data-id', String(person.id) )
.prop( 'title', spa.util_b.encodeHtml(person.name) )
.text( person.name )
.appendTo( $nav );
});
The loop that runs twice:
people_db().each(function(person,idx){
var select_class = '';
console.log(person);
if( person.get_is_anon() || person.get_is_user() ) {
return true;
}
if( chatee && chatee.id === person.id ){
select_class = 'spa-x-select';
}
list_html
+= '<div class="spa-chat-list-name'
+ select_class + '" data-id="' + person.id + '">'
+ spa.util_b.encodeHtml(person.name) + '</div>';
});
if( !list_html ){
list_html = String()
+ '<div class="spa-chat-list-note">'
+ 'To chat alone is the fate of all great souls...<br><br>'
+ 'No one is online'
+ '</div>';
clearChat();
}
jqueryMap.$list_box.html(list_html);
}
Any ideas what I'm doing wrong? I've gone through the rest of my code extensively and I'm not calling it twice, I'm almost certain is has to be something with the loop.
I'd start by making sure you're not calling it twice.
If you look at the console, does
console.log(person);
print twice?
If so unbind whatever is calling
people_db().each(function(person,idx){
before you bind it.

Hook AJAX in Wordpress

I have been delving into the world of Javascript and AJAX. I am super close, but for some reason I do not think I am hooking into wordpress ajax functions right. I have poured through the docs and this and think it is 99% there.
Is what this app does is there is a list of items. Each one with a + button. Clicking the button pops up a confirm box, and if confirmed grabs the needed data to pass to the php. The php adds the item into mysql with wpdb->insert. It also does some changes if you buy.
The js works all the way up to the call, grabbing the right values etc. Testing the php separately works as well if I hard code the values it is supposed to grab from POST. So I KNOW both pieces run, I just can't get the js to call the ajax api right. Can someone please take a look at this and let me know how to hook these together so the ajax call actually runs the php?
Here is the code.
<?php
add_action( 'admin_footer', 'addItemAJAX_javascript' );
function addItemAJAX_javascript() {
$adminAJAX = admin_url('admin-ajax.php');
?>
<script type="text/javascript" language="JavaScript">
$(function() {
$( "input[name=btnAddItem]" )
.button()
.click(function( event ) {
event.preventDefault();
var confirmAction = confirm('Are you sure you want to add this item to your character?');
if (confirmAction==true) {
// build data for AJAX call
var cID = $('#hdnCharID').val();
cID = cID*1;
var charMoney = $('#hdnCharMoney').val();
var thisValue = $(this).val();
var iID = $(this).prev('input[id="hdnItemID"]').val()
iID = iID*1;
//Add or Buy Item
if (thisValue != "+") {
var buy = 1;
}
else {
var buy = 0;
}
var ajaxurl = <?php echo json_encode($adminAJAX); ?>;
console.log('cID = ' + cID);
console.log('charMoney = ' + charMoney);
console.log('thisValue = ' + thisValue);
console.log('iID = ' + iID);
console.log('buy = ' + buy);
console.log('ajaxurl = ' + ajaxurl);
var data = {
action: 'addItemAJAX',
charID: cID,
itemID: iID,
buyItem: buy
};
console.log('data = ' + data);
console.log(data);
//WP ajax call
$.post(ajaxurl, data, function(response) {
alert('Got this from the server: ' + response);
});
}
else {
console.log('add item aborted');
}
});
});
</script>
<?php
};
addItemAJAX_javascript();
// PHP SIDE OF AJAX - Handeling Request //// AJAX PROCESSING /////////////////////////////////
add_action('wp_ajax_addItemAJAX', 'addItemAJAX_callback');
function addItemAJAX_callback() {
global $wpdb;
$charID = intval($_POST['charID']);
$itemID = intval($_POST['itemID']);
$buyItem = intval($_POST['buyItem']);
// //get item details
$getItemDetailsSQL = "
Select
fyxt_wp_db_fatcow.fyxt_items.idfyxt_items,
fyxt_wp_db_fatcow.fyxt_items.fyxt_item_name,
fyxt_wp_db_fatcow.fyxt_items.fyxt_item_description,
fyxt_wp_db_fatcow.fyxt_items.fyxt_item_cost,
fyxt_wp_db_fatcow.fyxt_items.fyxt_item_weight
From
fyxt_wp_db_fatcow.fyxt_items
Where
fyxt_wp_db_fatcow.fyxt_items.idfyxt_items = $itemID";
$getItemDetailsResults = $wpdb->get_row($getItemDetailsSQL);
$iID = $getItemDetailsResults->idfyxt_items;
$iName = $getItemDetailsResults->fyxt_item_name;
$iDesc = $getItemDetailsResults->fyxt_item_description;
$iCost = $getItemDetailsResults->fyxt_item_cost;
$iWeight = $getItemDetailsResults->fyxt_item_weight;
$charItemTable = fyxt_char_items;
$wpdb->insert(
$charItemTable,
array (
idfyxt_item => $iID,
idfyxt_character => $charID,
item_name => $iName,
item_desc => $iDesc,
item_cost => $iCost,
item_weight => $iWeight,
item_quant => 1,
equip => 0,
carried => 1
)
);
$wpdb->print_error();
$newItemAdded = $wpdb->insert_id;
//remove cash if item is bought
if ($buyItem == 1 ) {
$curCharMoneySQL =
"Select
fyxt_wp_db_fatcow.fyxt_characters.char_money
From
fyxt_wp_db_fatcow.fyxt_characters
Where
fyxt_wp_db_fatcow.fyxt_characters.idfyxt_character = $charID";
$curCharCash = $wpdb->get_var($curCharMoneySQL);
$wpdb->print_error();
$newCash = $curCharCash - $iCost;
$changeCashSQL = "
UPDATE fyxt_characters
SET
char_money = $newCash
WHERE
idfyxt_character = $charID";
$changeCash = $wpdb->query($changeCashSQL);
$wpdb->print_error();
}
$debugArray = Array();
array_push($debugArray,$charID, $itemID, $buyItem, $getItemDetailsSQL, $getItemDetailsResults,$newItemAdded, $newCash);
echo $debugArray ;
die();
}
?>
I am pretty sure it is 1 (or 2) of 2 things. I am not sure if I am hooking these functions to wordpress right. Or there might be issues with nested functions I have for the jQuery button. I doubt it is number 2 though because it seems to work... I just get a 0 back from the server without any database activity. Here is what the log says.
cID = 112 ?charID=112:538
charMoney = 9990 ?charID=112:539
thisValue = + ?charID=112:540
iID = 664 ?charID=112:541
buy = 0 ?charID=112:542
ajaxurl = http://localhost/nnnnnnnn.com/wp-admin/admin-ajax.php ?charID=112:543
data = [object Object] ?charID=112:550
Object {action: "addItemAJAX", charID: 112, itemID: 664, buyItem: 0} ?charID=112:551
XHR finished loading: "http://localhost/nnnnnnnn.com/wp-admin/admin-ajax.php". jquery-1.9.1.js:8526
send jquery-1.9.1.js:8526
jQuery.extend.ajax jquery-1.9.1.js:7978
jQuery.(anonymous function) jquery-1.9.1.js:7614
(anonymous function) ?charID=112:554
jQuery.event.dispatch jquery-1.9.1.js:3074
elemData.handle
Thank you very much for all of the help and suggestions!
First of all you need to add hooks in proper way
// For the users that are not logged in
add_action( 'wp_ajax_nopriv_addItemAJAX', 'addItemAJAX_callback' );
// For the users that are logged in:
add_action( 'wp_ajax_addItemAJAX', 'addItemAJAX_callback' );
// ajax handler
function addItemAJAX_callback()
{
// code goes here
// since $debugArray is an array, so
die(json_encode($debugArray)); // last line
}
One hook will work when user is logged in and another will work when user is not logged in (for any user). If you are making ajax request for logged in users then, wp_ajax_nopriv_ hook is required.
Keep your js/ajax code in a separate file in yourthemefolder/js/myAjaxScript.js and also keep following code in your functions.php file
add_action('wp_enqueue_scripts', 'my_load_scripts');
function my_load_scripts()
{
// for pluggin, you may use "plugin_dir_url( __FILE__ )"
wp_enqueue_script( 'my_ajax-script', get_stylesheet_directory_uri() . '/js/myAjaxScript.js', array('jquery') );
// Following code will let you use "ajaxObj.ajax_url" to get the
// ajax url (admin-ajax.php) in your my_ajax_scriptjs file
wp_localize_script(
'my_ajax-script', 'ajaxObj', array( 'ajax_url' => admin_url( 'admin-ajax.php' )
));
}
In your my_ajax_script.js file, you may code like this
var data = {
action: 'addItemAJAX_callback',
// ...
};
$.getJson(ajaxObj.ajax_url, data, function(response) {
// response is an object
// ...
});
Alos remember, when using ajax from admin panel, you don't need to use wp_localize_script, since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php.
I won't go through your code as it seems a bit hard to replicate (see SSCCE for this matter). But I'll outline how to work with Ajax and WordPress (from How to Use AJAX in a WordPress Shortcode?):
1) Enqueue and localize the JavaScript file.
Instead of enqueueing, we could print directly in the head or footer, but it's not good practice. And the localization will pass PHP values to JS in a clean fashion.
I'm assuming you're working with a theme, otherwise change get_stylesheet_directory_uri() to plugins_url().
add_action( 'wp_enqueue_scripts', 'enqueue_so_19721859' );
function enqueue_so_19721859()
{
# jQuery will be loaded as a dependency
## DO NOT use other version than the one bundled with WP
### Things will BREAK if you do so
wp_enqueue_script(
'my-handler',
get_stylesheet_directory_uri() . '/js/ajax.js',
array( 'jquery' )
);
# Here we send PHP values to JS
wp_localize_script(
'my-handler',
'my_handler',
array(
'ajaxurl' => admin_url( 'admin-ajax.php' ),
'ajaxnonce' => wp_create_nonce( 'my_ajax_validation' ) // <--- Security!
)
);
}
2) Ajax for logged and non-logged users
You gotta add a public Ajax callback too with no_priv_:
add_action('wp_ajax_addItemAJAX', 'addItemAJAX_callback');
add_action('wp_ajax_no_priv_addItemAJAX', 'addItemAJAX_callback');
3) Ajax Callback and Response
The Ajax callback has security checks and uses wp_send_json_* to handle the response:
function addItemAJAX_callback()
{
check_ajax_referer( 'my_ajax_validation', 'security' );
$my_thing = something();
if( !$my_thing )
wp_send_json_error( array( 'error' => __( 'Could not retrieve a post.' ) ) );
else
wp_send_json_success( $my_thing );
}
4) Finally, the script
It's essential to wrap all jQuery with noConflict mode.
You can pass whatever info you need through the localized object my_handler. We check 3 things from the response:
total failure: couldn't reach the callback or didn't pass security
partial failure: the callback was reached but returned json_error
success: proceed with your thing
jQuery( document ).ready( function( $ ) {
var data = {
action: 'addItemAJAX_callback',
security: my_handler.ajaxnonce
};
$( '#my-submit' ).click( function(e) {
e.preventDefault();
$.post(
my_handler.ajaxurl,
data,
function( response ) {
// ERROR HANDLING
if( !response.success ) {
// No data came back, maybe a security error
if( !response.data )
$( '#my-answer' ).html( 'AJAX ERROR: no response' );
else
$( '#my-answer' ).html( response.data.error );
}
else
$( '#my-answer' ).html( response.data );
}
);
});
});

Javascript - callback function

This seems in my head like it should work but I cant figure out why it doesn't:
(function ($) {
$.fn.extend({
facebook: function (opts, callbackFnk) {
var $this = this;
...
...
...
$this.fbGetFriends = function( clback ){
jsonUrl = fbMe + '/friends?access_token=' + token + '&callback=?';
$.getJSON( jsonUrl, function( json ){
console.log(json.data[0].name);
clback.call(json);
});
}
...
...
...
In the console log the first name appears
In my other script:
var facebook = $.fn.facebook(
{
myClientId : '###############',
mySecret : '##############'
}
);
facebook.fbOnLogin = function(){
user = facebook.userDetails();
token = facebook.getToken();
facebook.fbGetFriends(function( json ){
for ( var i in json ) {
console.log( 'friends: ' + i + ' ' + json[i] );
}
});
}
In console log im getting nothing displayed and in previous tests its displaying errors data undefined.
Can anyone tell me where im going wrong?
regards
You don't need clback.call, just clback(json) is enough.

Categories

Resources