How to reflect JStree changes to the original XML? - javascript

I'm using JStree to display an XML file, and after displaying it the user can create, rename, or delete some nodes, and sor sure these changes appear only on the displayed xml and not reflected on the original file, I want to know how to reflect this changes to the original XML fie back after clicking like a submit button, or at least how to get the data changed.
Update
The code:
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>menu-editor</title>
<script type="text/javascript" src="src/jquery-1.10.1.min.js"></script>
<script type="text/javascript" src="src/jstree/jquery.cookie.js"></script>
<script type="text/javascript" src="src/jstree/jquery.hotkeys.js"></script>
<script type="text/javascript" src="src/jstree/jquery.jstree.js"></script>
<link href="themes/!style.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="src/jstree/!script.js"></script>
<script type="text/javascript" src="src/UIMTreeProcessor.js"></script>
<style type="text/css">
.
.
.
//css stuff
</style>
</head>
<body>
<div id="dummy"></div>
<div id="mylist">
<li id='root'><a href='#'>Root node</a><ul><li><a href='#'>Child node</a></li></ul></li>
</div>
<div id="submit" class="submit_btn">Submit</div>
</body>
<script type="text/javascript" class="source below">
var _url = "cafe.xml";
var _uimTree = null;
$(function () {
getTopContent();
});
getTopContent = function(){
$.ajax({
type: "GET",
url: _url,
dataType:"xml",
cache: false,
beforeSend:function(){
//do something before send
},
success: function(data){
processXML(data);
},
error:function(e){
alert("Error: "+e);
}
});
}
processXML = function(root){
_uimTree = new UIMTreeProcessor(root, $("#mylist"));
_uimTree.doProcess();
}
$('#submit').on('click',function(){
//alert the entire XML after edits via (getXML)
});
</script>
And the UIMtreeprocessor Library code
function UIMTreeProcessor(data, treeEl) {
this.data = data;
this.treeEl = treeEl;
}
UIMTreeProcessor.prototype.initTree = function(data){
this.treeEl.jstree({
"json_data" : {
"data":data,
"progressive_render":"true"
},
"plugins" : ["themes","json_data","ui","crrm","cookies","dnd","search","types","hotkeys","contextmenu"],
"core":{"animation":0}
});
}
UIMTreeProcessor.prototype.doProcess = function(){
//Find root:
var _root = $(this.data).children(':first-child');
var _a_feed = new Array();
this.vsTraverse($(_root), _a_feed);
var _treedata = [{"data":_root[0].nodeName,"children":_a_feed, "state":"open"}];
this.initTree(_treedata);
}
UIMTreeProcessor.prototype.vsTraverse = function(node, arr){
var _ch = $(node).children();
for(var i=0; i<_ch.length; i++){
var _vsArr = new Array();
this.vsTraverse(_ch[i], _vsArr);
var _a_att = this.vsTraverseAtt(_ch[i]);
if(null!=_a_att){
_vsArr.push([{"data":"Attributes "+"["+_ch[i].nodeName+"]","children":_a_att, attr : { "class" : "uim_attr"}}]);
}
if(null!=_ch[i].firstChild && 3==_ch[i].firstChild.nodeType){
arr.push([{"data":_ch[i].nodeName + ": " + _ch[i].firstChild.textContent,"children":_vsArr, "state":"open"}]);
}else{
arr.push([{"data":_ch[i].nodeName,"children":_vsArr, "state":"open"}]);
}
}
}
UIMTreeProcessor.prototype.vsTraverseAtt = function(node){
var _a_atts = null;
if(null!=node.attributes && node.attributes.length > 0){
_a_atts = new Array();
for(var i=0; i<node.attributes.length; i++){
_a_atts.push(node.attributes[i].nodeName + ":" + node.attributes[i].nodeValue);
}
}
return _a_atts;
}

Edit: I was really wrong in my original answer.
There is a get_xml method in the xml_data plugin, which is supposed to do what you describe. I have not tested it myself, but if it's anything like json_data.getJSON, the output will contain all kinds of JStree metadata which you will not want to put back into your XML.

Related

JS automated click not working

