While loop is not working properly in angularjs - javascript

I am trying to use while loop in Angular.
If I use alert in while loop, it give same quantity output. but I remove alert, the quantity is different. So what is wrong in my code.
var quantity= $scope.quantity;
var i=0;
while(i< quantity)
{
order.createOrderLineItem( localStorage.getItem( "orderID" ), itemStr, undefined, $scope.errorCallback )
.success(function(data){
$scope.lineItemID = data.id;
alert("i:"+i);
var orderLineItemData = {};
if( $scope.cusNote == "" )
{
var existedNote = data.note || "";
orderLineItemData = {
"unitQty": $scope.quantity,
"note": existedNote,
};
//if adding taxRates 0, clover will returns error
if($scope.taxRates !== 0) {
orderLineItemData.taxRates = $scope.taxRates;
}
}
else
{
var customerNote = "";
if( data.note != undefined && data.note != null ) customerNote = data.note;
customerNote = customerNote + "#order-request-[";
customerNote = customerNote + $scope.cusNote;
customerNote = customerNote + "]";
customerNote = customerNote.replace(/\\/g, '\\\\');
customerNote = customerNote.replace(/\"/g, '\\"');
console.log( "customerNote:" + customerNote );
orderLineItemData = {
"unitQty":$scope.quantity,
"note": customerNote,
"taxRates": $scope.taxRates
}
}
order.updateOrderLineItem( localStorage.getItem( "orderID" ), $scope.lineItemID, JSON.stringify(orderLineItemData), undefined, $scope.errorCallback )
.success( function( data ){
if( $scope.modCount == 0 )
{
location.href = "/" + $routeParams.slug;
}
$scope.addModifierItem( $scope.lineItemID );
});
});
i++;
}
So how can I correct this code?

I am not sure but, alert may be the reason of that. Can you try to use console.log("i:"+i); instead of the alert. Browser may interrupt when you use alert because of the pop up.
--Edited--
this is the service that you will need to implement into your application. You will need to notify this service at your success and it will trigger any observe that is implemented after the notify
app.service('checkService',['$q',function($q){
var checkRequest = $q.defer();
this.notifyRequestIsDone= function(){
checkRequest .notify();
};
this.observeRequestStatus = function(){
return checkRequest .promise;
};
}]);
Here is observe example of the code above add this to your controller where you need to increase your value after the request is done
checkService.observeRequestStatus ().then(null,null,function(){
//... Your code
});

Related

how to create an ajax request when server file(like php) doesnt exist?

i was developing sharetronix script but there is something realy odd about this script i can see in console network request goes for example for this address
http://localhost/ajax/postform-submit/ajaxtp:xml/r:0
but i cant find any folder with postform-submit name.i know this is possible with redirection using htaccess but i cant find anything in htaccess file.
this is part of js code where this request send
function postform_submit_step4()
{
var req = ajax_init(true);
if( ! req ) { return; }
var p = "post_temp_id="+encodeURIComponent(pf_data.temp_id)+"&message="+encodeURIComponent(pf_data.message);
if( pf_data.existing_post_id != "" ) {
p += "&editpost="+encodeURIComponent(pf_data.existing_post_id);
}
else if( pf_data.share_with_type == "user" ) {
p += "&username="+encodeURIComponent(pf_data.share_with_xtra);
}
else if( pf_data.share_with_type == "group" ) {
p += "&groupname="+encodeURIComponent(pf_data.share_with_xtra);
}
if( pf_data.at_link[0] ) {
p += "&at_link="+encodeURIComponent(pf_data.at_link[0]);
}
if( pf_data.at_image[0] ) {
p += "&at_image="+encodeURIComponent(pf_data.at_image[0]);
}
if( pf_data.at_file[0] ) {
p += "&at_file="+encodeURIComponent(pf_data.at_file[0]);
}
if( pf_data.at_videoembed[0] ) {
p += "&at_videoembed="+encodeURIComponent(pf_data.at_videoembed[0]);
}
req.onreadystatechange = function() {
if( req.readyState != 4 ) { return; }
if( ! req.responseXML ) { return; }
var data = req.responseXML.getElementsByTagName("result");
if( !data || !data[0] ) { return; }
data = data[0];
var status = data.getElementsByTagName("status");
var message = data.getElementsByTagName("message");
if( !status || !status[0] || !message || !message[0] ) {
return;
}
status = status[0].firstChild.nodeValue;
message = message[0].firstChild.nodeValue;
if( status != "OK" ) {
d.getElementById("pf_postederror_msg").innerHTML = message;
postform_htmlobject_hide("pf_posting");
postform_htmlobject_show("pf_postederror", 36);
postform_htmlobject_show("pf_mainpart", 114, function() { pf_open_state=1; pf_post_state=3; d.post_form.message.disabled=false; d.post_form.message.focus(); });
return;
}
d.getElementById("pf_postedok_msg").innerHTML = message;
postform_htmlobject_hide("pf_posting");
postform_htmlobject_show("pf_postedok", 36, function() { pf_open_state=0; pf_post_state=1; postform_statusmsg_setTimeout(); });
var btn = d.getElementById("postform_open_button");
if(btn) {
btn.style.display = "";
}
if( posts_synchronize ) {
posts_synchronize();
}
var pinf = pf_data.existing_post_id;
if( pinf != "" ) {
pinf = pinf.split("_");
var tmp = w.location.href.toString();
tmp = tmp.replace(/^http(s)?\:\/\//, "");
tmp = tmp.substr(tmp.indexOf("/"));
var mtch = "/view/"+(pinf[0]=="public"?"post":"priv")+":"+pinf[1];
if( tmp.substr(0,mtch.length)==mtch ) {
if( viewpost_synchronize ) {
viewpost_synchronize();
}
else {
w.location.href = w.location.href.toString();
}
}
}
}
req.open("POST", siteurl+"ajax/postform-submit/ajaxtp:xml/r:"+Math.round(Math.random()*1000), true);
req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
req.send(p);
}
how is this possible when there is no redirection?
The script is not odd: the way an URL maps to a file not always is so straightforward.
Most web frameworks, for example, use a router/dispatcher to decide what to do/which file to serve given a specific URL.
For example, most MVC web frameworks by default would handle this URL:
http://www.example.com/users/edit/5
by calling the action/method "edit" of the controller "users" passing an argument 5.
Long story short, redirects are not the only way an URL can be mapped to a physical file on the webserver.
To find which file is served or which file contains the code that is executed to produce what you receive, you first need to know which application server/framework is used, and learn how it works.

How to handle execution of javascript in infinite scroll?

I am using infinite scroll to load posts and tried to integrate a custom like button for every single posts that needs a small jquery script to work. My problem is I added this Jquery directly after the sucess in ajax load posts. But when I load eg the 3. page my jquery script executes twice and on the posts of the 2nd page the lke buttons are not working correctly. How can I handle this? If I dont execute the code after the ajax request and only call this jquery code globally the like buttons do not work in the new loaded posts of the ajax infinite scroll. Maybe I need to stop the sript of before when eg loadin 3. page through the ajax infinite scroll but how? This is my code:
function load_more_posts(selector){
var url = $(selector).attr('href');
var data;
loading = true;
$.ajax({
url: url,
data: data,
success: function( data ) {
var $items = $( '.loading-content .item', data );
$new_anchor = $( selector, data );
$items.addClass('hidden');
if ( $('#cooked-plugin-page .result-section.masonry-layout .loading-content').length ){
$( '.loading-content').isotope( 'insert', $items );
} else {
$( '.loading-content').append($items);
setTimeout(function() {
$items.removeClass('hidden');
}, 200);
}
if($new_anchor.length) {
$(selector).attr('href', $new_anchor.attr('href'));
} else {
$(selector).remove();
}
loading = false;
$('.like-btn').each(function() {
var $button = $(this),
$icon = $button.find('> i'),
likedRecipes = $.cookie('cpLikedRecipes'),
recipeID = $button.attr('data-recipe-id');
cookied = $button.attr('data-cookied');
userLiked = $button.attr('data-userliked');
if ( cookied == 1 && typeof likedRecipes !== 'undefined' && likedRecipes.split(',').indexOf(recipeID) > -1 || userLiked == 1 ) {
$icon.removeClass('fa-heart-o').addClass('fa-heart');
}
});
$('#cooked-plugin-page .like-btn').on('click', function() {
var $button = $(this),
$icon = $button.find('> i'),
$count = $button.find('.like-count'),
count = parseInt($count.text()),
likedRecipes = $.cookie('cpLikedRecipes'),
recipeID = $button.attr('data-recipe-id'),
cookied = $button.attr('data-cookied'),
likeURL = $button.attr('href'),
likeAction;
if ( $icon.hasClass('fa-heart-o') ) {
$icon.removeClass('fa-heart-o').addClass('fa-heart');
count++;
if (cookied == 1){
if ( typeof likedRecipes === 'undefined' ) {
likedRecipes = recipeID;
} else {
likedRecipes = likedRecipes + ',' + recipeID;
}
$.cookie('cpLikedRecipes', likedRecipes, { expires: 365 } );
}
likeAction = 'like';
} else {
$icon.removeClass('fa-heart').addClass('fa-heart-o');
count--;
if (cookied == 1){
if ( typeof likedRecipes === 'undefied' ) {
return false;
}
}
if (cookied == 1){
var likedSplit = likedRecipes.split(','),
recipeIdx = likedSplit.indexOf(recipeID);
if ( recipeIdx > -1 ) {
likedSplit.splice( recipeIdx, 1 );
likedRecipes = likedSplit.join(',');
$.cookie('cpLikedRecipes', likedRecipes, { expires: 365 } );
likeAction = 'dislike';
}
} else {
likeAction = 'dislike';
}
}
$.ajax({
'url' : likeURL,
'data': {
'action' : 'cp_like',
'likeAction': likeAction
},
success: function(data) {
$count.text(data);
}
});
return false;
});
$('#cooked-plugin-page .tab-links a').on('click', function() {
var tab = $(this).attr('href');
if ( !$(this).is('.current') ){
$(this).addClass('current').siblings('.current').removeClass('current');
$('#cooked-plugin-page.fullscreen .tab').removeClass('current');
$(tab).addClass('current');
$win.scrollTop(0);
}
return false;
});
if($('.rating-holder').length) {
$('.rating-holder .rate')
.on('mouseenter', function() {
var $me = $(this);
var $parent = $me.parents('.rating-holder');
var my_index = $me.index();
var rated = $parent.attr('data-rated');
$parent.removeClass(function(index, css) {
return (css.match (/(^|\s)rate-\S+/g) || []).join(' ');
});
$parent.addClass('rate-' + (my_index + 1));
})
.on('mouseleave', function() {
var $me = $(this);
var $parent = $me.parents('.rating-holder');
var my_index = $me.index();
var rated = $parent.attr('data-rated');
$parent.removeClass(function(index, css) {
return (css.match (/(^|\s)rate-\S+/g) || []).join(' ');
});
if(rated !== undefined) {
$parent.addClass('rate-' + rated);
}
})
.on('click', function() {
var $me = $(this);
var $parent = $me.parents('.rating-holder');
var my_index = $me.index();
$('.rating-real-value').val(my_index + 1);
$parent.attr('data-rated', my_index + 1);
$parent.addClass('rate-' + (my_index + 1));
});
}
setTimeout(function() {
masonry();
}, 500);
}
});
}
There's a great plugin for scrolling. He has methods such as bund, unbind, destroy and e.t.c.:
https://github.com/infinite-scroll/infinite-scroll#methods

ng-mouseenter fires first time, string is not a function next

I have this code on my html page:
<span data-miid="{{ orden._id }}"
data-fetxa="{{orden.fetxa}}"
data-linea="1"
ng-mouseenter="arraton(orden.ref);"
ng-click="grafikoa(orden.ref);"
ng-if="isadmin"
ng-bind-html="orden.ref"
>{{orden.ref}}</span>
And this is the angular part:
$scope.arraton = function(val) {
if ( ( val === "" ) || ( val === undefined ) ) { return false; }
var of="";
val = val.replace("<BR>", "<br>");
val = val.replace("<BR />", "<br>");
val = val.replace("<br />", "<br>");
if (val === undefined) {
return false
}
var n = val.indexOf("<br>");
if (n > 0) {
var miarray = val.split('<br>');
of = miarray[1];
}
var url = "SOMEURL/delaoferta?of="+of;
$http.get(url)
.success(function (data) {
$scope.arraton = "A Frabricar: " + parseInt(data.QFabricar)
+ "<br />Iniciada: " + parseInt(data.QIniciada)
+ "<br />Fabricada: " + parseInt(data.QFabricada);
})
.error(function () {
console.log("error al obtener datos");
return;
});
}
The fact is that when I mouse over the span, the first time works fine, but then, I´m getting
TypeError: string is not a function
all the time a mouse over the span.
Any help or clue?
thx
The problem is the success of yout $http request, your setting an string when your ng-mouseenter need a function. Change a variable name and you are done.

Nodejs,redis autocompleter, closures

*Code rewritten
I'm trying to convert antirez's autocompleter to javascript to use it with node.js.
I can't pass the closure Problem. Maybe someone can help me out.
I see where the problems are but can't figure out how to solve them.
The while loop is firing, the break is not correct and won't work etc.
Code:
var acp = {
vars: {
dict : false,
count : false,
prefix : false,
rangeLen : 10,
start : false,
results : false,
range : false,
},
sendResults: function(){
console.log(acp.vars.results);
},
getzrank: function(){
redis.zrank( acp.vars.dict, acp.vars.prefix, function( err, start ){
acp.vars.start = start;
});
},
getzrange: function(){
redis.zrange( acp.vars.dict, acp.vars.start, parseFloat( acp.vars.start+acp.vars.rangeLen-1 ), function( err, range ){
acp.vars.range = range;
});
},
createAutocomplete: function(){
while( acp.vars.results.length != acp.vars.count ){
acp.getzrange();
acp.vars.start+=acp.vars.rangeLen;
if( ! acp.vars.range || acp.vars.range.length == 0 ) { break; }
for ( var i in acp.vars.range ){
var minLen = Math.min(i.length,acp.vars.prefix.length);
if( i.substr( 0, minLen ) != acp.vars.prefix.substr( 0, minLen ) ){
acp.vars.count = acp.vars.results.length;
}
if( i.substr( 0, i.length-1 ) == "*" && acp.vars.results.length != acp.vars.count) {
acp.vars.results.push( i.substr(0,-1) );
}
}
}
acp.sendResults();
},
init: function(dict,prefix,count){
acp.vars.range = false;
acp.vars.dict = dict;
acp.vars.prefix = prefix;
acp.vars.count = count;
acp.vars.results = [];
acp.vars.start = acp.getzrank();
if( ! acp.vars.start ){ acp.sendResults(); }
else{ acp.createAutocomplete(); }
}
}
The break statement is outside the scope of the while loop since its nested in the anonymous function. Not sure if that solves your problem.

Ajax File Upload Not Working for IE8

I'm having trouble uploading a file using a Javascript function that makes an Ajax call to a servlet. The file is uploaded perfectly when I use chrome, but not when I use IE8 (Go figure).
I used to have a file select button on the bottom of my form. When I clicked that button a function would be called and it would upload the file to the servlet using ajax. This worked perfectly in IE8, but the client wanted links instead. So now I have the links in the form, and the buttons hidden with css. The links call the click event of the buttons. Now the file uploading only works with Chrome, and not IE8.
The request never makes it to the servlet for some reason, and for some reason the ajax request returns success. Any idea what the problem might be?
Here is my code:
//Uploading a file
$("#uploaded_file").change(function() {
var filename = $(this).val();
if(isAcceptable(filename)) {
$.ajaxFileUpload
(
{
type: "POST",
url:'GenerateServlet',
secureuri:false,
fileElementId:'uploaded_file',
dataType: 'json',
success: function (data, status)
{
if(typeof(data.error) != 'undefined')
{
if(data.error != '')
{
alert(data.error);
}else
{
alert(data.msg);
}
}
fillTemplate(data);
}
}
)
}
else if(filename.length > 0){
$("#uploaded_file").val("");
alert("Invalid File! Please select another file")
}
});
$("#upload_link").click(function() {
document.getElementById('uploaded_file').click();
return false;
});
Here is the upload function:
jQuery.extend({
createUploadIframe: function(id, uri)
{
//create frame
var frameId = 'jUploadFrame' + id;
var iframeHtml = '<iframe id="' + frameId + '" name="' + frameId + '" style="position:absolute; top:-9999px; left:-9999px"';
if(window.ActiveXObject)
{
if(typeof uri== 'boolean'){
iframeHtml += ' src="' + 'javascript:false' + '"';
}
else if(typeof uri== 'string'){
iframeHtml += ' src="' + uri + '"';
}
}
iframeHtml += ' />';
jQuery(iframeHtml).appendTo(document.body);
return jQuery('#' + frameId).get(0);
},
createUploadForm: function(id, fileElementId, data)
{
//create form
var formId = 'jUploadForm' + id;
var fileId = 'jUploadFile' + id;
var form = jQuery('<form action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data"></form>');
if(data)
{
for(var i in data)
{
jQuery('<input type="hidden" name="' + i + '" value="' + data[i] + '" />').appendTo(form);
}
}
var oldElement = jQuery('#' + fileElementId);
var newElement = jQuery(oldElement).clone();
jQuery(oldElement).attr('id', fileId);
jQuery(oldElement).before(newElement);
jQuery(oldElement).appendTo(form);
//set attributes
jQuery(form).css('position', 'absolute');
jQuery(form).css('top', '-1200px');
jQuery(form).css('left', '-1200px');
jQuery(form).appendTo('body');
return form;
},
ajaxFileUpload: function(s) {
// TODO introduce global settings, allowing the client to modify them for all requests, not only timeout
s = jQuery.extend({}, jQuery.ajaxSettings, s);
var id = new Date().getTime()
var form = jQuery.createUploadForm(id, s.fileElementId, (typeof(s.data)=='undefined'?false:s.data));
Console.log(form);
var io = jQuery.createUploadIframe(id, s.secureuri);
var frameId = 'jUploadFrame' + id;
var formId = 'jUploadForm' + id;
// Watch for a new set of requests
if ( s.global && ! jQuery.active++ )
{
jQuery.event.trigger( "ajaxStart" );
}
var requestDone = false;
// Create the request object
var xml = {}
if ( s.global )
jQuery.event.trigger("ajaxSend", [xml, s]);
// Wait for a response to come back
var uploadCallback = function(isTimeout)
{
var io = document.getElementById(frameId);
try
{
if(io.contentWindow)
{
xml.responseText = io.contentWindow.document.body?io.contentWindow.document.body.innerHTML:null;
xml.responseXML = io.contentWindow.document.XMLDocument?io.contentWindow.document.XMLDocument:io.contentWindow.document;
}else if(io.contentDocument)
{
xml.responseText = io.contentDocument.document.body?io.contentDocument.document.body.innerHTML:null;
xml.responseXML = io.contentDocument.document.XMLDocument?io.contentDocument.document.XMLDocument:io.contentDocument.document;
}
}catch(e)
{
jQuery.handleError(s, xml, null, e);
}
if ( xml || isTimeout == "timeout")
{
requestDone = true;
var status;
try {
status = isTimeout != "timeout" ? "success" : "error";
// Make sure that the request was successful or notmodified
if ( status != "error" )
{
// process the data (runs the xml through httpData regardless of callback)
var data = jQuery.uploadHttpData( xml, s.dataType );
// If a local callback was specified, fire it and pass it the data
if ( s.success )
s.success( data, status );
// Fire the global callback
if( s.global )
jQuery.event.trigger( "ajaxSuccess", [xml, s] );
} else
jQuery.handleError(s, xml, status);
} catch(e)
{
status = "error";
jQuery.handleError(s, xml, status, e);
}
// The request was completed
if( s.global )
jQuery.event.trigger( "ajaxComplete", [xml, s] );
// Handle the global AJAX counter
if ( s.global && ! --jQuery.active )
jQuery.event.trigger( "ajaxStop" );
// Process result
if ( s.complete )
s.complete(xml, status);
jQuery(io).unbind()
setTimeout(function()
{ try
{
jQuery(io).remove();
jQuery(form).remove();
} catch(e)
{
jQuery.handleError(s, xml, null, e);
}
}, 100)
xml = null
}
}
// Timeout checker
if ( s.timeout > 0 )
{
setTimeout(function(){
// Check to see if the request is still happening
if( !requestDone ) uploadCallback( "timeout" );
}, s.timeout);
}
try
{
var form = jQuery('#' + formId);
jQuery(form).attr('action', s.url);
jQuery(form).attr('method', 'POST');
jQuery(form).attr('target', frameId);
if(form.encoding)
{
jQuery(form).attr('encoding', 'multipart/form-data');
}
else
{
jQuery(form).attr('enctype', 'multipart/form-data');
}
jQuery(form).submit();
} catch(e)
{
jQuery.handleError(s, xml, null, e);
}
jQuery('#' + frameId).load(uploadCallback );
return {abort: function () {}};
},
uploadHttpData: function( r, type ) {
var data = !type;
data = type == "xml" || data ? r.responseXML : r.responseText;
// If the type is "script", eval it in global context
if ( type == "script" )
jQuery.globalEval( data );
// Get the JavaScript object, if JSON is used.
if ( type == "json" )
eval( "data = " + data );
// evaluate scripts within html
if ( type == "html" )
jQuery("<div>").html(data).evalScripts();
return data;
}
})
That is a typical Microsoft security measure (e.g. to stop automated uploads).
That means you have to originate an upload from an actual user-pressed button click.
Style the button to make it look like a link instead.

Categories