Two ajax function calls on single click - ajax

I've some folders in a div and contents of those folders are shown in tree view(when small plus button is clicked) using following code:
echo '<span class="toggle" onclick="getchildren(\''.$objectnode["fid"].'\', \'childdiv'.$objectnode["fid"].'\');" ></span>';
when folder is clicked,its contents are shown in another div,parallel to it using following code:
<span><?php echo $objectnode["object_name"]; ?></span>
Now what i want to do is, when i click on folder name,its contents should be load in div parallel to it as well as its child nodes should also be visible or expand at the same time. Any help will be appreciated

Just make two ajax calls. Ajax calls are asynchronous and you can make as many as you like. For example, you could do something like this:
function ajax(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.open('POST', 'yourpage.php', true);
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
// Your callback code goes here
xmlhttp.responseXML; // this is the response data
}
};
xmlhttp.send(yourdatahere);
var xmlhttp2 = new XMLHttpRequest();
xmlhttp2.open('POST', 'yourpage.php', true);
xmlhttp2.onreadystatechange = function() {
if (xmlhttp2.readyState == 4) {
// Your callback code goes here
xmlhttp2.responseXML; // this is the response data
}
};
xmlhttp2.send(yourdatahere);
}
Call this function from your onclick function and that should do the trick. You can also nest the function calls. For example, if you're waiting on data from the first call, put the second ajax call in the callback from the first and do all of the updating. You won't need to wait for the second ajax call to return to update the DOM.
You could also make a separate ajax call for each child node, and if you want to do that for all of the child nodes, you'll have to do some recursion, such as:
function ajax(parentNode){
var xmlhttp = new XMLHttpRequest();
xmlhttp.open('POST', 'yourpage.php', true);
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
// Your callback code goes here
xmlhttp.responseXML; // this is the response data
// do stuff with responseXML
}
};
xmlhttp.send(yourdatahere);
var i;
for(i = 0; i < parentNode.childNodes.length; i++){
ajax(parentNode.childNodes[i]);
};
}
There are already plugins made for this. I know jQuery has one for it's framework. I built my own because it wasn't exactly what I wanted. I hope this helps!

Related

Aframe: Binding Async data within Aframe using API response

I am trying to find out if we can integrate an API response within Aframe scene. For example, I want to get the information about an entity object when I move my cursor over it.
I know we can have maintained these static data with an a-text, but I am looking for AJAX based integration so that I can add/edit data from the backend.
Please advise.
You could use a custom component, which will grab the text and use it as an <a-text> value. Execute the AJAX call inside an event listener (like a click, or any other one):
AFRAME.registerComponent("foo", {
init: function() {
let self = this.el
this.el.addEventListener("click", (e)=>{
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
self.children[0].setAttribute("value", this.responseText;
}
};
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
})
}
})
In a setup like this:
<a-entity foo>
<a-text></a-text>
</a-entity>
Something like this, exept with the ajax call, i took the ajax code from w3schools.

iScroll Ajax content

i have problem with refreshing content in wrapper after it is loaded by ajax.
When i check with firebug - XHR is showing request and i can see elements loaded but it isn't showing on page.
This is what i am using for pullDown function to get ajax content
function pullDownAction () {
setTimeout(function () {
var el, li, i;
el = document.getElementById('thelist');
var http = new XMLHttpRequest();
var url = window.location;
http.open("GET",url,true);
http.send();
myScroll.destroy();
myScroll = null;
loaded();
}, 1000);
}
It looks like as content is stuck between showing on webpage and ajax request.
Any idea?
myScroll.refresh() (instead of .destroy() and recalling "loaded()") should do the trick!
If you're using IScroll4 you can try to use the checkDOMChanges:true option of iscroll.
If it still won't work - it could be a CSS issue caused by the scroll-wrapper (#scroller) not expanding with its content. (float,position:absolute; or something like that)
EDIT: it seems to me as you're not handling a responseText of the request at all!
According to this example you need an event handler for the onreadystatechange event:
http.open("GET",url,true);
http.onreadystatechange = function () {
if (http.readyState == 4) {
alert(http.responseText); //handle this response! (i.e. writing to an element's innerHTML)
}
};
http.send(null);