EDIT:
I think i have found a solution for this one. Might be a little primitive but inserting it here until someone comes up with a better solution.
Thanks !
<html>
<body onload="makeShort()">
<p id="button" style=display:none; onclick="makeShort()">Click me.</p>
<span id="output" style=display:none; >Wait. Loading....</span>
</body>
<head>
</head>
<script type="text/javascript">
function makeShort()
{
var longUrl=location.href;;
var request = gapi.client.urlshortener.url.insert({
'resource': {
'longUrl': longUrl
}
});
request.execute(function(response)
{
if(response.id != null)
{
str =""+response.id+"";
document.getElementById("output").innerHTML = str;
}
else
{
alert("error: creating short url n"+ response.error);
}
});
}
window.onload = makeShort;
function load()
{
//Get your own Browser API Key from https://code.google.com/apis/console/
gapi.client.setApiKey('xxxxxx');
gapi.client.load('urlshortener', 'v1',function(){document.getElementById("output").innerHTML="";});
}
window.onload = load;
</script>
<script>
setTimeout(function(){
document.getElementById('button').click();
},1000);
</script>
<script src="https://apis.google.com/js/client.js"> </script>
</html>
<html lang="en">
<head>
<meta charset="utf-8">
<title></title>
<script>
function SendLinkByMail(href) {
var subject= "Interesting Information";
var body = document.getElementById("output").innerHTML;
body += " Interesting Information";
var uri = "mailto:?subject=";
uri += encodeURIComponent(subject);
uri += "&body=";
uri += encodeURIComponent(body);
window.open(uri);
}
</script>
</head>
<body>
<p>Email link to this page</p>
</body>
</html>
Can some one suggest why this "auto-click" function is not working in my code below?
function makeShort() {
var longUrl = location.href;;
var request = gapi.client.urlshortener.url.insert({
'resource': {
'longUrl': longUrl
}
});
request.execute(function(response) {
if (response.id != null) {
str = "<b>Long URL:</b>" + longUrl + "<br>";
str += "<b>Short URL:</b> <a href='" + response.id + "'>" + response.id + "</a><br>";
document.getElementById("output").innerHTML = str;
} else {
alert("error: creating short url n" + response.error);
}
});} window.onload = function() {
var button = document.getElementById('modal');
button.form.submit();}
function load() {
//Get your own Browser API Key from https://code.google.com/apis/console/
gapi.client.setApiKey('xxxxxxxxx');
gapi.client.load('urlshortener', 'v1', function() {
document.getElementById("output").innerHTML = "";
});} window.onload = load;
<html>
<input type="button" id="modal" value="Create Short" onclick="makeShort();" /> <br/> <br/>
<div id="output">Wait. Loading....</div>
<head>
</head>
<script src="https://apis.google.com/js/client.js"> </script>
</html>
My basic aim is to insert a "share via email" button on the page which would shorten the url on the address bar and open user's email client/whatsapp app to share that url..
Obviously I could not find a way to combine these two functions in to one since I am not a very experienced js person. The primitive solution I found is to auto-click the first function, get the short url, and then find a different code to insert this in to the body of the "mailto" link, which will be my 2nd challenge.
To programmatically click a button on page load
If you are using jQuery:
$(function() {
$('#modal').click();
});
Plain javascript:
window.onload = function(){
var event = document.createEvent('Event');
event.initEvent('input', true, true);
document.getElementById("modal").dispatchEvent(event);
};

Javascript scope and sequentiality issue

