Angular JS data not populated from asynchronous http request - ajax

I am trying to get a loading div to show when my angular module is contacting the server. I am using AngularJS 1.0.1 and AngularJS Resources 1.0.1 to expand the functionality of the HTML and jquery 1.7.2 for some additional dom manipulation and ajax support.
I already found out that the loading div will not show if I run the ajax call in async false, except for Firefox where it shows but animated gif is not animated.
If I run the ajax call in async true, the data returned back does not get loaded into the angular model variables of the loaded template partial.
Is it at all possible to get an animated loading div to show and get the angular data to load into the model?

Hopefully I'm understanding you correctly. You want to show a loading progress for your ajax requests. To do this you need a response interceptor. Here is a an example of how to do this http://jsfiddle.net/zdam/dBR2r/
// register the interceptor as a service, intercepts ALL angular ajax http calls
.factory('myHttpInterceptor', function ($q, $window, $rootScope) {
return function (promise) {
$rootScope.nowloading = true; // use ng-show="nowloading" on element containing spinner
return promise.then(function (response) {
// do something on success
$rootScope.nowloading = false; // need to turn it off on success
return response;
}, function (response) {
// do something on error
$rootScope.nowloading = false; // need to turn it off on failure
$rootScope.network_error = true; // you might want to show an error icon.
return $q.reject(response);
});
};
hope this helps
--dan

Related

AJAX Updates with Angular

I am trying to implement a polling method in my client that uses AJAX. I am building an ASP.NET framework Web application, wit c# on the backend and I use JavaScript with Angular on the front end, but I am unsure of....
1.) If the code I have will actually do real time updates and update the displayed content on my web page like intended.
2.) If the way I am incorporating Angular into my AJAX request will work.
and 3.) If I need to specify 'get' in the body of the ajax request, like type: 'get';
I have a variable attached to $scope called instruments that I would like to update with the data from the url, and update my webpage if there are any changed to the data. Obviously the url will contain the actual URL where I wish to get data from. Here is my code thus far in my module...
var updates = function update() {
$.ajax({
url: '...',
success: function (data) {
$scope.instruments = data;
},
complete: function () {
setTimeout(update, 5000);
}
});
};
its easy with v_comet packge
import { V_ } from 'v_comet';
/**
title is the variable that need to change.
*/
V_('this.state.title', object); /** in react */
V_('this.title', object); /** in angular */
more details:
https://www.npmjs.com/package/v_comet

cannot click links contained within ajax response

I have some content returned via ajax, and that content contains some links, but if I click them nothing happens (they don't respond to the JS written for them). Then, If i refresh the page, the first time I click, it works, and then it doesn't again.
How can I make it work normally?
This is basically my ajax call:
$('a.add').click(function() {
var data = {
action: 'ADD_PROD'
};
// make the request
$.get(ajax_object.ajax_url, data, function(response) {
// $('#vru_div').html(data);
$('div.left').html(response);
});
// $('div.left').html('<img src=712.gif>');
// alert('code');
return false;
});
The new links won't have any event handlers attached to them.
try using
$('.left').on('click','a',function(){
//your logic
});

Using Infinite Scroll with AJAX and Mustache render

I have a jsp page in which I am loading the posts using AJAX which responds in JSON data. The HTML is rendered using the Mustache renderer. The question is how can I use this Infinite Scroll using this scenario. I have read that jQuery load() method can be used but I am not able to get it work. If anybody guide me that will be helpful.
var data = "";
$.getJSON("/ajax?command=getposts", function(returnedData){
console.log("bar"+returnedData);
var data = JSON.parse(JSON.stringify(returnedData));
//alert(JSON.stringify(returnedData));
console.log(data);
$.get('temp.html', function(templates)
{
var tpl = $(templates).filter('#content').html();
//console.log(data);
var html = Mustache.to_html(tpl, returnedData);
$('#posts').html(html);
$('#posts').imagesLoaded(function() {
$('#posts').freetile({
animate: true,
elementDelay: 30
});
});
});
});
This is the Jquery code that I use to load the posts in the container. I want to implement the Infinite Scroll which will call this method everytime the user scrolls.

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();
});

TinyMCE not working in http request xhr ajax generated page