JQuery ajax calls collision using Play! framework

When some action is invoked in my page, I make two ajax calls (A, B) to two different methods on my server.
Most of the times each request gets its matching response, but here and there both requests gets the same response! (of one of the requests - A,A or B,B)
The Ajax calls are made using JQuery and the server methods are implemented using Play! framework (in java).
Does anyone have any idea why does it happen and how to resolve it?
Thanks!
Ajax Call A:
var renderTypePreviewPageRoute = jsRoutes.com.eyeview.connectad.controllers.solutions.FeedLibrary.getFeedTypePreviewPage(feedHashId, feedType);
// Makes an ajax call that gets the rendered solution page
$.ajax({
// Sets the route (URL) of the server call
url:renderTypePreviewPageRoute.url,
// Sets the method (GET / POST) of the server call
type:renderTypePreviewPageRoute.method,
//data:{ hashId: feedHashId, feedType: feedType, withPreview: withPreview }-->
// In case of success
success:function(result) {
var typePreviewElement = $('#typePreviewSection');
// Set the feed preview section html content to the rendered content got from the server
typePreviewElement.html(result);
typePreviewElement.removeClass('hidden');
$('#feedPreviewGrid tr:eq(1)').removeClass('hidden');
if ($('#feedPreviewSection').is(':visible')){
typePreviewElement.show('blind');
}
var feedURL = urlEle.val();
if (waitForFileTypePreview && feedURL != "") {
feedEditNS.renderFilePreviewSection(true);
}
},
// In case of failure
error:function(xhr, ajaxOptions, thrownError) {
// Shows the error message
showError(xhr.responseText);
// Clears the preview section
feedEditNS.clearTypePreviewSection();
var feedURL = urlEle.val();
if (waitForFileTypePreview && feedURL != "") {
feedEditNS.renderFilePreviewSection(true);
}
}
Ajax Call B:
var renderFilePreviewPageRoute = jsRoutes.com.eyeview.connectad.controllers.solutions.FeedLibrary.getFeedFilePreviewPage(feedHashId);
// Makes an ajax call that gets the rendered solution page
$.ajax({
// Sets the route (URL) of the server call
url:renderFilePreviewPageRoute.url,
// Sets the method (GET / POST) of the server call
type:renderFilePreviewPageRoute.method,
// In case of success
success:function(result) {
// Set the feed preview section html content to the rendered content got from the server
$('#filePreviewSection').html(result);
// Shows the feed preview section
$('#verticalLine').show('blind');
$('#leftShadow').show('blind');
$('#rightShadow').show('blind');
$('#feedPreviewSection').show('blind');
feedEditNS.createDataTable(withHeaders);
waitForFileTypePreview = false;
},
// In case of failure
error:function(xhr, ajaxOptions, thrownError) {
// Shows the error message
showError(xhr.responseText);
// Clears the preview section
feedEditNS.clearFilePreviewSection();
waitForFileTypePreview = false;
}
I could not resolve the problem.
So, I ended up combining both calls to one call to a single server side method.
This method returned a JSON object containing both calls answers.
I ran into this exact issue (3'ish years later...) I am still not sure what the real problem is, but as a workaround I ended up using setTimeout() inside my Angular controller.
myApp.controller('myCtrl', function($scope, myRestApi) {
$scope.restCallOne = function() {
myRestApi.callOne().then(
// handle result one
);
};
$scope.restCallTwo = function() {
myRestApi.callTwo().then(
// handle result two
);
};
// loads each time the view is shown
// *** race condition when calling consecutively without a delay ***
//$scope.restCallOne();
setTimeout($scope.restCallOne, 100);
$scope.restCallTwo();
});

Loading Varying Number of files with Ajax

I have an HTML page that dynamically loads one to many HTML snippets that are used as modal forms on the page. The page comes out of a CMS, so the business users can decide "I want one form on this page" or "I want 6 forms on this page". Each of the links and it's loading info need to be a module that goes together and can be put on any page. When each of these links are chosen on the page, I'm outputting a snippet of code that will call an Ajax load script when the page loads.
Snippet Example:
<script>
$(document).ready(function()
{
load('/web_fragments/file.html', 'content_item1');
$('#item1').click(function(){
$('#rmi_item1').dialog("open");
return false;
});
$('#rmi_item1.modal').dialog({autoOpen: false, modal:true,
dialogClass:'modal', width:590});});
</script>
Request More Information
<div id="rmi_item1" class="appLvl mod modal dialog">
<div id="content_item1">
</div>
</div>
Each of the IDs and divs on the page have unique identifiers, I've just simplified them here for ease of reading. The problem is the load method. I have no idea how many of these will be on the page, so I can't really create multiple load methods. If there is only one item on the page, it all works great. Here is the load method I have now. I'm new to Ajax/jQuery, so I extend my apologies and beg you to be kind! :)
function load(url, target)
{
document.getElementById(target).innerHTML = ' Fetching data...';
if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
} else if (window.ActiveXObject) {
req = new ActiveXObject("Microsoft.XMLHTTP");
}
if (req != undefined) {
req.onreadystatechange = function() {targetDiv(url, target);};
req.open("GET", url, true);
req.send("");
}
}
function targetDiv(url, target)
{
if (req.readyState == 4) { // only if req is "loaded"
if (req.status == 200) { // only if "OK"
document.getElementById(target).innerHTML = req.responseText;
}
}
}
Any suggestions or help is welcome as I am now officially about really to lose my mind over this error! Thanks!
I think your problem comes from this line
req = new XMLHttpRequest();
Here you use (and implicitly declare) a variable req. This variable is declared in the
global scope (window object)
Make this var local to the load function, like this
var req = new XMLHttpRequest();
This will prevent the second snippet to overwrite the req var and trash the first
snippet request that was just fired but not yet recieved.
Have a look to the jquery load method. This should make your code smaller and avoid
this problem.
hope this helps,

How to execute a page ,that contains JS ,in AJAX ,using innerHTML?

I send GET data with AJAX to another file.And on the another file I have echo "<script>alert('Something');</script>";.This is displayed dynamicly with AJAX ,i.e
var ajaxDisplay = document.getElementById('edit');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
puts the <script>alert('Something');</script> to div with name edit.
But it doesn't alert anything.
How to get it work?
I have mixed html/javascript.
Here is the code.
function ajaxFunctions(){
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('edit');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
var namef = document.getElementById('nameed').value;
var queryString = "?namef=" + namef;
ajaxRequest.open("GET", "try.php" + queryString, true);
ajaxRequest.send(null);
}
Maybe to find the script tags and to eval them?
But how to find the script tags?
Instead of trying to inject a script element in the DOM, just have your script return:
alert('Something');
And then use eval(response); to run it. Or you could add a script element with the src attribute pointing to the page that returns your JavaScript into the <head> (which is the preferred method).
function loadScript(url) {
var head = document.getElementsByTagName("head")[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = url;
head.appendChild(script);
}
Keep in mind that this wont work for cross-domain requests--the script has to have the same origin as the page running your code. To get around this, you'll have to use a callback.
It looks like the only purpose of setting innerHTML is an attempt to get the JS to execute. But once the page is loaded, JS won't 'know' that it needs to parse and execute the new text you've changed, so your method won't work. In this case, what you want is a callback function:
http://api.jquery.com/jQuery.ajax/
I haven't used jQuery, but it looks like you'd simply add a 'complete' property to the settings object you pass to the .ajax() call, like so:
$.ajax({
// ......
complete: function(){
alert('Something');
}
// ......
});
In this case, the callback function would execute once the ajax call has completed. You can pick other events, such as on success, on failure, and so on, if you need to attach your code to a different event.
But how to find the script tags?
Well, parent.getElementsByTagName('script') and then evaling the data of the text node inside will do it.
However, inserting content that includes script tags is unreliable and works slightly differently across browsers. eg. IE will execute the script the first time the script node is inserted into any parent, inside the document or not, whilst Firefox will execute script the first time a subtree including the script is added to a node inside the document. So if you're not extremely careful, you can end up executing scripts twice on some browsers, or executing the script at the wrong time, following a further page manipulation.
So don't. Return script that you want to execute separately to any HTML content, eg. using a JSON object containing both the HTML and the JavaScript seperately.

Resources