I want to get an id from the query and display it in html.
I want to keep things in separate javascript files, because in the future, it will retrieve a json from php and will filter it based on some checkboxes, radio buttons, etc. and then display the result.
In this moment, I get a blank page, and the id value is not shown, so I'm doing something wrong.
http://localhost:10600/js1/index.php?id=5
index.php
<html>
<head>
<script type='text/javascript' src='https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js'></script>
</head>
<body>
<div class="results"></div>
</body>
</html>
<script type="text/javascript" src="config.js"></script>
<script type="text/javascript" src="display.js"></script>
<script type="text/javascript" src="sequence.js"></script>
config.js
function getId() {
id = "<?php echo $_GET['id']; ?>";
}
display.js
function updateHtml() {
window.onload = function() {
document.querySelector('.results').innerHTML = id;
}
}
sequence.js
function seq()
{
getId();
updateHtml();
}
seq();
Please try the following:
index.php
<html>
<head>
<script type='text/javascript' src='https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js'></script>
</head>
<body>
<div class="results"></div>
</body>
</html>
<script type="text/javascript">
var id;
function getId() {
id = "<?php echo $_GET['id']; ?>";
}
</script>
<script type="text/javascript" src="display.js"></script>
<script type="text/javascript" src="sequence.js"></script>
function getParameters() {
var url_params = window.location.search.substring(1); // Removing characters : ?
var params = url_params.split("&");
var res = {};
for (var i = 0, c = params.length; i < c; i++) {
var split = params[i].split("=");
res[split[0]] = split[1];
}
return res;
}
Returns an object {param: value}
In index.php within body you can do like this one
<input type="hidden" name="hidden_id" id="hidden_id" value="<?=$_GET['id']?>">
In JS :
If you are using jQuery,then you should do like this one.
$(document).ready(){
var strHiddenId = $("#hidden_id").val();
$(".results").html(strHiddenId);
}

Upload multiple images parse.com javascript

I'm trying to make a multiple upload in parse.com with javascript code.
I have managed to upload one image into a class but now i want multiple images to be uploaded in different rows.
I have tried this
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script src="http://www.parsecdn.com/js/parse-latest.js"></script>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<script type="text/javascript">
$(document).ready(function() {
Parse.initialize("APPID", "JSKEY");
function saveJobApp(objParseFile) {
var jobApplication = new Parse.Object("imagemagazia");
jobApplication.set("imagename", objParseFile);
jobApplication.save(null, {
success: function(gameScore) {
alert("succesfull save image");
},
error: function(gameScore, error) {
alert('Failed to create new object, with error code: ' + error.description);
}
});
}
$('#submitId').on("click", function(e) {
PhotoUpload();
});
function PhotoUpload() {
var test = [];
console.log("edw");
var fileUploadControl = $("#profilePhotoFileUpload")[0];
for (i=0; i<3; i++){
var file = fileUploadControl.files[i];
//test.push(file);
var name = file.name; //This does *NOT* need to be a unique name
console.log(name +" : "+file);
//}
console.log(test);
//var t = [];
//for(j=0; j<test.length; j++){
var parseFile = new Parse.File(name, file);
//t.push(parseFile);
//var nw = t[i];
parseFile.save().then(
function() {
saveJobApp(parseFile);
},
function(error) {
alert("error");
}
);
}
}
});
</script>
</head>
<body>
<form id="business_form" method="post">
<table>
<tr>
<td>Image</td>
<td><input type="file" id="profilePhotoFileUpload" multiple></td>
</tr>
<tr>
<td><input type="button" id="submitId" value="submit"></td>
</tr>
</table>
</form>
</body>
</html>
UPDATE. with the above code i am trying to upload 3 images.
"1.jpg" "2.jpg" "3.jpg"
but it uploads only 3.jpg because its the last one.
Any idea?
I noticed it's better to make a loop the function itself externally and not making a loop in the function.
if you try making it like this :
$('#submitId').on("click", function(e) {
var fileUploadControl = $("#profilePhotoFileUpload")[0];
console.log(fileUploadControl.length);
for (i=0; i<3; i++){
var file = fileUploadControl.files[i];
var name = file.name;
PhotoUpload(name, file);
}
});
And then :
function PhotoUpload(objname, objfile) {
console.log(objname);
console.log(objfile);
var parseFile = new Parse.File(objname, objfile);
parseFile.save().then(
function() {
saveJobApp(parseFile);
},
function(error) {
alert("error");
}
);
}
Also if want to add more than tree images, you just add this :
for (i=0; i<fileUploadControl.files.length; i++)

It works with jquery 1.8.0 but not working in jquery 10.3 jqueryui - jeasyui