So i I have a page that contains links that call an httpRequest. The request calls a php file that grabs data from mysql and pre populates a form which is then returned to the browser/webpage. My problem is that when the page is returned to the browser via the httpRequest/ajax the text area does not display the tinymce editor, it just displays a normal text area. It looks like my request and ajax is working fine the text area just doesn't have the tinycme editor on it.
When i don't use ajax it works fine but when i put it in a separate file and call it via ajax it doesn't bring in the tinymce editor.
Does anyone know how to fix this problem so that my ajax generated page displays the text area with the tinymce editor. Thank you.
Lets presume that your thinyMCE instance is initialized with code below
// initialize tinyMCE in page
tinyMCE.init({
mode: "textareas",
theme: "advanced"
});
and you have some kind of button somewhere in the page. For purpose of this tip, i will not give it any ID but you may. Now, using jQuery you can easily attach event handler to that button which will call through AJAX your server and take content which you want to put tinyMCE editor. Code which will do such job would look somehow like below.
$(function() {
$("button").bind("click", function() {
var ed = tinyMCE.get('content');
ed.setProgressState(1); // Show progress
$.getJSON('/page/12.json', { /* your data */
}, function(data) {
ed.setProgressState(0); // Hide progress
ed.setContent(data["body"]);
}
});
});
});
You can see that on button.click ajax will call url /page/12.json which will return JSON as response. bare minimum of that response could be:
{
title: "Page title",
body: "<html><head><title>Page title</title>......</html>"
}
I attached anonymous function as callback which will handle response from server. and hide progress indicator which is shown before ajax call.
About JSON
JSON is shorten of JavaScript Object Notation. It is JavaScript code!!! So don't be confused about it. Using JSON you can make javascript object which can have attributes you can use later in your code to access particular peace of data which that object "holds". You can look at it as some kind of data structure if it is easier to you.
Anyway, to show you how this JSON can be created by hand look at examples below
var data = new Object();
data.title = "Page title";
data.body = "<html....";
or
var data = {
title: "page title",
body: "<html...."
};
it is very same thing.
If you want to learn more about JSON point your browser to http://json.org.
===== alternative =====
Alternative to json solution could be just plane ajax call to server and response can be plain HTML (from your question I can assume that you have something like this already). So instad of calling $.getJSON you can use $.get(url, callback); to do same thing. The code at the top of my answer will not dramatically change. Instead of geting JSON in response you will get string which is HTML.
----------- BOTTOM LINE -------
I prefer JSON since it can be easily extended later with other attributes, so there is no painful code changes later ;)
Problem here will be that when you return the full page and render it using the ajax response, your tinymce instance has not been shut down before.
In order to do this you can call this small piece of code before you render the ajax response:
tinymce.execCommand('mceRemoveControl',true,'editor_id');
In this case the editor should initialize correctly. You are not allowed to initialize a tinymce editor with the same id before shutting the first one down.
Strangely i ran into this problem yesterday. Following code should work, but YMMV. Trick is to use the correct steps in ajax events. I used the Regular TinyMCE and made use of the jQuery library already included.
Following goes into your tinyMCE initialization tinyMCE.init() . All of the below block should be outside the document.ready.
myTinyInit = {
//.......All essential keys/values ...........
setup : function(ed) {
ed.onChange.add(function( ed ) {
tinyMCE.triggerSave();
}) }
//.....................
};
// Init the tinyMCE
tinyMCE.init(myTinyInit);
This ensures the content is being saved regularly onto the textarea that holds the value. Next step is setting up the request events.
Normally tinyMCE mceAddControl before the ajax post and mceRemoveControl after the ajax success should do the trick. But I found that often does not work.
I used the form as the jQuery selector in my case.
jQuery( '.myForm' )
.find( 'textarea#myTextArea' )
.ajaxStart(function() {
// If you need to copy over the values, you can do it here.
// If you are using jQuery form plugin you can bind to form-pre-serialize event instead.
// jQuery( this ).val( tinyMCE.get( jQuery( this ).attr( 'id' )).getContent() );
}).ajaxSend( function() {
// ! - step 2
// My case was multiple editors.
myEds = tinyMCE.editors;
for( edd in myEds ) {
myEds[ eds ].remove();
}
// tinyMCE.get( 'myTextarea' ).remove();
// strangely mceRemoveControl didnt work for me.
// tinyMCE.execCommand( 'mceRemoveControl', false, jQuery( this ).attr('id'));
}).ajaxSuccess(function() {
// Now we got the form again, Let's put up tinyMCE again.
txtID = jQuery( this ).attr( 'id' );
// ! - step 3
tinyMCE.execCommand( 'mceAddControl', false, txtID );
// Restore the contents into TinyMCE.
tinyMCE.get( txtID ).setContent( jQuery( this ).val());
});
Problems i came across :
Using mceRemoveControl always gave me r is undefined error persistently.
If you get a blank tinyMCE editor, check the DOM whether the ID of the textarea is replaced with something like mce_02, this means that TinyMCE is being initialized again or something is wrong with the order. If so, the tinyMCE is duplicated with each save.
if you are new to JS, I recommend using jQuery with the form plugin, it might be easier for you. But do use the regular non-jquery tinyMCE, as it is well documented.
I fixed this problem by recalling the function after the ajax call. In this part of my ajax:
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("Content").innerHTML=xmlhttp.responseText;
tinymce();
Now it works fine.

Resources