FancyTree activate function for a node on initiating - javascript

i need some help. I am trying to build a fancytree with url as source
var currentTree = $('#files_tree');
var urlBase = currentTree.attr("data-url");
currentTree.fancytree({
extensions: ["glyph", "dnd"],
glyph: {map: glyphIconClasses()},
// selectMode: 1,
source: {url: urlBase ,
data: {mode: "all"},
cache: false
},
activate: function (event, data) {
//data.node.render();
//show_edit_node_fnc(data.node.key);
//currentNodeToEdit = data.node;
id = data.node.data.id;
filesof = data.node.data.filesof;
list_files( filesof , id ) ; // Call to another JS function
},
and i make the content using php array, and send the request as json response
$arrFileTree['title'] = $project->name;
$arrFileTree['folder'] = true;
$arrFileTree['expanded'] = true;
$arrFileTree['activated'] = true;
$arrFileTree['data'] = array("filesof" => "project" , "id" => $project->id);
$arrSource = $project->sources ;
if($arrSource){
$arrChildren = array();
foreach($arrSource as $source){
$arNode['key'] = $source->id;
$arNode['title'] = $source->title;
$arNode['folder'] = true;
$arNode['data'] = array("filesof" => "source", "id" => $source->id);
$arrChildren[] = $arNode;
}
$arrFileTree['children'] = $arrChildren;
}
return array($arrFileTree);
what I need is, when i load the page for the first time, that an element be activated and the default "activate" function to be called on some value i assigned in php like ($arrFileTree['activated'] = true;)
So when i page loaded the "activate" function for a node will be called, and it will call my second function "list_files"
could anyone help me with this ?
Thanks
Wael

You could define the active state in the source data
...
$arrFileTree['active'] = true;
and trigger the activate event when the data was loaded:
$("#tree").fancytree({
source: {
...
},
init: function(event, data) {
data.tree.reactivate();
},

Related

Using fetch in chrome extension popup.js return empty response object

Below is the code for the popup.js in my chrome extension v3
The parts I commented out are meant to extract previews (of the first few lines) for the respective queries, but when implemented, the search for the extension does not work at all (no errors though).
I tried logging into console to see what happened along the way, and noticed that even the response object did not register anything in the console, needless to say the HTML. Any clues, or perhaps there are better ways to generate the previews?
document.addEventListener("DOMContentLoaded", function () {
// Select the search form and the search results container
var form = document.getElementById("search-form");
var container = document.getElementById("search-results");
// Handle the submit event of the form
form.addEventListener("submit", function (event) {
event.preventDefault(); // Prevent the form from being submitted
// Get the search title from the form
var title = form.elements.title.value;
var title2 = title.replace(/ /g, "+"); // Replace spaces with +
var results = [];
var queries = [
{
url: `https://www.ncbi.nlm.nih.gov/pmc/?term=${title}`,
title: "NCBI PMC"
},
{
url: `https://www.biorxiv.org/search/${title}`,
title: "bioRxiv"
},
{
url: `https://www.medrxiv.org/search/${title}`,
title: "medRxiv"
},
{
url: `https://www.google.com/search?q=${title2}+filetype:pdf`,
title: "PDF Search"
}
];
queries.forEach(function (query) {
fetch(query.url)
.then(function (response) {
return response.text();
console.log(response);
})
// .then(function (html) {
// console.log(query.title);
// console.dir(html); // Inspect the properties of the html variable
// console.table(html); // View the contents of the html variable as a table
// // Parse the HTML using the DOMParser
// var parser = new DOMParser();
// var doc = parser.parseFromString(html, "text/html");
// // Extract the relevant information from the parsed HTML
// var title = doc.querySelector("title").innerText;
// var lines = [];
// var paragraphs = doc.querySelectorAll("p");
// for (var i = 0; i < paragraphs.length; i++) {
// lines.push(paragraphs[i].innerText);
// if (lines.length === 5) {
// break; // Break the loop
// }
// }
results.push({
title: query.title,
url: query.url,
// preview: lines.join("\n")
});
// });
});
// Create the search results HTML
var resultsHTML = "";
results.forEach(function (result) {
resultsHTML += `<div class="result">
<h2>${result.title}</h2>
<p>${result.preview}</p>
</div>`;
});
// Update the container with the search results HTML
container.innerHTML = resultsHTML;
// Handle the click event of the result links
container.addEventListener("click", function (event) {
var target = event.target;
if (target.tagName === "A") {
// Open the URL in a new tab and bring it to the front
var url = target.dataset.url;
var tab = window.open(url, "_blank");
tab.focus();
}
});
});
});```

ajax.post returns index html but not the html that I should get after a post

So I'm trying to build a JS script that allows me to automatically enroll in courses in uni once they're available, and what I've gotten so far is filling the boxes with course IDs and then clicking submit but then I realized using ajax to post would be a better way than simulating a click.
The problem is, the returned html after a post is just a normal html with no success msg on enrolling neither failure. Here is my code:
const courses = ['56895', '56712', '56812']
function findnewreg() {
var index = 0
courses.forEach(element => {
index++;
var ind = "crn_id" + index;
document.getElementById(ind).value = element
form = document.getElementById(ind).form
});
var regbtn = document.getElementsByName('REG_BTN')
regbtn.forEach(element =>{
if(element.value=='تنفيذ التغييرات'){
//element.click();//<form action="/PROD/xwckcoms.P_Regs" method="post" onSubmit="return checkSubmit()">
submitForm()
console.log("clicked")
document.addEventListener("DOMContentLoaded", function(event){
if (document.body.textContent.includes("لقد قمت بإجراء العديد من المحاولات لتسجيل هذا الفصل الدراسي، اتصل بمكتب التسجيل للحصول على مساعدة. ")) {
console.log('⛔️ error retrying...');
//history.back();
findnewreg()
}else{
console.log('✅ success');
}});
}
})
}
function submitForm(){
var form = form = document.getElementById("crn_id1").form
var href = '/PROD/xwckcoms.P_Regs'//form.getAttribute("action");
var formData = {};
jQuery(form)?.find("input[type=text]").each(function (index, node) {
console.log(index, node)
formData[node.name] = node.value;
});
// formData = jQuery(form).serialize() //also tried this, same result
jQuery.post(href, formData).done(function (data) {
prompt('DATA:' , data)
findnewreg();
});
}
findnewreg();

AJAX - reload page if JSON has changed

I cannot find a suitable way to achieve this:
I have this script
<script type="text/javascript">
function updateSpots() {
$.ajax({
url : '/epark/api/spots/last',
dataType : 'text',
success : function(data) {
var json = $.parseJSON(data);
var currentMessage = json.dateTime;
var idPosto = json.idPosto;
console.log('current '+currentMessage);
console.log('old '+oldMessage);
if(currentMessage != oldMessage){
setTimeout(function(){location.reload();}, 5000);
$('#idPosto').toggle("higlight");
}
oldMessage = currentMessage;
}
});
}
var intervalId = 0;
intervalId = setInterval(updateSpots, 3000);
var oldMessage ="";
</script>
This should check every 3 seconds if the dateTimehas changed on the JSON.
The problem is that I cannot get to go further first step. I mean, when the page loads, oldMessageempty so the if condition is not satisfied. If I could "jump" this first iteration, then everything would go well...
var oldMessage = false;
//...
if (oldMessage && oldMessage !== currentMessage) {
//...

Catching form submissions in Backbone

I have a URL route that has a parameter whose value is not known ahead of time when the page is loaded. For example:
/read/book/page/:page
But when the user is selection screen they get to type in which page number they want to start on then click submit. Is it possible to catch this form submission and place it in the URL? Normally there is a question mark (?) right because its a GET request. But Backbone how can backbone catch that?
Demo:
http://jsfiddle.net/vpetrychuk/PT2tU/
JS:
var Model = Backbone.Model.extend({
url : function () {
return 'http://fiddle.jshell.net/echo/json?page=' + this.get('page');
},
// remove it
parse : function (response) {
response || (response = {});
response.justToTriggerChangeEvent = Math.random();
return response;
},
getPageContent : function () {
return 'Here should be page a content for page #' + this.get('page');
}
});
var View = Backbone.View.extend({
el : '[data-page]',
events : {
'submit' : 'submit'
},
initialize : function () {
this.listenTo(this.model, 'change', this.showPage);
},
showPage : function () {
this.$('[data-page-content]').html(this.model.getPageContent());
},
submit : function (e) {
e.preventDefault();
var page = this.$('[data-page-num]').val();
if (page) {
app.navigate('read/book/page/' + page, true);
}
}
});
var Router = Backbone.Router.extend({
routes : {
'read/book/page/:page' : 'page'
},
initialize : function (options) {
this.bookModel = options.bookModel;
},
page : function (page) {
this.bookModel.set('page', page);
this.bookModel.fetch();
}
});
var model = new Model();
var view = new View({model:model});
var app = new Router({bookModel:model});
Backbone.history.start();
HTML:
<div data-page>
<form>
<label><input type="text" data-page-num /></label>
<button type="submit">Submit</button>
</form>
<div data-page-content></div>
</div>

dojox.grid.enchancegrid editable fields force save

I have a enhancegrid which fields are editable. Some fields will be changed manually while others will change dynamically. The thing is that I would not want to store values ​​onApplyEdit, I want to force save the values ​​but I cant find the solution for it. Here is how it´s right now which actually working great.
dojo.connect(grid, "onApplyEdit", grid, function(evt, rowIndx, fieldIndx){
var selected_item = grid.getItem(evt);
//Not sure if this is the most efficient way but it worked for me
var row_id = grid.store.getValue(selected_item, "row_id");
var from_item_no = grid.store.getValue(selected_item, "from_item_no");
var from_inventory = grid.store.getValue(selected_item, "from_inventory");
var comment = grid.store.getValue(selected_item, "comment");
edit_quantity = grid.store.getValue(selected_item, "quantity");
var to_item_no = grid.store.getValue(selected_item, "to_item_no");
var to_inventory = grid.store.getValue(selected_item, "to_inventory");
var foundation = grid.store.getValue(selected_item, "foundation");
// Instantiate some write implementing store.
var store = grid.store;
// Set our load completed handler up...
var onCompleteFetch = function(items, request){
// Define the save callbacks to use
var onSave = function(){
dojo.xhrPost({
url: url,
content: {
row_id: row_id,
from_item_no: from_item_no,
from_inventory: from_inventory,
comment: comment,
quantity: edit_quantity,
to_item_no: to_item_no,
to_inventory: to_inventory,
foundation: foundation
},
handleAs: "text",
load: function(data){
console.log("Returned value: " + data);
global_saved_check = false;
},
error: function(error){
alert(error);
}
});// end xhrPost
} // end onSave
var onSaveError = function(error){
alert("Error occurred: " + error);
}
// If the store has modified items (it should), call save with the handlers above.
if(store.isDirty()){
store.save({onComplete: onSave, onError: onSaveError});
}
} // end onCompleteFetch
// Define a fetch error handler, just in case.
var onFetchError = function(error, request){
alert("Fetch failed. " + error);
}
// Fetch some data... All items with a foo attribute, any value.
store.fetch({query: {foo:"*"}, onComplete: onCompleteFetch});
});//end connect onApplyEdit

Categories

Resources