I'm trying to insert an external html file into a panel/div. I'm using jquery and jeasyui to do this.
I used the onload function to create a panel and load external html file via jquery, as shown below:
<script type="text/javascript">
$(function(){
$('#tt').tabs({
onLoad:function(panel){
var plugin = panel.panel('options').title;
panel.find('textarea[name="code-'+plugin+'"]').each(function(){
var data = $(this).val();
data = data.replace(/(\r\n|\r|\n)/g, '\n');
if (data.indexOf('\t') == 0){
data = data.replace(/^\t/, '');
data = data.replace(/\n\t/g, '\n');
}
data = data.replace(/\t/g, ' ');
var pre = $('<pre name="code" class="prettyprint linenums"></pre>').insertAfter(this);
pre.text(data);
$(this).remove();
});
prettyPrint();
}
});
});
function open1(plugin){
if ($('#tt').tabs('exists',plugin)){
$('#tt').tabs('select', plugin);
} else {
$('#tt').tabs('add',{
title:plugin,
href:plugin+'.html',
closable:true,
extractor:function(data){
data = $.fn.panel.defaults.extractor(data);
var tmp = $('<div></div>').html(data);
data = tmp.find('#content').html();
tmp.remove();
return data;
}
});
}
}
</script>
<script type="text/javascript" src="prettify.js"></script>
<script type="text/javascript" src="jquery-1.8.10.js"></script>
<script type="text/javascript" src="jquery.easyui.min.js"></script>

oAuth Fails: Is not allowed … Access-Control-Allow-Origin

what's wrong here?
OPTIONS https://twitter.com/oauth/request_token 401 (Unauthorized)
jsOAuth-1.3.4.js:483 XMLHttpRequest cannot load
https://twitter.com/oauth/request_token. Origin "http://localhost:8080"
is not allowed by Access-Control-Allow-Origin.Object
<!DOCTYPE html>
<html>
<head>
<!--
A simple example of PIN-based oauth flow with Twitter and jsOAuth.
This is mostly based on/copied from <http://log.coffeesounds.com/oauth-and-pin-based-authorization-in-javascri>.
Get jsOAuth at <https://github.com/bytespider/jsOAuth/downloads>
-->
<meta charset="utf-8">
<title>jsOauth test</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script type="text/javascript" src="jsOAuth-1.3.4.js"></script>
<style type="text/css" media="screen">
</style>
<script>
$(document).ready(function() {
var options = {
consumerKey: 'YOUR_CONSUMER_KEY',
consumerSecret: 'YOUR_CONSUMER_SECRET'
};
var requestParams;
var accessParams;
var oauth = OAuth(options);
oauth.get('https://twitter.com/oauth/request_token',
function(data) {
console.dir(data);
window.open('https://twitter.com/oauth/authorize?'+data.text);
requestParams = data.text
},
function(data) { alert('darn'); console.dir(data) }
);
$('#pinbutton').click(function() {
if ($('#pin').val()) {
oauth.get('https://twitter.com/oauth/access_token?oauth_verifier='+$('#pin').val()+'&'+requestParams,
function(data) {
console.dir(data);
// split the query string as needed
var accessParams = {};
var qvars_tmp = data.text.split('&');
for (var i = 0; i < qvars_tmp.length; i++) {;
var y = qvars_tmp[i].split('=');
accessParams[y[0]] = decodeURIComponent(y[1]);
};
oauth.setAccessToken([accessParams.oauth_token, accessParams.oauth_token_secret]);
getHomeTimeline();
},
function(data) { alert('poop'); console.dir(data); }
);
}
});
function getHomeTimeline() {
oauth.get('https://api.twitter.com/1/statuses/home_timeline.json',
function(data) {
entries = JSON.parse(data.text);
var html = [];
for (var i = 0; i < entries.length; i++) {
html.push(JSON.stringify(entries[i]));
};
$('#timeline').html(html.join('<hr>'));
},
function(data) { alert('lame'); console.dir(data); }
);
}
});
</script>
</head>
<body>
<h1>jsOauth test</h1>
When you get a PIN, enter it here.
<input id="pin" type="text" value=""><button id='pinbutton'>Save</button>
<div id="timeline">
</div>
</body>
</html>
I could give you the answer, but what you're doing is against the Twitter API Terms of Service. OAuthing in JavaScript exposes the secret credentials to anyone who visits the site and that is A Bad Thing. Please do this on your back-end.

Categories

Resources