Reload jsTree data return in an Ajax Request - jstree

My jsTree contains html data that is set when the tree loads (see javascript below). This works correctly. However, I want to be able to reload the entire tree in an Ajax request based on certain user actions. I basically need to reload all the tree data returned from the Ajax request. Is this possible?
My current code is below:
function setJoinType(node, joinType) {
$.ajax({
type: "POST",
url: "qbwizard.aspx/SetJoinType",
contentType: "application/json; charset=utf-8",
data: "{'alias': '" + node[0].id + "', 'joinType': '" + joinType + "'}",
dataType: "json",
success: RedrawJoinSummary,
error: AjaxFailed
});
return true;
}
function RedrawJoinSummary(data) {
//$("#tvJoinSummary").jstree('destroy');
$("#tvJoinSummary").jstree("html", data.d);
$("#tvJoinSummary").jstree("refresh", -1);
}

Thanks Radek.
I actually got this to work by putting the jstree intialization code into a function (tvJoinWorkspaceTreeviewScriptInit) and then calling that function after resetting the html. The probably is that the nodes all lose their state (opened / closed). I decided to use Ajax callbacks and javascript to build the tree again because it ended up being much easier to do.
$("div#tvJoinWorkspace").html(data);
$("#tvJoinWorkspace").jstree("destroy");
tvJoinWorkspaceTreeviewScriptInit(null);

