I am trying to get my chat script to work I have moved to a VPS thinking that should solve any missing extensions but I have the same problem.
A user logs into the website and can then load the chat to talk with other members - I am using the datingframework
in the console window I can see the message but socket.io keeps timing out I have tried using different ports and changing from https - http but get the same error
On their demo website when I send a chat I notice a different scroll event getting triggered before the message is displayed.
This is some of the chat js code as there is a limit on the amount I can post!!
/* this is main chat controller */
App.controller('WebsocketChatController',function($scope,$rootScope,$http, socket, $timeout,$location,$anchorScroll,Upload,$log,$timeout,screenSize) {
$scope.getSocketObj= function()
{
return socket;
}
/* socket operations */
$scope.socket_id = 0;
socket.on('connected', function(data){
$scope.socket_id = data.socket_id;
$scope.mapUserWithSocket();
});
//if not in chatUsers array take from ajax call
socket.on("new_message_received", function(data){
//$scope.getChatUsers();
var text = parseInt($(".notification-message").html());
if(isNaN(text)){
text= 0;
}
$(".notification-message").html(text+1);
console.log(JSON.stringify(data));
toastr.success(recieved_msg);
var user = $scope.findUserByID(data.from_user);
//toastr.success('You got a new message from '+user.user.name);
if(data.to_user==$scope.authUser)
{
data.recipient='other';
}
else
{
data.recipient='self';
}
user.user.messages.push(data);
if (user.user.last_msg == "" && user.user.id == $scope.chatUsers[$scope.selected].user.id) {
$('#third_img_div').show();
$('#first_img_div').hide();
$("#no-users-div").hide();
$("#fourth_div").hide();
}
if (data.type == 2) {
user.user.last_msg = data.meta;
user.user.last_msg_type = 2;
} else if (data.type == 0) {
user.user.last_msg = data.text;
user.user.last_msg_type = 0;
}
user.user.total_messages_count += 1;
var curr_user_id= "user-"+user.user.id;
//if user selected and user msg recieved are differed=nt then increment otherwise no
if(curr_user_id != $(".all_users").parent().find('.active').data('id'))
{
user.user.total_unread_messages_count += 1;
$scope.overall_unread_messages_count += 1;
}
var audio = new Audio("#plugin_asset('WebsocketChatPlugin/audio/ping.mp3')");
audio.play();
//$("#chat-container").scrollTop($("#chat-container").find("> .img_main_div_padding").height());
});
socket.on("new_message_sent", function(data){
var user = $scope.findUserByID(data.to_user);
if(data.to_user==$scope.authUser)
{
data.recipient='other';
}
else
{
data.recipient='self';
}
user.user.messages.push(data);
if (user.user.last_msg == "" && user.user.id == $scope.chatUsers[$scope.selected].user.id) {
$('#third_img_div').show();
$('#first_img_div').hide();
$("#no-users-div").hide();
$("#fourth_div").hide();
}
if (data.type == 2) {
user.user.last_msg = data.meta;
user.user.last_msg_type = 2;
} else if (data.type == 0) {
user.user.last_msg = data.text;
user.user.last_msg_type = 0;
}
// user.user.total_messages_count += 1;
// user.user.total_unread_messages_count += 1;
//$("#chat-container").scrollTop($("#chat-container").find("> .img_main_div_padding").height());
});
/*end of socket operations */
/* user online offline status */
socket.on('user_online', function(data){
var user = $scope.findUserByID(data.user_id);
if (user) {
user.online = 1;
}
});
socket.on('user_offline', function(data){
var user = $scope.findUserByID(data.user_id);
if (user) {
user.online = 0;
}
});
/* end user online offline status */
//event listening to contact delete
socket.on('contact_deleted', function(data){
$scope.getChatUsers();
});
$scope.isTypingUser=0;
/* typing stop and start notification */
socket.on('typing', function(data){
var user = $scope.findUserByID(data.from_user);
if (user) {
user.user.isTyping = true;
console.log(user.user.name + " is typing..");
//$scope.isTypingUser=1;
$('#typing_'+user.user.id).show();
}
});
socket.on('typing_stop', function(data){
var user = $scope.findUserByID(data.from_user);
if (user) {
user.user.isTyping = false;
console.log(user.user.name + " is stopped typing..");
$('#typing_'+user.user.id).hide();
}
});
$scope.typing = function(){
if (!$scope.type) {
$scope.type = true;
socket.emit('typing', {from_user: auth_user_id_chat, to_user:$scope.chatUsers[$scope.selected].user.id });
}
lastTypingTime = (new Date()).getTime();
setTimeout(function () {
var typingTimer = (new Date()).getTime();
var timeDiff = typingTimer - lastTypingTime;
if (timeDiff >= 2000 && $scope.type) {
socket.emit('typing_stop', {from_user: auth_user_id_chat, to_user:$scope.chatUsers[$scope.selected].user.id });
$scope.type = false;
}
}, 2000);
}
/* end typing stop and start notification */
/* new user contacted */
socket.on("new_user_contacted", function(data){
var user = $scope.findUserByID(data.user_id);
/* if user is already in list then remove*/
if (user) {
if(!$scope.total_contacts_count)
{
$scope.chatUsers=[];
}
else
{
var index = $scope.chatUsers.indexOf(user);
$scope.chatUsers.splice(index, 1);
}
}
//push object again retriving ajax call
$http.post(chat_user, {user_id:data.user_id})
.then(function(response){
if (response.data.status == 'success') {
//$scope.chatUsers.push(response.data.chat_user);
var temp = [];
temp.push(response.data.chat_user);
$scope.chatUsers = $.merge(temp, $scope.chatUsers);
$scope.chatUsers = _.uniq($scope.chatUsers, function(a) { return a.contact_id; });
}
}
,function(response){});
});
/* end new user contacted */
$scope.findUserByID = function(user_id){
if ($scope.chatUsers.length < 1)
return null;
return $scope.chatUsers.find(function(item){
if(item.user.id == user_id) return true;
});
}
$scope.mapUserWithSocket = function() {
$http.post(map_user_socket,
{socket_id:$scope.socket_id}).then(function(response){
if (response.data.status == 'success') {
socket.emit('user_socket_mapped', {user_id:auth_user_id_chat})
console.log('you are connected');
}
}, function(){});
}
function swapElement(array, indexA, indexB) {
var tmp = array[indexA];
array[indexA] = array[indexB];
array[indexB] = tmp;
return array;
}
$scope.chatUsers = [];
$scope.chat_users_count = 0;
$scope.total_contacts_count = 0;
$scope.last_contact_id = 0;
$scope.authUser = auth_user_id_chat;
$scope.overall_unread_messages_count = 0;
/* this method gets chat users */
$scope.getChatUsers = function(){
$http.get(
chat_users,
{last_contact_id:$scope.last_contact_id}
).then(function(res){
if(res.data.status == "success") {
$scope.total_contacts_count = res.data.total_contacts_count;
$scope.chatUsers = res.data.chat_users;
if($scope.contact_id_already_contacted)
{
_.each($scope.chatUsers, function(listItem,index){
if(listItem.contact_id == $scope.contact_id_already_contacted)
$scope.indexToBeSelected = index;
})
$scope.chatUsers = swapElement($scope.chatUsers, $scope.indexToBeSelected,0);
}
$scope.chat_users_count = $scope.chatUsers.length;
if ($scope.total_contacts_count == 0 || $scope.chat_users_count == 0) {
$scope.last_contact_id = 0;
} else {
$scope.last_contact_id = $scope.chatUsers[$scope.chat_users_count-1].contact_id;
}
if ($scope.total_contacts_count != 0 && $scope.load_chat_data_first == true) {
$scope.loadChatDataFirst();
$('#fourth_div').hide();
}
else
{
$('#fourth_div').show();
$('#third_img_div').hide();
$('#first_img_div').hide();
$("#no-users-div").hide();
}
$scope.overall_unread_messages_count = res.data.overall_unread_messages_count;
}
}, function(res){});
}
/* this method retrives message of a particular user */
$scope.getMessages = function(user){
$http.post(
msgs_chat,
{user_id:user.user.id, last_message_id:$scope.last_message_id}
).then(function(res){
if (res.data.status == 'success') {
var temp = [];
$.merge(temp, res.data.messages);
_.each(temp,function(item,index){
if(item.to_user==$scope.authUser)
{
temp[index].recipient='other';
}
else
{
temp[index].recipient='self';
}
})
user.user.messages = $.merge(temp, user.user.messages);
}
}, function(res){});
}
/* this method is used to send message */
$scope.submitMessage = function(){
console.log('$scope.messageInput',$scope.messageInput);
var to_send_user = $scope.chatUsers[$scope.selected];
if($scope.messageInput.indexOf(':')==0)
$scope.messageInput = emojione.shortnameToUnicode($scope.messageInput)
var msg_obj = {
from_user : auth_user_id_chat,
to_user : to_send_user.user.id,
contact_id : to_send_user.contact_id,
message_type : 0,
message_text : $scope.messageInput
};
if(to_send_user.user.can_init_chat)
{
socket.emit('new_message', msg_obj);
}
else{
if(to_send_user.user.init_chat_error_type === 'CHAT_INIT_HOURS_EXPIRED')
{
$('#myModalExceedsChatHourExpired').modal('show');
}
else if(to_send_user.user.init_chat_error_type === 'CHAT_LIMIT_OF_DAY')
{
$('#myModalExceedsChatLimit').modal('show');
}
Plugin.fire('chat_init_send_gift', [to_send_user]);
}
$scope.messageInput='';
}
/* submit messege with media
/* this method is used to send message */
$scope.submitMessageWithMedia = function(image_name){
var to_send_user = $scope.chatUsers[$scope.selected];
var msg_obj = {
from_user : auth_user_id_chat,
to_user : to_send_user.user.id,
contact_id : to_send_user.contact_id,
message_type : 2,
message_text : image_name
};
if(to_send_user.user.can_init_chat)
{
socket.emit('new_message', msg_obj);
}
else{
if(to_send_user.user.init_chat_error_type === 'CHAT_INIT_HOURS_EXPIRED')
{
$('#myModalExceedsChatHourExpired').modal('show');
}
else if(to_send_user.user.init_chat_error_type === 'CHAT_LIMIT_OF_DAY')
{
$('#myModalExceedsChatLimit').modal('show');
}
Plugin.fire('chat_init_send_gift', [to_send_user]);
}
}
$scope.submitMessageFirstTime = function(){
var to_send_user = $scope.chatUsers[$scope.selected];
if($scope.messageInput.indexOf(':')==0)
$scope.messageInput = emojione.shortnameToUnicode($scope.messageInput)
var msg_obj = {
from_user : auth_user_id_chat,
to_user : to_send_user.user.id,
contact_id : to_send_user.contact_id,
message_type : 0,
message_text : $scope.messageInput
};
if(to_send_user.user.can_init_chat)
{
socket.emit('new_message', msg_obj);
$scope.loadChatData(to_send_user, $scope.selected);
}
else{
if(to_send_user.user.init_chat_error_type === 'CHAT_INIT_HOURS_EXPIRED')
{
$('#myModalExceedsChatHourExpired').modal('show');
}
else if(to_send_user.user.init_chat_error_type === 'CHAT_LIMIT_OF_DAY')
{
$('#myModalExceedsChatLimit').modal('show');
}
Plugin.fire('chat_init_send_gift', [to_send_user]);
}
$scope.messageInput='';
}
$scope.loadOnline =function() {
var counter=0;
$scope.onlineSelectedUsers = _.filter($scope.chatUsers, function (item,index) {
if(item.online && counter==0){
$scope.chatUsers[index].user.already_clicked= 0;
$scope.loadChatData($scope.chatUsers[index],index);
counter++;
}
return item.online;
});
var onlineUsers_count = $scope.onlineSelectedUsers.length;
if(onlineUsers_count == 0)
{
$('#third_img_div').hide();
$('#first_img_div').hide();
$("#no-users-div").show();
}
}
$scope.loadOnline_mobile =function() {
$scope.onlineSelectedUsers = _.filter($scope.chatUsers, function (item) { return item.online; });
if($scope.total_contacts_count)
{
if ($scope.onlineSelectedUsers.length == 0) {
$('#third_img_div').hide();
$('#first_img_div').hide();
$("#no-users-div").show();
return false;
}
$scope.loadChatData($scope.onlineSelectedUsers[0],0);
}
}
$scope.loadMatched = function() {
var counter=0;
$scope.matchedUsers = _.filter($scope.chatUsers, function (item,index) {
if(item.matched && counter==0){
$scope.chatUsers[index].user.already_clicked= 0;
$scope.loadChatData($scope.chatUsers[index],index);
counter++;
}
return item.matched;
});
var matchedUsers_count = $scope.matchedUsers.length;
if(matchedUsers_count == 0)
{
$('#third_img_div').hide();
$('#first_img_div').hide();
$("#no-users-div").show();
}
}
$scope.loadAll =function() {
if($scope.total_contacts_count)
{
if ($scope.chatUsers.length == 0) {
$('#third_img_div').hide();
$('#first_img_div').hide();
$("#no-users-div").show();
return false;
}
$scope.loadChatData($scope.chatUsers[0],0);
}
}
$scope.loadAll_mobile =function() {
if ($scope.chatUsers.length == 0) {
$('#third_img_div').hide();
$('#first_img_div').hide();
$("#no-users-div").show();
return false;
}
if($scope.total_contacts_count)
$scope.loadChatData($scope.chatUsers[0],0);
}
$scope.selected = 0;
$scope.loadChatData = function(user,index) {
//$scope.selected = index;
//index = $scope.chatUsers.indexOf(user);
if(user !=undefined)
{
$scope.current_to_user_id=user.user.id;
if(!$scope.total_contacts_count)
{
$http.post(add_to_contacts, {user_id:user.user.id})
.then(function(response){
if (response.data.status == 'success') {
$scope.getChatUsers();
}
}
,function(response){});
}
//hide the button
$('#load_more').show();
$scope.userChatDetail = user;
$scope.selected = index;
if (user.user.last_msg) {
$scope.last_message_id = 0;
if (user.user.messages.length > 0) {
$scope.last_message_id = user.user.messages[0].id;
}
if(!user.already_clicked) {
$('.loaderChatData').fadeIn();
$scope.getMessages(user);
user.already_clicked = 1;
//clear unread mesg count
user.user.total_unread_messages_count= 0;
//call function to make unread status for this user once i click on unread mesges
//pending
$http.post(
mark_read ,
{user_id:user.user.id}
).then(function(res){
console.log(res);
$('.loaderChatData').fadeOut();
});
}
if(user.already_clicked)
{
//clear unread mesg count
user.user.total_unread_messages_count= 0;
//$scope.getMessages(user);
}
// $scope.last_msg = user.user.last_msg;
// $scope.last_msg_type = user.user.last_msg_type;
$('#third_img_div').show();
$('#first_img_div').hide();
$("#no-users-div").hide();
$("#fourth_div").hide();
if($scope.mobile)
{
$('.mobile_users').hide();
}
}
else
{
$('#third_img_div').hide();
$('#first_img_div').show();
$("#no-users-div").hide();
$("#fourth_div").hide();
if($scope.mobile)
{
$('.mobile_users').hide();
}
}
}
}
$scope.loadMoreChatData =function(user,index,last_msg_id)
{
$scope.userChatDetail = user;
$scope.selected = index;
if (user.user.last_msg) {
$scope.last_message_id = 0;
if (user.user.messages.length > 0) {
$scope.last_message_id = last_msg_id;
}
$scope.getMessages(user);
// $scope.last_msg = user.user.last_msg;
// $scope.last_msg_type = user.user.last_msg_type;
$('#third_img_div').show();
$('#first_img_div').hide();
$("#no-users-div").hide();
}
else
{
$('#third_img_div').hide();
$('#first_img_div').show();
$("#no-users-div").hide();
}
}
$scope.loadChatDataFirst = function() {
$scope.loadChatData($scope.chatUsers[0], 0);
}
});
/* this is socket factory */
App.factory('socket', function ($rootScope) {
var socket = io(websocket_domain+":"+server_port);
return {
on: function (eventName, callback) {
socket.on(eventName, function () {
var args = arguments;
$rootScope.$apply(function () {
callback.apply(socket, args);
});
});
},
emit: function (eventName, data, callback) {
socket.emit(eventName, data, function () {
var args = arguments;
$rootScope.$apply(function () {
if (callback) {
callback.apply(socket, args);
}
});
})
}
};
});
/* end of socket factory */
Related
I have two JavaScript files. One is running validation, and other have ajax plugin that sends form after validation.
When I attached these files in the header section, then they simultaneously run, but if I attach these two files in the body, then validation runs as it should but ajax call not working.
There is no any error on the console as well.
..
What you people suggests?
AjaxCall.js
$(document).ready(function() {
var options = {
beforeSubmit: showRequest, // pre-submit callback
success: showResponse, // post-submit callback
url: 'quoteProcess.php', // override for form's 'action' attribute
type: 'post', // 'get' or 'post', override for form's 'method' attribute
clearForm: true // clear all form fields after successful submit
};
// bind 'myForm' and provide a simple callback function
$('#testform').ajaxForm(options);
});
// pre-submit callback
function showRequest(formData, jqForm, options) {
$('.modal').show();
return true;
}
function showResponse(responseText, statusText, xhr, $form) {
$('.modal').hide();
alert( '\n\nYour Quote has been Recieved ! \n' + responseText +
'\n');
window.location.replace("http://localhost/lamozine/quote.php");
}
validation.js
(function($){
var functions = {
reset: resetValidation
};
var settings;
var _reqForm;
var _indicatorTemplate = '<span class="error-indicator" role="alert" aria-live="assertive" aria-hidden="true"></span>';
var _summaryTemplate = '<div id="errorSummary" class="alert alert-danger" role="alert" aria-live="assertive" tabindex="-1"><p>{0}</p></div>';
var _validationTypes = {
required: {msg: ' is required' },
tel: {msg: ' is not a valid phone number' },
email: {msg: ' is not a valid email address' },
date: {msg: ' is not a valid date'},
number: {msg: ' is not a valid number'}
};
$.fn.attrvalidate = function() {
if (!this.is('form')) {
return this;
}
if (typeof arguments[0] === 'string') {
var property = arguments[1];
var newArgs = Array.prototype.slice.call(arguments);
newArgs.splice(0, 1);
functions[arguments[0]].apply(this, newArgs);
} else {
setupFormValidation.apply(this, arguments);
}
return this;
};
function resetValidation(){
$(_reqForm).find('input, select, textarea, fieldset').removeClass('invalid');
$(_reqForm).find('.error-indicator').attr('aria-hidden', true);
$(_reqForm).find('#errorSummary').remove();
}
function setupFormValidation(options){
settings = $.extend({
showFieldIndicator: true,
showErrorSummary: true,
errorSummaryMsg: 'Please fix the following issues before continuing:',
validateTel: true,
telRegex: /^\+*[\d-()]{7,20}$/,
validateEmail: true,
emailRegex: /^(\S+#\S+)*$/,
validateDate: true,
validateNumber: true
}, options);
_reqForm = this;
initialiseValidation();
$(_reqForm).bind('submit', handleSubmit);
}
function initialiseValidation(){
var _groupsInitialised = [];
$(_reqForm).find('input, select[required], textarea[required]').each(function(){
if (isRadioGroup($(this)) && $(this).is('[required]')) {
var groupName = $(this).attr('name');
if ($.inArray(groupName, _groupsInitialised) === -1) {
$(this).attr('data-do-validate', true);
setFieldName($(this));
if (settings.showFieldIndicator){
$(this).parents('fieldset').first().append($(_indicatorTemplate));
}
$(_reqForm).find('input[name="' + $(this).attr('name') + '"]').each(function(){
$(this).change(function(){
handleFieldChanged($(this));
});
});
_groupsInitialised.push(groupName);
}
} else {
if ($(this).is('[required]') ||
(settings.validateTel && $(this).is('input[type="tel"]')) ||
(settings.validateEmail && $(this).is('input[type="email"]')) ||
(settings.validateDate && $(this).is('input[type="date"]')) ||
(settings.validateNumber && $(this).is('input[type="number"]'))){
$(this).attr('data-do-validate', true);
setFieldName($(this));
if (settings.showFieldIndicator){
if (($(this).is('input[type="radio"]') || $(this).is('input[type="checkbox"]')) && $(this).next('label').length > 0) {
$(this).next('label').after($(_indicatorTemplate));
} else {
$(this).after($(_indicatorTemplate));
}
}
$(this).change(function(){
handleFieldChanged($(this));
});
}
}
});
}
function handleFieldChanged(elem){
var validationResult = validateField(elem);
if (validationResult.isValid) {
clearFieldError(elem);
} else {
var fieldMsg = getFieldMessage(elem, validationResult.type);
showFieldError(elem, fieldMsg);
}
}
function handleSubmit(e){
e.preventDefault();
var formValid = true;
var errorMessages = [];
$(_reqForm).find('#errorSummary').remove();
$(_reqForm).find('[data-do-validate="true"]').each(function(){
var validationResult = validateField($(this));
if (!validationResult.isValid) {
var fieldMsg = getFieldMessage($(this), validationResult.type);
errorMessages.push({ elem: $(this).prop('id'), msg: fieldMsg });
showFieldError($(this), fieldMsg);
formValid = false;
} else {
clearFieldError($(this));
}
});
if (!formValid) {
if (settings.showErrorSummary) {
showErrorSummary(errorMessages);
}
return false;
} else {
if (typeof(settings.submitFunction) !== 'undefined') {
settings.submitFunction();
} else {
_reqForm[0].submit();
}
}
}
function validateField(elem){
if (!elem.is(':visible') || elem.parents('[aria-hidden="true"]').length > 0){
return { isValid: true };
}
if (elem.is('input[type="radio"]')) {
if (elem.is('[required]')){
if (isRadioGroup(elem)) {
return { isValid: ($(_reqForm).find('input[name="' + elem.attr('name') + '"]:checked').length > 0), type: _validationTypes.required };
} else {
return { isValid: elem.is(':checked'), type: _validationTypes.required };
}
} else {
return { isValid: true };
}
} else if (elem.is('input[type="checkbox"]')) {
return { isValid: (!elem.is('[required]') || elem.is(':checked')), type: _validationTypes.required };
} else {
if (elem.is('[required]') && (elem.val() === '')) {
return { isValid: false, type: _validationTypes.required };
} else if (settings.validateTel && elem.is('input[type="tel"]')) {
return { isValid: settings.telRegex.test(elem.val().replace(/ /g, '')), type: _validationTypes.tel };
} else if (settings.validateEmail && elem.is('input[type="email"]')) {
return { isValid: settings.emailRegex.test(elem.val().trim()), type: _validationTypes.email };
} else if (settings.validateDate && elem.is('input[type="date"]')) {
var doesPass;
if (elem.val().trim() === '') {
doesPass = true;
} else if (isNaN(Date.parse(elem.val()))) {
doesPass = false;
} else if (elem.prop('max') && !isNaN(Date.parse(elem.prop('max'))) && Date.parse(elem.val()) > Date.parse(elem.prop('max'))) {
doesPass = false;
} else if (elem.prop('min') && !isNaN(Date.parse(elem.prop('min'))) && Date.parse(elem.val()) < Date.parse(elem.prop('min'))) {
doesPass = false;
} else {
doesPass = true;
}
return { isValid: doesPass, type: _validationTypes.date };
} else if (settings.validateNumber && elem.is('input[type="number"]')) {
var doesPass;
if (elem.val().trim() === '') {
doesPass = true;
} else if (isNaN(parseFloat(elem.val()))) {
doesPass = false;
} else if (elem.prop('max') && !isNaN(parseFloat(elem.prop('max'))) && parseFloat(elem.val()) > parseFloat(elem.prop('max'))) {
doesPass = false;
} else if (elem.prop('min') && !isNaN(parseFloat(elem.prop('min'))) && parseFloat(elem.val()) < parseFloat(elem.prop('min'))) {
doesPass = false;
} else {
doesPass = true;
}
return { isValid: doesPass, type: _validationTypes.number };
} else {
return { isValid: true };
}
}
}
function setFieldName(elem){
if (typeof(elem.data('error-msg')) !== 'undefined' && elem.data('error-msg') !== '') {
return;
}
var elemName;
var forLabel = $(_reqForm).find('label[for="' + elem.attr('id') + '"]');
if (forLabel.length > 0 && $(forLabel[0]).text() !== '') {
elemName = $(forLabel[0]).text();
} else {
elemName = elem.attr('name');
}
elem.data('error-name', elemName);
}
function getFieldMessage(elem, resultType){
var elemMsg;
if (typeof(elem.data('error-msg')) !== 'undefined' && elem.data('error-msg') !== '') {
elemMsg = elem.data('error-msg');
} else {
elemMsg = elem.data('error-name') + resultType.msg;
}
return elemMsg;
}
function showFieldError(elem, fieldMsg){
if (isRadioGroup(elem)) {
elem.parents('fieldset').first().addClass('invalid');
if (settings.showFieldIndicator){
elem.parents('fieldset').first().find('.error-indicator').first().text(fieldMsg).attr('aria-hidden', false);
}
} else {
elem.addClass('invalid');
if (settings.showFieldIndicator){
elem.nextAll('.error-indicator').first().text(fieldMsg).attr('aria-hidden', false);
}
}
}
function clearFieldError(elem){
if (isRadioGroup(elem)) {
elem.parents('fieldset').removeClass('invalid');
if (settings.showFieldIndicator){
elem.parents('fieldset').first().find('.error-indicator').first().attr('aria-hidden', true);
}
var firstInGroup = $(_reqForm).find('input[name="' + elem.attr('name') + '"]').first();
var summaryItem = $('#errorSummary li a[data-field="' + firstInGroup.attr('id') + '"]');
if (summaryItem.length > 0) {
summaryItem.parent('li').remove();
if ($('#errorSummary ul li').length === 0) {
$('#errorSummary').remove();
}
}
} else {
elem.removeClass('invalid');
if (settings.showFieldIndicator){
elem.nextAll('.error-indicator').first().attr('aria-hidden', true);
}
var summaryItem = $('#errorSummary li a[data-field="' + elem.attr('id') + '"]');
if (summaryItem.length > 0) {
summaryItem.parent('li').remove();
if ($('#errorSummary ul li').length === 0) {
$('#errorSummary').remove();
}
}
}
}
function showErrorSummary(errorMsgList){
var errorSummary = $(_summaryTemplate.replace('{0}', settings.errorSummaryMsg));
var errorList = $('<ul></ul>');
for (var i=0; i < errorMsgList.length; i++) {
var errorLink = $('' + errorMsgList[i].msg + '');
errorLink.click(function(){ jumpToElem($(this).data('field')); return false; });
var errorItm = $('<li></li>');
errorItm.append(errorLink);
errorList.append(errorItm);
}
errorSummary.append(errorList).prependTo($(_reqForm));
errorSummary.focus();
}
function isRadioGroup(elem){
return (elem.is('input[type="radio"]') && typeof(elem.attr('name')) !== 'undefined' && elem.attr('name') !== '');
}
function jumpToElem(fieldId){
$(_reqForm).find('#' + fieldId).focus();
}
}(jQuery));
I am not clear with your question very well but if you want to load one script file after loading an another script file. You can simple load using $.when() and $.getScript() jquery functions like this.
$.getScript() will load javascript file asynchronously and .done() call back of $.when() method will continue after the loading script done.
This is a very simple sample.
<html>
<head>
<script src="/jquery.min.js"></script>
</head>
<body>
<script>
$.when(
$.getScript("/mypath/validation.js")
).done(function(){
$.getScript("/mypath/AjaxCall.js")
});
</script>
</body>
Hope it might help.
I have a JavaScript function that updates my data.
The user may Click several times and I want to Wait for the Second click while the first click is not finished and so on
$scope.isLastUpdateFinished = true;
$scope.onSave = function (isFitToPage) {
if (!$scope.isLastUpdateFinished)
while (!$scope.isLastUpdateFinished) {
}
$scope.isLastUpdateFinished = false;
dataService.save($scope.draft, "api/Draft/UpdateDraft/").then(function (data) {
if (data.Succeeded && data.Message != null)
toaster.pop("warning", _("Dataservice_TTL_Save"), data.Message);
if (!data.Succeeded) {
modalOptions.headerText = _("Error_InRefreshList");
modalOptions.bodyText = data.Message;
modalService.showModal(errorDefaults, modalOptions);
}
if (isFitToPage) {
$scope.imageviewer.viewerconfig.controls.imageReload(true, true);
}
if ($scope.myOtherAside.$scope.$isShown && isFitToPage) {
$scope.viewerconfig.controls.imageReload(true, true);
}
$scope.isLastUpdateFinished = true;
});
};
How about just notifying the user that the app is still working?
$scope.isLastUpdateFinished = true;
$scope.onSave = function (isFitToPage) {
if (!$scope.isLastUpdateFinished)
{
toaster.pop("info", "Please wait...", "Request already in progress... ");
return false;
}
$scope.isLastUpdateFinished = false;
dataService.save($scope.draft, "api/Draft/UpdateDraft/").then(function (data) {
if (data.Succeeded && data.Message != null)
toaster.pop("warning", _("Dataservice_TTL_Save"), data.Message);
if (!data.Succeeded) {
modalOptions.headerText = _("Error_InRefreshList");
modalOptions.bodyText = data.Message;
modalService.showModal(errorDefaults, modalOptions);
}
if (isFitToPage) {
$scope.imageviewer.viewerconfig.controls.imageReload(true, true);
}
if ($scope.myOtherAside.$scope.$isShown && isFitToPage) {
$scope.viewerconfig.controls.imageReload(true, true);
}
$scope.isLastUpdateFinished = true;
});
};
I got a function for removing elements from the site. When i click the "ok" button the console tells me "removeElements is not defined"...?! But in my opinion everything is done right.
Here is the code:
function showPic(obj, yes)
{
var obj = (yes) ? obj : this;
if(!isTimeRunning)
{
isTimeRunning = true;
chronoId = setInterval(function() { chronometro() }, 1000);
pointers[game] = chronoId;
}
if(!waitASecond)
{
if(!imagesInGame.isInArray(obj))
{
return;
}
if(!clicks.length)
{
clicks[0] = obj;
if(!openedImages.isInArray(obj))
{
notOpenedImages.deleteElementByValue(obj.divNum, 'divNum');
}
obj.firstChild.style.display = 'none';
}
else
{
if(clicks[0].divNum == obj.divNum)
return;
clicks[1] = obj;
if(!openedImages.isInArray(obj))
{
openedImages.push(obj);
notOpenedImages.deleteElementByValue(obj.divNum, 'divNum');
}
obj.firstChild.style.display = 'none';
waitASecond = true;
checkIdentity();
document.getElementById('numberOfTries' + game).value = allPlayers[player]['failures'];
}
}
}
function showPicOnclick()
{
if(humanPlayer)
showPic(this, true);
}
function checkIdentity()
{
if(clicks[0].imageNum == clicks[1].imageNum)
{
countPairs();
imagesInGame.deleteElementByValue(clicks[0].imageNum, 'imageNum');
openedImages.deleteElementByValue(clicks[0].imageNum, 'imageNum');
addElement('match_div_one_'+clicks[1].imageNum, "img");
addElement('match_div_two_'+clicks[1].imageNum, 'Inhalt1');
addElement('match_div_three_'+clicks[1].imageNum, 'Inhalt1');
addElement('match_div_button_'+clicks[1].imageNum, '<button onclick="removeElements()">OK</button>');
/*alert(messages[clicks[1].imageNum]); */
gotLastPair = player;
waitASecond = false;
clicks.clean();
checkForGameEnd();
}
else
{
allPlayers[player]['failures']++;
turnId = setTimeout(function() { hidePics() }, timeout);
}
}
function removeElement(divNum) {
var olddiv = document.getElementById(divNum);
olddiv.parentNode.removeChild(olddiv);
}
function removeElements() {
removeElement('match_div_one_'+clicks[1].imageNum);
removeElement('match_div_two_'+clicks[1].imageNum);
removeElement('match_div_three_'+clicks[1].imageNum);
removeElement('match_div_button_'+clicks[1].imageNum);
}
I am trying to render a pdf in chrome using PDFJS
This is the function I am calling:
open: function pdfViewOpen(url, scale, password) {
var parameters = {password: password};
if (typeof url === 'string') { // URL
this.setTitleUsingUrl(url);
parameters.url = url;
} else if (url && 'byteLength' in url) { // ArrayBuffer
parameters.data = url;
}
if (!PDFView.loadingBar) {
PDFView.loadingBar = new ProgressBar('#loadingBar', {});
}
this.pdfDocument = null;
var self = this;
self.loading = true;
getDocument(parameters).then(
function getDocumentCallback(pdfDocument) {
self.load(pdfDocument, scale);
self.loading = false;
},
function getDocumentError(message, exception) {
if (exception && exception.name === 'PasswordException') {
if (exception.code === 'needpassword') {
var promptString = mozL10n.get('request_password', null,
'PDF is protected by a password:');
password = prompt(promptString);
if (password && password.length > 0) {
return PDFView.open(url, scale, password);
}
}
}
var loadingErrorMessage = mozL10n.get('loading_error', null,
'An error occurred while loading the PDF.');
if (exception && exception.name === 'InvalidPDFException') {
// change error message also for other builds
var loadingErrorMessage = mozL10n.get('invalid_file_error', null,
'Invalid or corrupted PDF file.');
//#if B2G
// window.alert(loadingErrorMessage);
// return window.close();
//#endif
}
var loadingIndicator = document.getElementById('loading');
loadingIndicator.textContent = mozL10n.get('loading_error_indicator',
null, 'Error');
var moreInfo = {
message: message
};
self.error(loadingErrorMessage, moreInfo);
self.loading = false;
},
function getDocumentProgress(progressData) {
self.progress(progressData.loaded / progressData.total);
}
);
}
This is the call:
PDFView.open('/MyPDFs/Pdf2.pdf', 'auto', null);
All I get is this:
If you notice, even the page number is retrieved but the content is not painted in the pages. CanĀ“t find why.. Is the any other function I should call next to PDFView.open?
Found the solution...!
This is the code that does the work.
$(document).ready(function () {
PDFView.initialize();
var params = PDFView.parseQueryString(document.location.search.substring(1));
//#if !(FIREFOX || MOZCENTRAL)
var file = params.file || DEFAULT_URL;
//#else
//var file = window.location.toString()
//#endif
//#if !(FIREFOX || MOZCENTRAL)
if (!window.File || !window.FileReader || !window.FileList || !window.Blob) {
document.getElementById('openFile').setAttribute('hidden', 'true');
} else {
document.getElementById('fileInput').value = null;
}
//#else
//document.getElementById('openFile').setAttribute('hidden', 'true');
//#endif
// Special debugging flags in the hash section of the URL.
var hash = document.location.hash.substring(1);
var hashParams = PDFView.parseQueryString(hash);
if ('disableWorker' in hashParams)
PDFJS.disableWorker = (hashParams['disableWorker'] === 'true');
//#if !(FIREFOX || MOZCENTRAL)
var locale = navigator.language;
if ('locale' in hashParams)
locale = hashParams['locale'];
mozL10n.setLanguage(locale);
//#endif
if ('textLayer' in hashParams) {
switch (hashParams['textLayer']) {
case 'off':
PDFJS.disableTextLayer = true;
break;
case 'visible':
case 'shadow':
case 'hover':
var viewer = document.getElementById('viewer');
viewer.classList.add('textLayer-' + hashParams['textLayer']);
break;
}
}
//#if !(FIREFOX || MOZCENTRAL)
if ('pdfBug' in hashParams) {
//#else
//if ('pdfBug' in hashParams && FirefoxCom.requestSync('pdfBugEnabled')) {
//#endif
PDFJS.pdfBug = true;
var pdfBug = hashParams['pdfBug'];
var enabled = pdfBug.split(',');
PDFBug.enable(enabled);
PDFBug.init();
}
if (!PDFView.supportsPrinting) {
document.getElementById('print').classList.add('hidden');
}
if (!PDFView.supportsFullscreen) {
document.getElementById('fullscreen').classList.add('hidden');
}
if (PDFView.supportsIntegratedFind) {
document.querySelector('#viewFind').classList.add('hidden');
}
// Listen for warnings to trigger the fallback UI. Errors should be caught
// and call PDFView.error() so we don't need to listen for those.
PDFJS.LogManager.addLogger({
warn: function () {
PDFView.fallback();
}
});
var mainContainer = document.getElementById('mainContainer');
var outerContainer = document.getElementById('outerContainer');
mainContainer.addEventListener('transitionend', function (e) {
if (e.target == mainContainer) {
var event = document.createEvent('UIEvents');
event.initUIEvent('resize', false, false, window, 0);
window.dispatchEvent(event);
outerContainer.classList.remove('sidebarMoving');
}
}, true);
document.getElementById('sidebarToggle').addEventListener('click',
function () {
this.classList.toggle('toggled');
outerContainer.classList.add('sidebarMoving');
outerContainer.classList.toggle('sidebarOpen');
PDFView.sidebarOpen = outerContainer.classList.contains('sidebarOpen');
PDFView.renderHighestPriority();
});
document.getElementById('viewThumbnail').addEventListener('click',
function () {
PDFView.switchSidebarView('thumbs');
});
document.getElementById('viewOutline').addEventListener('click',
function () {
PDFView.switchSidebarView('outline');
});
document.getElementById('previous').addEventListener('click',
function () {
PDFView.page--;
});
document.getElementById('next').addEventListener('click',
function () {
PDFView.page++;
});
document.querySelector('.zoomIn').addEventListener('click',
function () {
PDFView.zoomIn();
});
document.querySelector('.zoomOut').addEventListener('click',
function () {
PDFView.zoomOut();
});
document.getElementById('fullscreen').addEventListener('click',
function () {
PDFView.fullscreen();
});
document.getElementById('openFile').addEventListener('click',
function () {
document.getElementById('fileInput').click();
});
document.getElementById('print').addEventListener('click',
function () {
window.print();
});
document.getElementById('download').addEventListener('click',
function () {
PDFView.download();
});
document.getElementById('pageNumber').addEventListener('change',
function () {
PDFView.page = this.value;
});
document.getElementById('scaleSelect').addEventListener('change',
function () {
PDFView.parseScale(this.value);
});
document.getElementById('first_page').addEventListener('click',
function () {
PDFView.page = 1;
});
document.getElementById('last_page').addEventListener('click',
function () {
PDFView.page = PDFView.pdfDocument.numPages;
});
document.getElementById('page_rotate_ccw').addEventListener('click',
function () {
PDFView.rotatePages(-90);
});
document.getElementById('page_rotate_cw').addEventListener('click',
function () {
PDFView.rotatePages(90);
});
//#if (FIREFOX || MOZCENTRAL)
//if (FirefoxCom.requestSync('getLoadingType') == 'passive') {
// PDFView.setTitleUsingUrl(file);
// PDFView.initPassiveLoading();
// return;
//}
//#endif
//#if !B2G
PDFView.open(file, 0);
//#endif
});
The system must be initialized first before PDFView.open call!
Thanks
Currently having a problem where I have wanted to do a simple jQuery append to move a div into another div. In this case, when I type in the search box suggested results should appear underneath. However due to myself changing some of the code it no longer appears too the left so I did a simple jQuery append to make my life easier.
The problem is that when I make a simple search and the results box appears under the search box I use the console to excute the following line of code:
$('#QuickSearch').appendTo($('#searchheader'));
All works fine in the console. However when I put it in the search's javascript file, it does not execute that line of code. Below is the jQuery associated with the search:
var QuickSearch = {
minimum_length: 3,
search_delay: 125,
cache: new Object(),
init: function()
{
$('#search_query').bind("keydown", QuickSearch.on_keydown);
$('#search_query').bind("keyup", QuickSearch.on_keyup);
$('#search_query').bind("change", QuickSearch.on_change);
$('#search_query').blur(QuickSearch.on_blur);
$('#search_query').attr('autocomplete', 'off');
var scripts = document.getElementsByTagName('SCRIPT');
for(var i = 0; i < scripts.length; i++)
{
s = scripts[i];
if(s.src && s.src.indexOf('quicksearch.js') > -1)
{
QuickSearch.path = s.src.replace(/quicksearch\.js$/, '../');
break;
}
}
},
on_blur: function(event)
{
if(!QuickSearch.item_selected && !QuickSearch.over_all)
{
QuickSearch.hide_popup();
}
},
on_keydown: function(event)
{
if(event.keyCode == 13 && !event.altKey)
{
if(QuickSearch.selected)
{
try {
event.preventDefault();
event.stopPropagation();
} catch(e) { }
window.location = QuickSearch.selected.url;
return false;
}
else
{
QuickSearch.hide_popup();
}
}
else if(event.keyCode == 27)
{
if(document.getElementById('QuickSearch'))
{
try {
event.preventDefault();
event.stopPropagation();
} catch(e) { }
}
QuickSearch.hide_popup();
}
},
on_keyup: function(event)
{
if(QuickSearch.timeout)
{
clearTimeout(QuickSearch.timeout);
}
// Down key was pressed
if(event.keyCode == 40 && QuickSearch.results)
{
if(QuickSearch.selected && QuickSearch.results.length >= QuickSearch.selected.index+1)
{
QuickSearch.highlight_item(QuickSearch.selected.index+1, true);
}
if(!QuickSearch.selected && QuickSearch.results.length > 0)
{
QuickSearch.highlight_item(0, true);
}
try {
event.preventDefault();
event.stopPropagation();
} catch(e) { }
return false;
}
else if(event.keyCode == 38 && QuickSearch.results)
{
if(QuickSearch.selected && QuickSearch.selected.index > 0)
{
QuickSearch.highlight_item(QuickSearch.selected.index-1, true);
}
try {
event.preventDefault();
event.stopPropagation();
} catch(e) { }
}
else if(event.keyCode == 27)
{
QuickSearch.hide_popup();
}
else
{
if($('#search_query').val() == QuickSearch.last_query)
{
return false;
}
QuickSearch.selected = false;
if($('#search_query').val().replace(/^\s+|\s+$/g, '').length >= QuickSearch.minimum_length)
{
QuickSearch.last_query = $('#search_query').val().replace(/^\s+|\s+$/g, '');
if(QuickSearch.timeout)
{
window.clearTimeout(QuickSearch.timeout);
}
QuickSearch.timeout = window.setTimeout(QuickSearch.do_search, QuickSearch.search_delay);
}
else {
if(document.getElementById('QuickSearch'))
{
$('#QuickSearch').remove();
}
}
}
},
on_change: function(event)
{
return (QuickSearch.on_keydown(event) && QuickSearch.on_keyup(event));
},
do_search: function()
{
var cache_name = $('#search_query').val().length+$('#search_query').val();
if(QuickSearch.cache[cache_name])
{
QuickSearch.search_done(QuickSearch.cache[cache_name]);
}
else
{
$.ajax({
type: 'GET',
dataType: 'xml',
url: QuickSearch.path+'search.php?action=AjaxSearch&search_query='+encodeURIComponent($('#search_query').val()),
success: function(response) { QuickSearch.search_done(response); }
});
}
},
search_done: function(response)
{
// Cache results
var cache_name = $('#search_query').val().length+$('#search_query').val();
QuickSearch.cache[cache_name] = response;
if(document.getElementById('QuickSearch')) {
$('#QuickSearch').remove();
}
if ($('result', response).length > 0) {
var popup_container = document.createElement('TABLE');
popup_container.className = 'QuickSearch';
popup_container.id = 'QuickSearch';
popup_container.cellPadding = "0";
popup_container.cellSpacing = "0";
popup_container.border = "0";
var popup = document.createElement('TBODY');
popup_container.appendChild(popup);
var counter = 0;
$('result', response).each(
function()
{
var tr = $($(this).text());
var url = $('.QuickSearchResultName a', tr).attr('href');
var tmpCounter = counter;
$(tr).attr('id', 'QuickSearchResult' + tmpCounter);
$(tr).bind('mouseover', function() { QuickSearch.item_selected = true; QuickSearch.highlight_item(tmpCounter, false); });
$(tr).bind('mouseup', function() { window.location = url; });
$(tr).bind('mouseout', function() { QuickSearch.item_selected = false; QuickSearch.unhighlight_item(tmpCounter) });
$(popup).append(tr);
counter++;
}
);
// More results than we're showing?
var all_results_count = $('viewmoreurl', response).size();
if(all_results_count)
{
var tr = document.createElement('TR');
var td = document.createElement('TD');
tr.className = "QuickSearchAllResults";
tr.onmouseover = function() { QuickSearch.over_all = true; };
tr.onmouseout = function() { QuickSearch.over_all = false; };
td.colSpan = 2;
td.innerHTML = $('viewmoreurl', response).text();
tr.appendChild(td);
popup.appendChild(tr);
}
var clone = popup.cloneNode(true);
document.body.appendChild(clone);
clone.style.pp = "10px";
clone.style.left = "10px";
offset_height = clone.offsetHeight;
offset_width = clone.offsetWidth;
clone.parentNode.removeChild(clone);
var offset_top = offset_left = 0;
var element = document.getElementById('search_query');
if(typeof(QuickSearchAlignment) != 'undefined' && QuickSearchAlignment == 'left') {
offset_left = 0;
}
else {
offset_left += element.offsetWidth - $('#SearchForm').width();
}
offset_top = 87;
do
{
offset_top += element.offsetTop || 0;
offset_left += element.offsetLeft || 0;
element = element.offsetParent;
} while(element);
popup_container.style.position = "fixed";
popup_container.style.top = offset_top + "px";
if(typeof(QuickSearchWidth) != 'undefined') {
popup_container.style.width = QuickSearchWidth;
}
else {
popup_container.style.width = document.getElementById('SearchForm').offsetWidth - 2 + "px";
}
if($('#QuickSearch'))
{
$('#QuickSearch').remove();
}
document.body.appendChild(popup_container);
popup_container.style.display = '';
}
else
{
if(document.getElementById('QuickSearch'))
{
$('#QuickSearch').remove();
}
}
},
hide_popup: function()
{
$('#QuickSearch').remove();
QuickSearch.selected = null;
},
highlight_item: function(index, keystroke)
{
element = $('#QuickSearchResult'+index);
if(keystroke == true)
{
if(QuickSearch.selected) QuickSearch.selected.className = 'QuickSearchResult';
QuickSearch.selected = document.getElementById('QuickSearchResult'+index);
}
element.addClass("QuickSearchHover");
},
unhighlight_item: function(index)
{
element = $('#QuickSearchResult'+index);
element.removeClass('QuickSearchHover');
}
};
$(document).ready(function()
{
QuickSearch.init();
});