What about this one? If you define your tree by
$("#jstree").jstree({ and you html is
<div id="tree">
<div id="jstree">
</div>
</div>
then you can
replace the <div id="jstree"></div> with something like <div id="jstree_ajax"></div>

Related

DOM elements not accessible after onsen pageinit in ons.ready

I am using the Onsen framework with jQuery and jQuery mobile, it appears that there is no way to catch the event that fires once the new page is loaded.
My current code, which executes in the index.html file (the master page)
<script src="scripts/jQuery.js"></script>
<script src="scripts/jquery.mobile.custom.min.js"></script>
<script src="scripts/app.js"></script>
<script>
ons.bootstrap();
ons.ready(function() {
$(document.body).on('pageinit', '#recentPage', function() {
initRecentPage();
});
});
in app.js is the following code
function initRecentPage() {
$("#yourReports").on("tap", ".showReport", recentShowReport);
var content = document.getElementById("yourReports");
ons.compile(content);
}
and the HTML:
<ons-page id="recentPage">
<ons-toolbar id="myToolbar">
<div id="toolBarTitle" class="center">Recent Checks</div>
<div class="right">
<ons-toolbar-button ng-click="mySlidingMenu.toggleMenu()">
<ons-icon icon="bars"></ons-icon>
</ons-toolbar-button>
</div>
</ons-toolbar>
<ons-scroller>
<h3 class="headingTitle"> Checks</h3>
<div id="Free" class="tabArea">
<ons-list id="yourReports">
</ons-list>
<ons-button id="clearFreeRecentButton">
<span id="clearRecentText" class="bold">Clear Recent Checks</span>
</ons-button>
</div>
</ons-scroller>
</ons-page>
in this instance the variable 'content' is always null. I've debuged significantly, and the element I am trying to get is not present when this event fires. It is loaded later.
So, the question is, how do I ensure that all of the content is present before using a selector. It feels like this is an onsen specific issue.
In the end I could only find one reliable way of making this work.
Essentially I had to wait, using setTimeout 300 milliseconds for the DOM elements to be ready. It feels like a hack, but honestly there is no other reliable way of making this behave. The app is in the app store and works well, so even though it seems like a hack, it works:
$(document).on('pageinit', '#homePage', function() {
initHomePage();
});
function initHomePage() {
setTimeout(function() {
setUpHomePage();
}, 300);
}
Move your $(document.body).on('pageinit', '#recentPage', function() { outside of ons.ready block.
JS
ons.bootstrap();
ons.ready(function() {
console.log("ready");
});
$(document.body).on('pageinit', '#recentPage', function() {
initRecentPage();
});
function initRecentPage() {
//$("#yourReports").on("tap", ".showReport", recentShowReport);
var content = document.getElementById("yourReports");
alert(content)
ons.compile(content);
}
I commented out a line because I do not have access to that "recentShowReport"
You can see how it works here: 'http://codepen.io/vnguyen972/pen/xCqDe'
The alert will show that 'content' is not NULL.
Hope this helps.

Passing dynamic values on page redirect

I have a GUI with various fields in which user can enter data.
I have a button.
I want to pass values entered by user on the GUI, and on the button click, I want to pass those values to another page where i can use them.
Note: No form/No onSubmit/No form action, it is just a page redirect to another page using a button.
Based on some markup:
<div id="x">Some data</div>
<div id="y">Some more data</div>
jQuery script to retrieve the data you want:
$("my button/link/whatever").click(function(e) {
e.preventDefault();
var data = {
x: $("#x").text(),
y: $("#y").text()
};
var req = $.ajax({
url: "the page to send data to",
type: "post",
data: data
});
req.done(function(response) {
// Do something here once the request is complete
});
});
Or use a second form.

jquery / ajax form not passing button data

I thought the HTML spec stated that buttons click in a form pass their value, and button "not clicked" did not get passed. Like check boxes... I always check for the button value and sometimes I'll do different processing depending on which button was used to submit..
I have started using AJAX (specifically jquery) to submit my form data - but the button data is NEVER passed - is there something I'm missing? is there soemthing I can do to pass that data?
simple code might look like this
<form id="frmPost" method="post" action="page.php" class="bbForm" >
<input type="text" name="heading" id="heading" />
<input type="submit" name="btnA" value="Process It!" />
<input type="submit" name="btnB" value="Re-rout it somewhere Else!" />
</form>
<script>
$( function() { //once the doc has loaded
//handle the forms
$( '.bbForm' ).live( 'submit', function() { // catch the form's submit event
$.ajax({ // create an AJAX call...
data: $( this ).serialize(), // get the form data
type: $( this ).attr( 'method' ), // GET or POST
url: $( this ).attr( 'action' ), // the file to call
success: function( response ) { // on success..
$('#ui-tabs-1').html( response );
}
});
return false; // cancel original event to prevent form submitting
});
});
</script>
On the processing page - ONLY the "heading" field appears, neither the btnA or btnB regardless of whichever is clicked...
if it can't be 'fixed' can someone explain why the Ajax call doesn't follow "standard" form behavior?
thx
I found this to be an interesting issue so I figured I would do a bit of digging into the jquery source code and api documentation.
My findings:
Your issue has nothing to do with an ajax call and everything to do with the $.serialize() function. It simply is not coded to return <input type="submit"> or even <button type="submit"> I tried both. There is a regex expression that is run against the set of elements in the form to be serialized and it arbitrarily excludes the submit button unfortunately.
jQuery source code (I modified for debugging purposes but everything is still semantically intact):
serialize: function() {
var data = jQuery.param( this.serializeArray() );
return data;
},
serializeArray: function() {
var elementMap = this.map(function(){
return this.elements ? jQuery.makeArray( this.elements ) : this;
});
var filtered = elementMap.filter(function(){
var regexTest1= rselectTextarea.test( this.nodeName );
var regexTest2 = rinput.test( this.type ); //input submit will fail here thus never serialized as part of the form
var output = this.name && !this.disabled &&
( this.checked || regexTest2|| regexTest2);
return output;
});
var output = filtered.map(function( i, elem ){
var val = jQuery( this ).val();
return val == null ?
null :
jQuery.isArray( val ) ?
jQuery.map( val, function( val, i ){
return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}) :
{ name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}).get();
return output;
}
Now examining the jQuery documentation, you meet all the requirements for it to behave as expected (http://api.jquery.com/serialize/):
Note: Only "successful controls" are serialized to the string. No submit button value is serialized since the form was not submitted using a button. For a form element's value to be included in the serialized string, the element must have a name attribute. Values from checkboxes and radio buttons (inputs of type "radio" or "checkbox") are included only if they are checked. Data from file select elements is not serialized.
the "successful controls link branches out to the W3 spec and you definitely nailed the expected behavior on the spec.
Short lame answer: I think it is teh broken! Report for bug fix!!!
I've run into a rather unusual issue with this. I'm working on a project and have two separate php pages where one has html on the page separate from the php code and one is echoing html from inside php code. When I use the .serialize on the one that has the separate html code it works correctly. It sends my submit button value in its ajax call to another php page. But in the one with the html echoed from the php script I try to do the same thing and get completely different results. It will send all of the other info in the form but not the value of the submit button. All I need it to do is send whether or not I pushed "Delete" or "Update". I'm not asking for help (violating the rules of asking for help on another persons post) but I thought this info might be helpful in figuring out where the break down is occurring. I'll be looking for a solution and will post back here if I figure anything out.

How to manipulate forms with Mootools

I'm trying to manipulate forms with Mootools. My purpose is to inject the response content of a form into a div element named result.
Here a code that works, but it replaces the content of the result div. This is not what I want : I want to ADD the form response content to the result div existing content. I just can't find on the web how to do this, and I've tried many things that are not working ... Please help
window.addEvent('domready', function() {
$('myform').addEvent('submit', function(e) {
e.stop();
var result = $('result').empty();
this.set('send',{
url: this.get('action'),
data: this,
onSuccess: function() {
result.set("html", this.response.text);
}
}).send();
});
});
If it's only text you want to add, just remove the empty method, and replace result.set() with result.appendText().
If you need to append an element tree, repeat the first step, and do:
onSuccess: function(){
Elements.from(this.response.text).inject(result);
}
Btw. It's all in the documentation - http://mootools.net/docs/core/Element/Element

Problem posted data with jQuery submit()

I have the script below. I am trying to POST the data and insert it into a database, the jQuery executes just fine, but does not post anything, the action is working properly because when i post the data without the script, the data posts fine and is inserted into the database fine without any errors, so it seems as if the jquery function is posting nothing. can someone please help?
$('#form').live('submit',function(){
$('#form').fadeOut('slow');
$('#div').append("<h2>submittes</h2>");
return false;
});
<form id="form" method="post" action="execute.php" name="form">
<textarea id="text" name="update"></textarea>
<br>
<input type="submit" value="update" id="update-submit">
</form>
EDIT:
$('#form').live('submit',function(){
var updateTextArea = $('#textarea').val();
$.ajax({
type: "POST",
url: "execute.php",
data: updateTextArea,
success: function() {
$('#form').fadeOut('slow');
$('#div').append("<h2>updated</h2>");
}
});
return false;
});
this is what i have for the ajax, but i am still not having any success.
You don't have any AJAX calls in your javascript. You're just fading out the form, appending an h2, and preventing the default action from occurring (which would be to submit the form normally).
Here's a basic example of how to create a POST ajax request:
$('#form').submit(function(){
$.post($(this).attr('action'), { update: $(this).find('#text).val() }, function(){
// success
});
});
Checkout the jQuery API/Docs for more info on this. There are also dozens of tutorials lurking around the net on how to do this.
Well, by returning false from the event handler function, you trigger two things:
prevent the default action (.preventDefault())
stop the event propagation (.stopPropagation())
This prevents that the submit ever happens.
You need to transfer the data on your own within the submit event handler. For instance, create an ajax request which serializes the form data and sends it to your server.
Could look like:
$('#form').live('submit',function(){
$('#form').fadeOut('slow');
$('#div').append("<h2>submittes</h2>");
$.post('execute.php', $(this).serialize(), function(data) {
// do something after success
});
return false;
});