Unable to make asynchronous HTTP call in Angular with Laravel framework - javascript

I'm facing a very strange issue where I'm able to make asynchronous HTTP call in my local Cent-OS environment but as soon as I push my code to demo server somehow the HTTP calls are not executed asynchronously.
Below is the function that I'm trying to execute,
$scope.getResults = function(){
$http({
url: /getResults,
method: 'POST',
data: data,
headers: {'async': true}
})
.then(function (response) {
var contactId = response.data.contactId[0];
$scope.loadProfileInfo(contactId);
var requestId = response.data.requestId;
$scope.getTotalCount(requestId);
}
});
};
$scope.loadProfileInfo = function(id){
$http({
url: /getProfileInfo,
method: 'POST',
data: {contactId: id},
headers: {'async': true})
.then(function (response) {
//perform operations
});
};
$scope.getTotalCount = function(id){
$http({
url: /getTotalCount,
method: 'POST',
data: {some: data},
headers: {'async': true})
.then(function (response) {
//perform operations
});
};
When I call the function getResults() it loads the results and calls the function loadProfileInfo() which loads the profile information as expected.
Now the issue is the function getTotalCount takes a lot longer to execute and until it does not return the response no other HTTP calls are processed even if they are very small.
I'm using Laravel PHP framework.
Real Code
Reference:
pageChangeHandler() = getResults()
getCount() = getTotalCount()
showProfileAction() = loadProfileInfo()
$scope.pageChangeHandler = function(num) {
$scope.checkMoreResults = false;
console.log("pageChangeHandler begins");
//removing cached values from previous results
$("#analyticsResults").text("...");
$scope.showTitleLevelGraph(['','','','',''], [0,0,0,0,0]);
$scope.showScoreGraph([0,0,0,0,0,0]);
$scope.showGenderGraph([0,0,0]);
$scope.showCompanySizeGraph([0,0,0,0]);
$scope.analyticsFlag = false;
$("#loading-bar").show();
$("#loading-spinner").show();
if ($window.Math.ceil(num*50)>50000){
sweetAlert("Oops", "Seeking is limited to 50,000 results. Please narrow your search or contact a Customer Support rep at 866-535-3960 if you are interested in larger quantities of data.", "error");
} else {
$('body').css('cursor', 'progress');
// if downloadList exists, save it so it can be added to after reloading.
if ($scope.downloadList.length>0) {
$scope.storedSelectedContacts = angular.copy($scope.downloadList);
$scope.storedLiUrl = angular.copy($scope.liUrl);
$scope.storedCompanyName = angular.copy($scope.companyName);
$scope.storedCompLink = angular.copy($scope.compLink);
}
$scope.selectedPage = num;
//$scope.showProfile = false;
//$scope.profileData = null;
if (num > 1 || null!==$scope.shortCode) {
// use code
var data = {'code': $scope.shortCode};
} else {
$scope.shortCode = null;
var data = angular.copy($scope.wizardData);
console.debug(data+" "+JSON.stringify(data));
try{
if (data.state.length > 0) {
for (var x = 0; x < data.state.length; x++) {
data.tbl_company_State[x] = data.state[x].value;
}
data.state = null; // null it out to prevent issues in LV controller
}
}catch(e){
}
}
//console.debug(data);
if ($scope.searchFast == true){
var url = $scope.baseUrl + "/search/fast?page=" + num;
} else {
var url = $scope.baseUrl + "/search/wizard?page=" + num;
console.log("wizard: "+num);
var newsearch = true;
}
console.log("Real data: "+JSON.stringify(data));
$http({
url: url,
method: 'POST',
data: data,
headers: {'async': true}
})
.success(function (response) {
(function() {
setTimeout(function() {
// code-here
//response = response.data;
console.log("Search results: "+JSON.stringify(response));
$('body').css('cursor', 'auto');
//console.debug(response);
if (response.error){
if (response.error == 1000000) {
sweetAlert("Oops", "Your search returned more than 1 million results. Please narrow your search or contact a Customer Support rep at 866-535-3960 if you are interested in larger quantities of data.", "error");
$scope.totalResults = '1000000+';
} else {
sweetAlert("Oops", response.error, "error");
$scope.totalResults = '0';
}
} else {
if (response.data) {
//loading the profile of the first result from the fast load
$scope.selectedAll = false;
$scope.searchResults = response.data;
$scope.totalResults = response.total;
$scope.resultStart = $window.Math.ceil((response.per_page * response.current_page) - response.per_page + 1);
$scope.resultEnd = $window.Math.ceil(response.per_page * response.current_page);
if ($scope.resultEnd > $scope.totalResults) {
$scope.resultEnd = angular.copy($scope.totalResults);
}
$scope.resultsPerPage = response.per_page;
$scope.pageSize = $scope.resultsPerPage;
$scope.lastPage = response.last_page;
$scope.currentPage = response.current_page;
if (response.code) {
$scope.shortCode = response.code;
$scope.disableRange = false;
}
$scope.shareUrl = $scope.baseUrl + '/search/code/' + $scope.shortCode;
console.log();
if (response.data.length > 0) {
if ($scope.currentPage > 1 && $scope.passedCode!='') {
$scope.passedCode=''
}
if ($scope.currentPage == 1 && ($scope.searchFast==true || $scope.searchFast==null)) {
//------Edit Jeet kapadia---//
if($scope.newSearchFlag == false){
$scope.showResults = true;
//loading the profile of the first result from the fast load
$scope.firstContactId = response.data[0].ContactID;
console.log("1 Profile loaded");
$scope.showProfileAction($scope.firstContactId);
}
}*/
//-----End Jeet Kapadia-----//
}
if(newsearch == true && $scope.newSearchFlag == true){
//console.log(response.data[0]);
//$scope.newSaveSelectSearch();
$scope.showResults = false;
newsearch = "false";
}
angular.forEach($scope.searchResults, function (item) {
item.Selected = false;
if (arrayObjectIndexOf($scope.storedSelectedContacts, item.ContactID)>-1 || arrayObjectIndexOf($scope.downloadList, item.ContactID)>-1) {
item.Selected = true;
}
});
$scope.buildDownloadList();
if (response.more){
$scope.totalResults = 'Loading...';
$scope.searchFast=false;
$scope.disableRange = true;
$scope.checkMoreResults = true;
$scope.pageChangeHandler(1);
}else{
$scope.getCount();
//reloading the profile of the first result if the contact changes after all
//the records have been loaded
if($scope.firstContactId != response.data[0].ContactID){
console.log("2 Profile loaded: "+$scope.firstContactId+" "+response.data[0].ContactID);
$scope.showProfileAction(response.data[0].ContactID);
}
//fetching all results to perform analytics on
console.log("short code: "+$scope.shortCode);
//globalAnalyticsInterval = $interval(function () {
}
} else {
sweetAlert("Oops", "Your search returned 0 results. Please widen your search parameters a bit.", "error");
}
}
}
}, 500)
})()
});
}
};
$scope.getCount = function(){
var data = angular.copy($scope.wizardData);
console.debug(data+" "+JSON.stringify(data));
try{
if (data.state.length > 0) {
for (var x = 0; x < data.state.length; x++) {
data.tbl_company_State[x] = data.state[x].value;
}
data.state = null; // null it out to prevent issues in LV controller
}
}catch(e){
}
var url = $scope.baseUrl + "/search/getCount";
$http.post(url, data)
.success(function (response) {
//response = response.data;
$scope.lastPage = response.last_page;
$scope.totalResults = response.total;
console.log("Count: "+JSON.stringify(response));
});
};
$scope.showProfileAction = function(id) {
$scope.liTimeoutFlag = false;
$scope.liResponseFlag = false;
$scope.storedContactId = id;
console.log("showProfileAction: "+id);
$scope.showProfile = false;
$scope.profileData = null;
$("#qualityScoreText").text("Verifying");
$scope.socialScoreFlag = false;
$scope.emailScoreFlag = false;
$("#profileInfo").addClass("visibilityHidden");
try{
$scope.canceller.resolve();
}catch(err){
//console.log("showProfileAction: "+err.message);
}
$scope.userNoteContactId = id;
//getting user notes for the contact
$scope.getUserNoteComment(id);
//console.debug(id);
if (id > 0) {
$scope.idContactSelected = id;
var url = $scope.baseUrl + "/search/contact/" + id;
$('body').css('cursor', 'progress');
$('#profilePanel').css('background-color: #ccc');
$http.get(url)
.then(function (response) {
response = response.data;
$('body').css('cursor', 'auto');
$('#profilePanel').css('background-color: #fff');
if (response.error) {
sweetAlert("Oops", "Contact info could not be loaded.", "error");
} else {
if (response.id) {
if ($scope.mapMarker!==null) {
$scope.mapMarker.setMap(null);
}
$timeout(function(){
$scope.showProfile = true;
}, 100)
$scope.profileData = response;
$("#profileInfo").removeClass("visibilityHidden");
$scope.lat = parseFloat($scope.profileData.Latitude).toFixed(6);
$scope.lon = parseFloat($scope.profileData.Longitude).toFixed(6);
$scope.mapOptions = {
zoom: 14,
center: new google.maps.LatLng($scope.lat, $scope.lon),
// Style for Google Maps
styles: [{"featureType":"landscape","stylers":[{"saturation":-100},{"lightness":65},{"visibility":"on"}]},{"featureType":"poi","stylers":[{"saturation":-100},{"lightness":51},{"visibility":"simplified"}]},{"featureType":"road.highway","stylers":[{"saturation":-100},{"visibility":"simplified"}]},{"featureType":"road.arterial","stylers":[{"saturation":-100},{"lightness":30},{"visibility":"on"}]},{"featureType":"road.local","stylers":[{"saturation":-100},{"lightness":40},{"visibility":"on"}]},{"featureType":"transit","stylers":[{"saturation":-100},{"visibility":"simplified"}]},{"featureType":"administrative.province","stylers":[{"visibility":"off"}]},{"featureType":"water","elementType":"labels","stylers":[{"visibility":"on"},{"lightness":-25},{"saturation":-100}]},{"featureType":"water","elementType":"geometry","stylers":[{"hue":"#ffff00"},{"lightness":-25},{"saturation":-97}]}],
mapTypeId: google.maps.MapTypeId.ROADMAP
};
$scope.mapMarker = new google.maps.Marker({
map: $scope.myMap,
position: $scope.mapOptions.center
});
for(var key in $scope.profileData) {
//console.log(key+" "+$scope.profileData[key]);
}
//verifying the email address of the loaded profile
var emailUrl = $location.protocol() + '://'+ $location.host() + '/contact/verify/' + id;
$http.post(emailUrl)
.then(function (result) {
var singleVerificationKey = result.data.verification_key;
var emailStatus = result.data.status;
var singleEmailResult = result.data.result;
console.log("single email call: "+JSON.stringify(result)+" "+emailStatus);
if($scope.storedContactId == result.data.contactid){
if(emailStatus == "0"){ //when something goes wrong while verifying the email
$("#qualityScoreEmail").html("<i class='fa fa-question' style='font-size:15px' popover-placement='right' popover-trigger='mouseenter' popover='The email for this contact is UNKNOWN.'></i> Email");
}else if(emailStatus == "2"){ //when the email is verified in last 24 hours
if((singleEmailResult == 'pass')){ //success
$("#qualityScoreEmail").html("<i class='fa fa-check' style='font-size:15px' popover-placement='right' popover-trigger='mouseenter' popover='The email for this contact IS up to date.'></i> Email");
}else if((singleEmailResult == 'fail')){ //failed
$("#qualityScoreEmail").html("<i class='fa fa-remove' style='font-size:15px' popover-placement='right' popover-trigger='mouseenter' popover='The email for this contact is NOT up to date.'></i> Email");
}else if((singleEmailResult == 'unknown')){ // unknown
$("#qualityScoreEmail").html("<i class='fa fa-question' style='font-size:15px' popover-placement='right' popover-trigger='mouseenter' popover='The email for this contact is UNKNOWN.'></i> Email");
}
}else if(emailStatus == "1"){
console.log("single email key: "+singleVerificationKey);
//instantiate a Pusher object with our Credential's key
var pusher = new Pusher('2703a05dc7f552e2a2d5', {
encrypted: true
});
//Subscribe to the channel we specified in our Laravel Event
var channel = pusher.subscribe(singleVerificationKey);
//Bind a function to a Event (the full Laravel class)
channel.bind('EmailSingleVerification', $scope.singleEmailVerification);
}
}else{
console.log("single email creation information from previous request");
}
});
// //verifying the social information of the loaded profile
var liUrl = $scope.baseUrl + '/socialVerifyBatch';
var contactIdArr = [id];
var postData = {'id': contactIdArr, 'background': false};
$http.post(liUrl, postData)
.then(function (result) {
setTimeout(function () {
console.log("Timeout: start");
$scope.liTimeoutFlag = true;
if(($scope.storedContactId == result.data.contactid) && (!$scope.liResponseFlag)){
console.log("Timeout: making unknown");
$("#qualityScoreSocial").html("<i class='fa fa-question' style='font-size:15px' popover-placement='right' popover-trigger='mouseenter' popover='The social record for this contact is UNKNOWN'></i> Social");
$scope.animateScore($scope.profileData.Quality_Score, $scope.profileData.Quality_Score-1, 1000);
console.log("here 1");
var url = $scope.baseUrl + '/contact/verifySocial/' + $scope.storedContactId + "/6";
$http.post(url)
.then(function (result) {
console.log("Timeout: Update quality score: "+JSON.stringify(result));
}
);
}
}, 20000);
console.log("single li: "+JSON.stringify(result)+" "+$scope.storedContactId+" "+result.data.contactid);
if($scope.storedContactId == result.data.contactid){
//if the social information was verified in last 24 hours
if(result.data.status == "exist"){
if(result.data.passed == 1){ //success
$("#qualityScoreSocial").html("<i class='fa fa-check' style='font-size:15px' popover-placement='right' popover-trigger='mouseenter' popover='The social record for this contact IS up to date.'></i> Social");
}else if(result.data.failed == 1){ //failed
$("#qualityScoreSocial").html("<i class='fa fa-remove' style='font-size:15px' popover-placement='right' popover-trigger='mouseenter' popover='The social record for this contact is NOT up to date.'></i> Social");
}else if(result.data.unknown == 1){ // unknown
$("#qualityScoreSocial").html("<i class='fa fa-question' style='font-size:15px' popover-placement='right' popover-trigger='mouseenter' popover='The social record for this contact is UNKNOWN'></i> Social");
}
}else if(result.data.status == "done"){
var uniqueString = result.data.download_key;
console.log("karthik key: "+uniqueString);
//instantiate a Pusher object with our Credential's key
var pusher = new Pusher('2703a05dc7f552e2a2d5', {
encrypted: true
});
//Subscribe to the channel we specified in our Laravel Event
var channel = pusher.subscribe(uniqueString);
//Bind a function to a Event (the full Laravel class)
channel.bind('SocialBulkVerification', $scope.singleSocialVerification);
console.log("end karthik key");
}
}else{
console.log("single social creation information from previous request");
}
});
}
}
});
} else {
}
}
Any help is appreciated. Thanks in advance.

Related

Textbox to values goes into round number

I bought a PHP script (https://codecanyon.net/item/easy-inventory) for distributor agency. but when I tried to add quantity like 2.55, it turned to 255. First one is textbox code and second one is JS. when I remove onblur ="order(this); "I can enter 2.55 value into textbox but the calculation is not processing. check image:
<td class="vertical-td">
<input type="number" name="qty" style="width: 90px" value="<?php echo $item['qty'] ?>" onblur ="order(this);" id="<?php echo 'qty'.$item['rowid'] ?>" class="form-control">
</td>
Here is JS code
function getXMLHTTP() { //fuction to return the xml http object
var xmlhttp = false;
try {
xmlhttp = new XMLHttpRequest();
}
catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e1) {
xmlhttp = false;
}
}
}
return xmlhttp;
}
$(document).ready(function() {
/*place jQuery actions here*/
var req = getXMLHTTP();
if (req) {
var link = getBaseURL();
//*********************************************
// purchase product Item add to cart
//*********************************************
//$("table.purchase-products form").submit(function () {
//
// var id = $(this).find('input[name=product_id]').val();
//
// $.post(link + "admin/purchase/add_cart_item", {product_id: id, ajax: '1'},
// function (data) {
//
// if (data == 'true') {
//
// $.get(link + "admin/purchase/show_cart", function (cart) {
// $("#cart_content").html(cart);
// });
//
// }
//
// });
//
// return false;
//});
//*********************************************
// add new product to purchase cart
//*********************************************
$("#add-product form").submit(function () {
var product_name = $(this).find('input[name=product_name]').val();
var qty = $(this).find('input[name=qty]').val();
var price = $(this).find('input[name=price]').val();
$.post(link + "admin/purchase/add_new_product_to_cart", {
product_name: product_name,
qty: qty,
price: price,
ajax: '1'
},
function (data) {
if (data == 'true') {
$.get(link + "admin/purchase/show_cart", function (cart) {
$("#cart_content").html(cart);
$("#newform")[0].reset();
});
}
});
return false;
});
}
});
//*********************************************
// Get Base URL
//*********************************************
function getBaseURL() {
return link = $('body').data('baseurl');
};
//*********************************************
// Update cart purchase cart item
//*********************************************
function purchase(arg){
$('#btn_purchase').attr('disabled','disabled');
var val = arg.getAttribute('id');
var id = val.slice(3);
// do your stuff
var qty = $( "#qty"+id ).val();
var price = $( "#pri"+id ).val();
//alert(price);
var link = getBaseURL();
$.post(link + "admin/purchase/update_cart_item", {rowid: id, qty: qty, price: price ,ajax: '1'},
function (data) {
if (data == 'true') {
$.get(link + "admin/purchase/show_cart", function (cart) {
$("#cart_content").html(cart);
});
}
});
}
//*********************************************
// Update order cart item
//*********************************************
function order(arg){
$('#btn_order').attr('disabled','disabled');
var req = getXMLHTTP();
if (req) {
var val = arg.getAttribute('id');
var id = val.slice(3);
// do your stuff
var qty = $("#qty" + id).val();
var price = $("#pri" + id).val();
var product_code = $("#code" + id).val();
if($("#opt" + id).prop("checked") == true){
var custom_price = 'on';
}
var link = getBaseURL();
if(qty && price && product_code)
$.post(link + "admin/order/update_cart_item", {
rowid: id,
qty: qty,
price: price,
product_code: product_code,
custom_price: custom_price,
ajax: '1'
},
function (data) {
if (data == 'false') {
var flag = 'inventory';
var url = link + "admin/order/new_order/"+flag;
$(location).attr("href", url);
}
if (data == 'true') {
$.get(link + "admin/order/show_cart", function (cart) {
$("#cart_content").html(cart);
});
$.get(link + "admin/order/show_cart_summary", function (cart_summary) {
$("#cart_summary").html(cart_summary);
});
//$('#btn_order')..removeAttr('disabled');
}
});
}
}
//*********************************************
// Custom Price Operation
//*********************************************
function price_checkbox(me)
{
var val = me.id
var id = val.slice(3);
//alert(id);
var result = $("#pri" + id).prop('disabled');
if(result){
$("#pri" + id).prop('disabled',false);
}else{
$("#pri" + id).prop('disabled',true);
}
if(result == false){
$('#btn_order').attr('disabled','disabled');
var req = getXMLHTTP();
if (req) {
// do your stuff
var qty = $("#qty" + id).val();
var price = $("#pri" + id).val();
var product_code = $("#code" + id).val();
var custom_price = 'unchecked';
var link = getBaseURL();
$.post(link + "admin/order/update_cart_item", {
rowid: id,
qty: qty,
price: price,
product_code: product_code,
custom_price: custom_price,
ajax: '1'
},
function (data) {
if (data == 'true') {
$.get(link + "admin/order/show_cart", function (cart) {
$("#cart_content").html(cart);
});
$.get(link + "admin/order/show_cart_summary", function (cart_summary) {
$("#cart_summary").html(cart_summary);
});
}
});
}
}
}
//*********************************************
// Customer phone number check
//*********************************************
function check_phone(phone) {
var customer_id = $("#customer_id").val();
//alert(customer_id);
var link = getBaseURL();
var strURL = link + "admin/customer/check_customer_phone/" + phone + "/" + customer_id;
var req = getXMLHTTP();
if (req) {
req.onreadystatechange = function() {
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
var result = req.responseText;
document.getElementById('phone_result').innerHTML = result;
if (result) {
$('#customer_btn').prop('disabled', true);
} else {
$('#customer_btn').prop('disabled', false);
}
validation_check();
} else {
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("POST", strURL, true);
req.send(null);
}
}
//*********************************************
// Employee user name check
//*********************************************
function check_user_name(str) {
$('#sbtn').attr('disabled','disabled');
var user_name = $.trim(str);
var user_id = $.trim($("#employee_id").val());
var link = getBaseURL();
//alert(link);
var strURL = link + "admin/global_controller/check_existing_user_name/" + user_name + "/" + user_id;
var req = getXMLHTTP();
if (req) {
req.onreadystatechange = function() {
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
var result = req.responseText;
document.getElementById('username_result').innerHTML = result;
var msg = result.trim();
if (msg) {
document.getElementById('sbtn').disabled = true;
} else {
document.getElementById('sbtn').disabled = false;
}
} else {
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("POST", strURL, true);
req.send(null);
}
}
//*********************************************
// Product Category to Subcategory
//*********************************************
function get_category(str) {
if (str == '') {
$("#subcategory").html("<option value=''>Select Subcategory</option>");
} else {
$("#subcategory").html("<option value=''>Select Subcategory</option>");
var link = getBaseURL();
var strURL = link + "admin/product/get_subcategory_by_category/" + str;
var req = getXMLHTTP();
if (req) {
req.onreadystatechange = function() {
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
var result = req.responseText;
//alert(result);
$("#subcategory").html("<option value=''>Select Subcategory</option>");
$("#subcategory").append(result);
} else {
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("POST", strURL, true);
req.send(null);
}
}
}
//*********************************************
// Change Password method div show hide
//*********************************************
function setVisibility() {
var a = $('#change_password').val();
var result = a.toString()
if( result == 'Change Password'){
$('#change_password').val('Hide Password'),
$('#password_flag').val('ok'),
$('#password_div').show();
}else{
$('#change_password').val('Change Password'),
$('#password_flag').val('no'),
$('#password_div').hide();
}
}
//*********************************************
// Purchase payment method show hide
//*********************************************
$(function() {
$('#payment_type').change(function(){
$("#pri" + id).prop('disabled',false);
if(val == 'cheque')
{
$('#payment').show();
}
else if (val == 'card')
{
$('#payment').show();
} else
{
$('#payment').hide();
}
});
});
//*********************************************
// Order payment method show hide
//*********************************************
$(function() {
$('#order_payment_type').change(function(){
var val = $( "#order_payment_type" ).val();
if(val == 'cheque')
{
$('#payment').show();
}
else if (val == 'card')
{
$('#payment').show();
} else
{
$('#payment').hide();
}
});
});
//*********************************************
// Order Confirmation Method
//*********************************************
$(function() {
$('#order_confirmation').change(function(){
var val = $( "#order_confirmation" ).val();
if(val == '2')
{
$('#payment_method_block').show();
}else
{
$('#payment_method_block').hide();
}
});
});
//*********************************************
// Email Campaign
//*********************************************
$("#sendEmail form").submit(function () {
var campaign_id = $(this).find('input[name=campaign_id]').val();
var req = getXMLHTTP();
if (req) {
var link = getBaseURL();
$.post(link + "admin/campaign/send_email", {
campaign_id: campaign_id,
ajax: '1'
},
function (data) {
if (data == 'true') {
$.get(link + "admin/purchase/show_cart", function (cart) {
$("#cart_content").html(cart);
$("#newform")[0].reset();
});
}
});
return false;
}
});
//*********************************************
// Update Discount %
//*********************************************
function discountValue(discount) {
var link = getBaseURL();
var req = getXMLHTTP();
if (req) {
$.post(link + "admin/order/assign_discount", {
discount: discount,
ajax: '1'
},
function (data) {
if (data == 'false') {
var flag = 'inventory';
var url = link + "admin/order/new_order/"+flag;
$(location).attr("href", url);
}
if (data == 'true') {
$.get(link + "admin/order/show_cart_summary", function (cart_summary) {
$("#cart_summary").html(cart_summary);
});
}
});
}
}
function getCustomer(customer) {
var link = getBaseURL();
var req = getXMLHTTP();
if (req) {
$.post(link + "admin/order/get_customer", {
customer_id: customer.value,
ajax: '1'
},
function (data) {
if (data == 'false') {
var flag = 'inventory';
var url = link + "admin/order/new_order/"+flag;
$(location).attr("href", url);
}
if (data == 'true') {
$.get(link + "admin/order/show_cart_summary", function (cart_summary) {
$("#cart_summary").html(cart_summary);
});
}
});
}
}
//*********************************************
// Product Code check
//*********************************************
function check_product_code(str) {
$('#submit').attr('disabled','disabled');
var product_code = $.trim(str);
var product_id = $.trim($("#product_id").val());
var link = getBaseURL();
var req = getXMLHTTP();
if (req) {
$.post(link + "admin/product/check_product_code", {
product_code: product_code,
product_id: product_id,
ajax: '1'
},
function (data) {
if (data) {
document.getElementById('product_code_result').innerHTML = data;
document.getElementById('submit').disabled = true;
} else {
document.getElementById('submit').disabled = false;
$('#product_code_result').empty();
}
});
}
}

How do I call a vendor library from my main.js?

I have a basic electron app where I am trying to use vendor supplied js library. The example they supplied provides a static html page which includes their custom library and an example js file. This is the html
<HTML>
<HEAD>
<TITLE> MWD Library </TITLE>
</HEAD>
<BODY>
<h2>MWD Library Example</h2>
<input id="authAndConnect" type="button" value="authenticate and connect to stream" onclick="authenticateAndConnectToStream()" /></br></br>
<input id="clickMe" type="button" value="place position" onclick="placePosition()" /></br></br>
<input id="unsubscribeMe" type="button" value="unsubscribe" onclick="unsubscribe()" />
<input id="streamError" type="button" value="reconn to stream" onclick="reconnectToStream()" />
<input id="historicalData" type="button" value="historical data for GOLD" onclick="getHistoricalData()" />
<input id="goldExpiries" type="button" value="expiries for GOLD" onclick="getCurrentGoldExpiries()" /></br></br>
<input id="userTrades" type="button" value="active&completed trades" onclick="getUserTrades()" />
</BODY>
<SCRIPT SRC="jquery.ajax.js"></SCRIPT>
<SCRIPT SRC="mwdlib.js"></SCRIPT>
<SCRIPT SRC="app.js"></SCRIPT>
</HTML>
In the example above the button click calls authenticateAndConnectToStream in their example apps.js
//DEMO
//provide API key
MWDLibrary.config("dwR4jXn9ng9U2TbaPG2TzP1FTMqWMOuSrCWSK5vRIW7N9hefYEapvkXuYfVhzmdyFypxdayfkUT07HltIs4pwT0FIqEJ6PyzUz0mIqGj1GtmAlyeuVmSC5IcjO4gz14q");
//authenticate on MarketsWorld
var getAuthTokenParams = {email:"rtmarchionne#gmail.com", password:"Pitts4318AEM"};
var authenticateAndConnectToStream = function(){
MWDLibrary.getAuthDetails(getAuthTokenParams, function(authDetails) {
//optional: get older data
var marketsToSubscribeTo = ['GOLD', 'AUDNZD'];
for (var i = 0; i < marketsToSubscribeTo.length; i++){
MWDLibrary.getHistoricalData(marketsToSubscribeTo[i], function(response) {
console.log(response);
}, function(errorMessage) {
console.log(errorMessage);
});
}
//now you can connect to stream
MWDLibrary.connect(marketsToSubscribeTo, function() {
addMarketsListeners();
}, function(errorMessage) {
console.log(errorMessage);
});
}, function(errorMessage) {
console.log(errorMessage);
});
};
I want to call the same methods that start with MWDLibrary. from my main js like MWDLibrary.config("dwR4jXn9")
My main.js:
const electron = require('electron')
var path = require('path');
var countdown = require(path.resolve( __dirname, "./tradescaler.js" ) );
var mwd = require(path.resolve( __dirname, "./mwdlib.js" ) );
const app = electron.app
const BrowserWindow = electron.BrowserWindow
const ipc = electron.ipcMain
let mainWindow
app.on('ready', _ => {
mainWindow = new BrowserWindow({
height: 360,
width: 700,
title: "TradeScaler Beta - Creative Solutions",
//frame: false,
alwaysOnTop: true,
autoHideMenuBar: true,
backgroundColor: "#FF7E47",
})
mainWindow.loadURL('file://' + __dirname + '/tradescaler.html')
mainWindow
//mainWindow.setAlwaysOnTop(true, 'screen');
mainWindow.on('closed', _ => {
mainWindow = null
})
})
ipc.on('countdown-start', _ => {
console.log('caught it!');
MWDLibrary.config();
countdown(count => {
mainWindow.webContents.send('countdown', count)
})
})
In my main.js above I get an error that says MWDLibrary is not defined.
Is it the structure of the library that is the problem? do i have to pass a window or modify the library?
Here is the library I'm trying to use:
(function(window){
'use strict';
function init(){
var MWDLibrary = {};
var transferProtocol = "https://"
var streamTransferProtocol = "https://"
var baseTLD = "www.marketsworld.com"
var basePort = ""
var streamBaseTLD = "www.marketsworld.com"
var streamPort = ""
var authToken = "";
var publicId = "";
var userLevel = "user";
var apiKey = "-";
var streamUrl = "";
var streamToken = "";
var subscribedChannels = [];
var streamEvents = {};
var offersWithExpiries = [];
var filteredExpiries = {};
var positions = {};
var evtSource;
MWDLibrary.config = function(apiUserKey){
apiKey = apiUserKey;
}
MWDLibrary.expiries = function(market){
return filteredExpiries[market];
}
MWDLibrary.connect = function(channelsToSubscribeTo, successHandler, errorHandler){
//console.log("Connecting...");
if(publicId === ""){
errorHandler("Please authenticate first.");
return;
}
var dispatchUrl = streamTransferProtocol+streamBaseTLD+streamPort+'/api/dispatcher';
getJSON(dispatchUrl, apiKey, authToken, function(data){
var data_from_json = JSON.parse(data);
if(data_from_json.url){
var url = data_from_json.url+'/announce?callback=__callback&publicToken='+publicId+'&userLevel='+userLevel+'&_='+(new Date().getTime() / 1000);
getJSON(url, apiKey, authToken, function(data) {
var data_from_json = JSON.parse(data);
if(data_from_json.url){
streamUrl = data_from_json.url.substring(0,data_from_json.url.lastIndexOf("/user"));
streamToken = data_from_json.url.split("token=")[1];
MWDLibrary.subscribe(channelsToSubscribeTo, function(subscribeResponseData) {
evtSource = new EventSource(streamTransferProtocol+data_from_json.url);
evtSource.onopen = sseOpen;
evtSource.onmessage = sseMessage;
evtSource.onerror = sseError;
successHandler('connected');
return;
}, function(errorMessage) {
errorHandler(errorMessage);
return;
});
}
else{
//console.log(data);
errorHandler('Something went wrong.');
return;
}
}, function(status) {
//console.log(status);
errorHandler(status);
return;
});
}
else{
//console.log(data);
errorHandler('Something went wrong.');
return;
}
}, function(status) {
//console.log(status);
errorHandler(status);
return;
});
}
MWDLibrary.subscribe = function(channelsToSubscribeTo, successHandler, errorHandler){
//console.log("Subscribing...");
if(publicId === ""){
errorHandler("Please authenticate first.");
return;
}
var channels = 'ALL|TEST|private.'+publicId;
if (channelsToSubscribeTo.length > 0){
var auxChannels = '';
if(subscribedChannels.length > 0){
channels = subscribedChannels[0];
for(var j = 1; j < subscribedChannels.length; j++){
channels = channels +'|'+subscribedChannels[j];
}
}
for(var i = 0; i < channelsToSubscribeTo.length; i++)
{
if(subscribedChannels.indexOf(channelsToSubscribeTo[i])==-1){
auxChannels = auxChannels+'|'+channelsToSubscribeTo[i]+'|'+channelsToSubscribeTo[i]+'.game#1';
}
}
channels = channels+auxChannels;
}
else{
if (subscribedChannels.length == 0)
{
channels = channels+'|GOLD|GOLD.game#1';
}
else{
channels = subscribedChannels[0];
for (var j = 1; j < subscribedChannels.length; j++){
channels = channels + '|' + subscribedChannels[j];
}
}
}
var subscribeUrl = streamTransferProtocol+streamUrl+'/user/stream/subscribe?callback=__callback&token='+streamToken+'&channels='+escape(channels)+'&_='+(new Date().getTime() / 1000);
//subscribe to channels
getJSON(subscribeUrl, apiKey, authToken, function(subscribeData) {
var subscribeData_from_json = JSON.parse(subscribeData);
subscribedChannels = subscribeData_from_json.channels;
//console.log(subscribedChannels);
for (var i = 0; i < subscribedChannels.length; i++)
{
if (subscribedChannels[i] == 'ALL')
{
streamEvents[subscribedChannels[i]] = {};
streamEvents[subscribedChannels[i]]['heartbeat'] = new CustomEvent('ALL.heartbeat', {'detail':'-'});
streamEvents[subscribedChannels[i]]['status'] = new CustomEvent('ALL.status', {'detail':'-'});
continue;
}
if (subscribedChannels[i].lastIndexOf('private') > -1)
{
streamEvents[subscribedChannels[i]] = {};
streamEvents[subscribedChannels[i]]['positions'] = new CustomEvent('PRIVATE.positions', {'detail':'-'});
streamEvents[subscribedChannels[i]]['balance'] = new CustomEvent('PRIVATE.balance', {'detail':'-'});
continue;
}
if (subscribedChannels[i].lastIndexOf('game') > -1)
{
streamEvents[subscribedChannels[i]] = {};
streamEvents[subscribedChannels[i]]['expiry'] = new CustomEvent(subscribedChannels[i].split('.')[0]+'.expiry', {'detail':'-'});
streamEvents[subscribedChannels[i]]['spread'] = new CustomEvent(subscribedChannels[i].split('.')[0]+'.spread', {'detail':'-'});
streamEvents[subscribedChannels[i]]['payout'] = new CustomEvent(subscribedChannels[i].split('.')[0]+'.payout', {'detail':'-'});
streamEvents[subscribedChannels[i]]['offer'] = new CustomEvent(subscribedChannels[i].split('.')[0]+'.offer', {'detail':'-'});
continue;
}
streamEvents[subscribedChannels[i]] = {};
streamEvents[subscribedChannels[i]]['value'] = new CustomEvent(subscribedChannels[i]+'.value', {'detail':'-'});
}
successHandler(subscribeData_from_json);
}, function(status) {
errorHandler(status);
});
}
MWDLibrary.unsubscribe = function(channelsToUnsubscribeFrom, successHandler, errorHandler){
//console.log("Unsubscribing...");
if(publicId === ""){
errorHandler("Please authenticate first.");
return;
}
if(channelsToUnsubscribeFrom.length == 0){
errorHandler("Please select markets to unsubscribe from.");
return;
}
var channels = channelsToUnsubscribeFrom[0]+'|'+channelsToUnsubscribeFrom[0]+'.game#1';
for(var i = 1; i < channelsToUnsubscribeFrom.length; i++)
{
channels = channels+'|'+channelsToUnsubscribeFrom[i]+'|'+channelsToUnsubscribeFrom[i]+'.game#1';
}
var subscribeUrl = streamTransferProtocol+streamUrl+'/user/stream/unsubscribe?callback=__callback&token='+streamToken+'&channels='+escape(channels)+'&_='+(new Date().getTime() / 1000);
//subscribe to channels
getJSON(subscribeUrl, apiKey, authToken, function(unsubscribeData) {
var unsubscribeData_from_json = JSON.parse(unsubscribeData);
var unsubscribedChannels = unsubscribeData_from_json.channels;
for(var i = 0; i < unsubscribedChannels.length; i++)
{
var index = subscribedChannels.indexOf(unsubscribedChannels[i]);
if(index != -1) {
subscribedChannels.splice(index, 1);
}
}
//console.log(subscribedChannels);
successHandler(unsubscribeData_from_json);
}, function(status) {
errorHandler(status);
});
}
MWDLibrary.getAuthDetails = function(params, successHandler, errorHandler){
//console.log("getting auth token...");
var url = transferProtocol+baseTLD+basePort+'/api/v2/sessions';
postJSON(url, apiKey, authToken, params, function(data) {
var data_from_json = JSON.parse(data);
if (!data_from_json.error){
authToken = data_from_json.api_session_token.token;
publicId = data_from_json.api_session_token.user.public_id;
successHandler(data_from_json.api_session_token);
return;
}
else{
errorHandler(data_from_json.error);
return;
}
}, function(status) {
errorHandler(status);
return;
});
}
MWDLibrary.placePosition = function(params, successHandler, errorHandler){
//console.log("placing a position...");
if(publicId === ""){
errorHandler("Please authenticate first.");
return;
}
var url = transferProtocol+baseTLD+basePort+'/api/v2/positions';
if(params.market == ''){
errorHandler('Market code is missing.');
return;
}
var position = positions[params.market];
if(!position || position.market_value <= 0){
errorHandler('No data for this market.');
return;
}
if(!params.offer_id || params.offer_id == ''){
errorHandler('Offer id is missing.');
return;
}
if(!params.resolution_at || params.resolution_at <= 0){
errorHandler('Expiry time is missing.');
return;
}
if(!params.type || params.type == ''){
errorHandler('Position type is missing.');
return;
}
if(!params.wager || params.wager <= 0){
errorHandler('Wager is missing.');
return;
}
position.offer_id = params.offer_id;
position.resolution_at = params.resolution_at;
position.type = params.type;
position.wager = params.wager;
//console.log(position);
postJSON(url, apiKey, authToken, position, function(data) {
var data_from_json = JSON.parse(data);
if (!data_from_json.error){
successHandler(data_from_json);
return;
}
else{
errorHandler(data_from_json.error);
return;
}
}, function(status) {
errorHandler(status+' - make sure all parameters are set correctly and wait 10 seconds between bets');
return;
});
}
MWDLibrary.getMarkets = function(successHandler, errorHandler){
//console.log("getting markets list...");
getJSON(transferProtocol+baseTLD+basePort+'/api/v2/markets.json', apiKey, authToken, function(data) {
var data_from_json = JSON.parse(data);
for (var i = 0; i < data_from_json.length; i++) {
var status = "closed";
if (data_from_json[i].market.next_open_time > data_from_json[i].market.next_close_time)
{
status = "open";
}
data_from_json[i].market.status = status;
}
successHandler(data_from_json);
}, function(status) {
errorHandler(status);
});
}
var sortedOffersWithExpiries = offers.sort(compareOffersBtOrder);
for (var i=0; i<sortedOffersWithExpiries.length;i++)
{
expiryValue = 0;
expiryResult = 0;
var expiriesCopy = sortedOffersWithExpiries[i].expiries;
for (var index = 0; index<expiriesCopy.length;index++)
{
expiryValue = expiriesCopy[index]
if (expiryValue > lastExpiry)
{
expiryResult = expiryValue
break
}
}
if (expiryResult != 0)
{
var tuple = {};
tuple.timestamp = expiryValue/1000;
tuple.offerId = sortedOffersWithExpiries[i].offer;
tuple.cutout = sortedOffersWithExpiries[i].cutout;
expiriesFinalList.push(tuple);
lastExpiry = expiryValue
}
}
return expiriesFinalList;
}
function compareOffersBtOrder(a,b) {
if (a.order < b.order)
return -1;
if (a.order > b.order)
return 1;
return 0;
}
})/*(window)-->*/;
You're missing the .js file extension at the end of mwdlib
And you may need to require it using the full system path, instead of a relative one.
var mwd = require(path.resolve( __dirname, "./mwdlib.js" ) );

How to display alert after AJAX post success.alert?

In my Node application I have used get and post request. Using get just renders the page and using post insert data into MySQL database. Data is inserted properly but after post gets called and alert fade away very quickly.
This is my code from app.js:
app.get('/Associate', routes.Associate);
app.get('/addAssociate',routes.addAssociate);
app.post('/addAssociate',routes.postAssociate);
This is my code from routes.js:
Associate: function(req, res) {
sess = req.session;
var name = req.session.user;
var username = 'SELECT first_name from user_info where email_id=?';
if (sess.user) {
console.log('\n--------------------- Associate ----------------------');
var db = req.app.get('db')();
var id = req.query['id'];
// var newsquery='SELECT * from associate_info';
var assoquery = 'SELECT associate_id,doctor_id,CONCAT(initial," ",first_name," ",middle_name," ",last_name) As Name,qualification,address_line1,city,state,pincode,email_id,contact_no from associate_info ';
var redirect = 'Associate_Listing';
async.parallel({
one: function(callback) {
db.query(assoquery, function(error, rows, fields, next) {
console.log("length-\t", rows.length);
callback(error, rows);
});
},
two: function(callback) {
db.query(username, [name], function(error, rows, fields, next) {
// console.log(rows.length);
console.log(rows);
callback(error, rows);
});
}
},
function(error, results) {
var totalNews = results.one.length;
for (var i = 0; i < results.one.length; i++) {
if (!(results.one[i].views > 0) || results.one[i].views == null)
results.one[i].views = 0;
results.one[i].ids = i + 1;
// if(!(results.one[i].views>0))
// results.one[i].views=0;
}
// console.log("--------",results.one[0].id);
res.render(redirect, {
error: JSON.stringify(1),
from_period: 0,
to_period: 0,
state: JSON.stringify("All States"),
user2: "Dr" + " " + JSON.parse(JSON.stringify(results.two[0]["first_name"])),
user: JSON.parse(JSON.stringify(req.session.user)),
Associate: results.one,
str_journal: JSON.stringify(results.one),
user_type_id: req.session.user_type_id,
totalJournals: JSON.stringify(totalNews)
});
});
} else {
res.redirect('/login');
}
},
// addJournal:function(req,res){
addAssociate: function(req, res) {
console.log('\n-------------------- addAssociate ----------------------\n');
var name = req.session.user;
var db = req.app.get('db')();
var username = 'SELECT first_name from user_info where email_id=?';
if (req.session.user) {
async.parallel({
one: function(callback) {
db.query(username, [name], function(error, rows, fields, next) {
console.log("length-\t", rows.length);
callback(error, rows);
});
}
},
function(error, results) {
res.render('addAssociate', {
user: JSON.parse(JSON.stringify(req.session.user)),
// cases : results.one,
user2: "Dr" + " " + JSON.parse(JSON.stringify(results.one[0]["first_name"])),
user_type_id: req.session.user_type_id,
// totalNews :JSON.stringify(totalNews)
})
});
} else {
res.redirect('/login');
// res.redirect('addAssociate');
}
},
postAssociate: function(req, res) {
console.log('\n-------------------- postAssociate ----------------------\n');
var db = req.app.get('db')();
// res.send('Username: ' + req.body.doctorName);
// var title = req.body.title;
// var created =req.body.created;
// initial : req.body.doctorName,
// var id=1;
// var dateArray=created.split('/');
// var finalDate=""+dateArray[2]+"/"+dateArray[1]+"/"+dateArray[0];
// var date1=new Date(finalDate);
var initial;
var first_name;
var middle_name;
var last_name;
var qualification;
var address_line1;
var address_line2;
var city;
var state;
var pincode;
var email_id;
var contact_no;
var Uname = req.session.user;
var post = {
initial: req.body.initial,
first_name: req.body.first_name,
middle_name: req.body.middle_name,
last_name: req.body.last_name,
qualification: req.body.qualification,
address_line1: req.body.address_line1,
address_line2: req.body.address_line2,
city: req.body.city,
state: req.body.state,
pincode: req.body.pincode,
email_id: req.body.email_id,
contact_no: req.body.contact_no,
status: 1,
};
console.log('--------------------' + initial)
console.log(initial);
console.log(post);
db.query('SELECT * from user_info where email_id= ? ', [Uname], function(error, rows, fields) {
if (error) {
console.log(error);
} else {
console.log('name------------' + Uname);
console.log('rows---------' + rows.length);
for (var i in rows) {
console.log('----------hhh---' + rows[i].doctor_id);
}
db.query('INSERT INTO associate_info SET doctor_id=' + rows[i].doctor_id + ', creation_date=CURRENT_TIMESTAMP(), ? ', post, function(error, result) {
console.log('inside if');
if (error) {
console.log(error);
res.status(200).send({
success: 3,
error: error
});
return;
}
console.log('Associate added successfully.');
});
}
});
},
this is jquery ajax code
$(document).ready(function() {
$("#save").click(function() {
var initial = $("#doctorName").val();
var first_name = $("#firstName").val();
var middle_name = $("#middleName").val();
var last_name = $("#lastName").val();
var qualification = $("#qualification").val();
var address_line1 = $("#address1").val();
var address_line2 = $("#address2").val();
var city = $("#city").val();
var state = $("#state").val();
var pincode = $("#pincode").val();
var email_id = $("#email").val();
var contact_no = $("#mobile").val();
var dr = /^[a-zA-Z]+\.$/;
var alphaExp = /^[a-zA-Z]+$/;
var zipexp = /^[0-9]{1,6}$/;
var mobileexp = /^(\+91-|\+91|0)?\d{10}$/;
var emailexp = /^[A-Z0-9_'%=+!`#~$*?^{}&|-]+([\.][A-Z0-9_'%=+!`#~$*?^{}&|-]+)*#[A-Z0-9-]+(\.[A-Z0-9-]+)+$/i;
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'initial=' + initial + '&first_name=' + first_name + '&middle_name=' + middle_name + '&last_name=' + last_name + '&qualification=' + qualification + '&address_line1=' + address_line1 + '&address_line2=' + address_line2 + '&city=' + city + '&state=' + state + '&pincode=' + pincode + '&email_id=' + email_id + '&contact_no=' + contact_no;
if (initial == '' || first_name == '' || middle_name == '' || last_name == '' || qualification == '' || address_line1 == '' || address_line2 == '' || city == '' || state == '' || pincode == '' || email_id == '' || contact_no == '') {
alert("Please Fill All Mandatory Fields");
return false;
} else if (!initial.match(alphaExp) && !initial.match(dr)) {
alert("please insert valid initial");
$("#doctorName").val('');
document.getElementById('doctorName').focus();
return false;
} else if (!first_name.match(alphaExp)) {
alert("please insert valid first name");
$("#firstName").val('');
document.getElementById('firstName').focus();
return false;
} else if (!middle_name.match(alphaExp)) {
alert("please insert valid middle name");
$("#middleName").val('');
document.getElementById('middleName').focus();
return false;
} else if (!last_name.match(alphaExp)) {
alert("please insert valid last name");
$("#lastName").val('');
document.getElementById('lastName').focus();
return false;
} else if (!pincode.match(zipexp) || pincode.length != 6) {
alert("please insert valid pincode");
$("#pincode").val('');
document.getElementById('pincode').focus();
return false;
} else if (!email_id.match(emailexp)) {
alert("please insert email id");
$("#email").val('');
document.getElementById('email').focus();
return false;
} else if (!contact_no.match(mobileexp)) {
alert("please insert valid contact no");
$("#mobile").val('');
document.getElementById('mobile').focus();
return false;
} else {
// AJAX Code To Submit Form.
$.ajax({
type: "post",
url: "/addAssociate",
// contentType: 'application/json',
data: dataString,
cache: false,
success: function(data) {
console.log("data-----------" + data);
alert("hi");
}
});
}
// return;
// return false;
});
});
I want to display an alert after data inserted successfully into database.
Just Try the Following to make some delay.
jQuery :
$.ajax({
url:'path-to-process',
type:'POST',
data:{},
success:function(){
// Content to Display on Success.
setTimeout(function () {
// Content to Display on Success with delay.
}, 800);
}
});
Here, the "setTimeout()" will provide some specified time delay for display your content.
Have a Nice Day !
http://jsbin.com/jatuju/edit?js,output
If you are using the plan old JavaScript,you can using the XMLHttpRequest status code to determine whether is success or not

Pubnub getting duplicated message when changing channel

I have a problem with pubnub.
I have friends list and I need to change pubnub channel on clicking them, by switching to another friend, to chat with him.
I have global channel variable, and I am changing it on friend click. The problem is, when I switch to another friend and write a message, the message appears in panel is duplicated.
Here is the code I am using.
base = "/";
pubnub = "";
channel ="";
messageListContent = "ul.chat-messages-block";
function handleMessage(message,$index) {
if ( $index != 'me' ) {
var $index = 'left';
} else {
var $index = 'right';
}
var $imageUrl = "";
if ( message.picture != '' && message.picture != null ) {
$imageUrl = message.picture;
if ( (/^http:\/\//.test( $imageUrl ) ) ) {
$imageUrl = $imageUrl;
} else {
$imageUrl = "uploads/user/"+ $imageUrl;
}
} else {
$imageUrl = 'resources/images/user-male.png';
}
var messageEl = jQuery('<li class="'+$index+' clearfix">'+
'<div class="user-img pull-'+$index+'"> <img src="' + $imageUrl +'" alt="'+message.username+'"> </div>'+
'<div class="chat-body clearfix">'+
'<div class="">'+
'<span class="name">'+message.username+'</span><span class="name"></span><span class="badge"><i class="fa fa-clock-o"></i>'+message.chat_date+'</span></div>'+
'<p>'+ message.message + '</p>'+
' </div>'+
'</li>');
jQuery(messageListContent).append(messageEl);
};
jQuery.getJSON( "/chat/read", function( data ) {
var items = [];
if ( data != null && data != "" ){
pubnub = PUBNUB.init({
publish_key: data.publish_key,
subscribe_key: data.subscribe_key,
});
if ( data.messages.length > 0 ) {
var $my_id = data.current_user;
for( var i = 0; i < data.messages.length; i++ ) {
if ( data.messages[i].user_id == $my_id ) {
$index = "me";
} else {
var $index = "";
}
handleMessage(data.messages[i],$index);
}
}
}
});
jQuery(document).ready(function () {
jQuery('#sendMessageButton').click(function (event) {
var message = jQuery('#messageContent').val();
var friend_id = jQuery('li.activeChannel').attr('data-id');
if ( message != '' ) {
jQuery.ajax({
url: base+"chat/sendChat",
type:'POST',
data:{
friend_id: friend_id,
text:message
},
success:function(data){
var data = JSON.parse(data);
//sounds.play( 'chat' );
pubnub.publish({
channel: channel,
message: {
username: data.messages.username,
message: data.messages.message,
user_id: data.messages.friend_id,
current_user: data.messages.user_id,
picture: data.messages.picture,
type:'message',
chat_date: data.messages.chat_date
}
});
},
error: function(err){
jQuery('.errorText').fadeIn();
}
});
jQuery('#messageContent').val("");
}
});
// Also send a message when the user hits the enter button in the text area.
jQuery('#messageContent').bind('keydown', function (event) {
if((event.keyCode || event.charCode) !== 13) return true;
jQuery('#sendMessageButton').click();
return false;
});
jQuery('ul.chat-users li').click(function(){
var friend_id = jQuery(this).attr('data-id');
jQuery('ul.chat-users li').removeClass('activeChannel');
jQuery(this).addClass('activeChannel');
jQuery.ajax({
url: base+"chat/getUsersChat",
type:'POST',
data:{
friend_id: friend_id
},
success:function(data){
var data = JSON.parse(data);
jQuery('.chat-messages ul').html("");
//id = pubnub.uuid();
//channel = 'oo-chat-' + id+friend_id;
channel = 'oo-chat-' + data.channel;
if ( data.messages.length > 0 ) {
var $my_id = data.current_user;
for( var i = 0; i < data.messages.length; i++ ) {
if ( data.messages[i].user_id == $my_id ) {
$index = "me";
} else {
var $index = "";
}
//messageListContent = "ul.activeChannel"+channel;
//console.log(channel);
handleMessage(data.messages[i],$index);
}
}
pubnub.subscribe({
channel: channel,
message: function(message) {
console.log("Pubnub callback", message);
handleMessage(message,"me");
},
connect: function(message) {
console.log("Pubnub is connected", message);
},
//callback:
});
},
error: function(err){
jQuery('.errorText').fadeIn();
}
});
});
});
And here is how it is looking
Any Idea?
I had even tried to unsubscribe the previous channel on friend click, but no result.
What am I doing wrong?
I solved the problem. The problem was in pubnub.js version, it was 3.4, I switched to 3.7.1 and added the following code
jQuery('ul.chat-users li').click(function(){
var friend_id = jQuery(this).attr('data-id');
jQuery('ul.chat-users li').removeClass('activeChannel');
jQuery(this).addClass('activeChannel');
if ( channel != "" ) {
pubnub.unsubscribe({
channel : channel,
});
}

Function within function want to execute very first function completely

I got a problem.I have multiple callback functions .
Function within function within a loop
I want to execute very first function fully first . Then I want to move further.
Currenlty no function is working fine:
function recurring_end() {
var diffbot = new Diffbot('ddddd');
var sql= "SELECT `bookmarks`.`id`,`bookmarks`.`bookmark_url` as url FROM bookmarks LIMIT 0, 10";
connection.query(sql, function(err,bookmarks) {
console.log(JSON.parse(JSON.stringify(bookmarks)));
for(var i = 0; i< bookmarks.length; i++){
(function(i) {
bookmark_id = bookmarks[i].id;
bookmark_url = bookmarks[i].url;
parseArticle(i,bookmark_id,bookmark_url,function(err,result){
bookamrk_title= result.bookmark_title;
bookmark_body= result.body;
bookmark_file_name= result.file_name;
preview_image = result.preview_image;
local_image_name = result.local_image_name;
mainPreviewImage = result.mainPreviewImage;
viewImage=result.viewImage;
var mediaExist =result.mediaExist;
if(mediaExist == 1) {
console.log("Entered in Media Exist");
download(preview_image, "images/" + local_image_name, function() {
console.log("Entered in download");
fs.exists("images/" + local_image_name, function(exists) {
console.log("Before Sending " +mainPreviewImage);
console.log("Before Sending Local " +local_image_name);
ImageMagic(local_image_name,mainPreviewImage,223,147,function(err,result) {
if(result != 0){
mainPreviewImage= result;
console.log("Image Magic Done" +mainPreviewImage);
AmazonUpload(mainPreviewImage,function(err,result) {
console.log("Amazon error "+err);
if(result != 0){
mainPreviewImage = result;
console.log("First Image Uploading is Sucessfully");
/* Now Lets Pass View Image FROM Graphic Magic */
ImageMagic(mainPreviewImage,viewImage,152,100,function(err,result) {
if(result != 0){
viewImage= result;
/* Upload New View File to Amazon */
AmazonUpload(viewImage,function(err,result) {
if(result != 0){
viewImage = result;
console.log("Second Image Upload to Amazon");
/*Finally here we need to write update logic here check it out */
console.log("Serious id is "+i);
console.log("Book Mark id " +bookmark_id);
console.log("bookamrk_title" +bookamrk_title);
console.log("preview_image"+mainPreviewImage);
console.log("viewImage"+viewImage);
console.log("End " +ddd);
}else {
/* need to write update Query here */
var viewImage="thumbnail_default_bookmark1.png";
}
});
}else{
/* need to write update Query here */
var viewImage="thumbnail_default_bookmark1.png";
}
});
}else {
/* need to writeUpdate Query Here */
var mainPreviewImage= 'default_bookmark.png';
var viewImage="thumbnail_default_bookmark1.png";
}
});
}else{
/* need to write Update Query here */
var mainPreviewImage= 'default_bookmark.png';
var viewImage="thumbnail_default_bookmark1.png";
}
});
});
});/* download function closed */
}
});
})(i);
}
console.log("Every Thing is done ");
});
}
function AmazonUpload(uploadImage,callback) {
knox.putFile('images/'+uploadImage,'BookmarkPreviewImages/'+uploadImage, {"Content-Type": "image/jpeg",'x-amz-acl': 'public-read'}, function (err, result) {
if(!err){
if(result.statusCode==200){
callback(err,uploadImage);
}else{
callback(err,0);
}
}else{
callback(err,0);
}
});
}
function download(uri, filename, callback) {
request.head(uri, function(err, res, body) {
//request(uri).pipe(fs.createWriteStream(filename),{end:true}).on('close', callback);
var r = request(uri);
r.pause()
r.on('response', function (resp) {
if(resp.statusCode === 200){
r.pipe(fs.createWriteStream(filename),{end:true}).on('close', callback); //pipe to where you want it to go
r.resume()
}
});
});
};
function ImageMagic(local_image_name,display_image,width,height,callback){
console.log("local_image_name is"+local_image_name);
gm('images/'+local_image_name).resize(width, height, '^').gravity('Center').crop(width, height).write('images/'+display_image, function (err) {
if(!err){
console.log("Sucessfully Image converted is "+display_image);
console.log("Sucessfully image which is converted "+ local_image_name);
callback(null,display_image);
}else{
console.log("Graphic Magic Error "+err);
callback(err,0);
}
});
}
function parseArticle(i,bookmark_id,bookmark_url,callback) {
diffbot.article({uri: bookmark_url}, function(err, response) {
var callBackString= {};
console.log("Diffbot Parsing URL with id " +bookmark_id+"and loop id is"+i);
var bookmark_title = response.title;
var body = response.html;
var timestamp = new Date().getTime().toString();
var file_name = common_function.generateRandomString() + timestamp + '.txt';
var timestamp0 = new Date().getTime().toString();
var local_image_name = common_function.generateRandomString() + timestamp0 + i + '.jpg';
var preview_image = response.media[0]['link'];
if(response.media[0].primary=='true'){
mainPreviewImage = "thumb_" + local_image_name;
viewImage = "thumbnail_" + local_image_name;
mediaExist=1;
}else{
mainPreviewImage="default_bookmark.png";
viewImage="thumbnail_default_bookmark1.png";
mediaExist=0;
}
callBackString .bookmark_title=bookmark_title;
callBackString.body = body;
callBackString.file_name = file_name;
callBackString.preview_image = preview_image;
callBackString.local_image_name = local_image_name;
callBackString.mainPreviewImage = mainPreviewImage;
callBackString.viewImage=viewImage;
callBackString.mediaExist =mediaExist;
callback(null,callBackString);
});
};
I understand the code is too long. I want to get an idea, I want to execute i=0 first completely, then I want to proceed further.
Any Idea how we can do in Nodejs. Any Help Will be appreicated
Thanks
Try replacing the loop with a recursive code like this..
function recurring_end() {
var diffbot = new Diffbot('ddddd');
var sql= "SELECT `bookmarks`.`id`,`bookmarks`.`bookmark_url` as url FROM bookmarks LIMIT 0, 10";
connection.query(sql, function(err,bookmarks) {
console.log(JSON.parse(JSON.stringify(bookmarks)));
var i = 0;
var callbackForParseArticle = function(err,result){
bookamrk_title= result.bookmark_title;
bookmark_body= result.body;
bookmark_file_name= result.file_name;
preview_image = result.preview_image;
local_image_name = result.local_image_name;
mainPreviewImage = result.mainPreviewImage;
viewImage=result.viewImage;
var mediaExist =result.mediaExist;
if(mediaExist == 1) {
console.log("Entered in Media Exist");
download(preview_image, "images/" + local_image_name, function() {
console.log("Entered in download");
fs.exists("images/" + local_image_name, function(exists) {
console.log("Before Sending " +mainPreviewImage);
console.log("Before Sending Local " +local_image_name);
ImageMagic(local_image_name,mainPreviewImage,223,147,function(err,result) {
if(result != 0){
mainPreviewImage= result;
console.log("Image Magic Done" +mainPreviewImage);
AmazonUpload(mainPreviewImage,function(err,result) {
console.log("Amazon error "+err);
if(result != 0){
mainPreviewImage = result;
console.log("First Image Uploading is Sucessfully");
/* Now Lets Pass View Image FROM Graphic Magic */
ImageMagic(mainPreviewImage,viewImage,152,100,function(err,result) {
if(result != 0){
viewImage= result;
/* Upload New View File to Amazon */
AmazonUpload(viewImage,function(err,result) {
if(result != 0){
viewImage = result;
console.log("Second Image Upload to Amazon");
/*Finally here we need to write update logic here check it out */
console.log("Serious id is "+i);
console.log("Book Mark id " +bookmark_id);
console.log("bookamrk_title" +bookamrk_title);
console.log("preview_image"+mainPreviewImage);
console.log("viewImage"+viewImage);
console.log("End " +ddd);
}else {
/* need to write update Query here */
var viewImage="thumbnail_default_bookmark1.png";
}
//additional lines to the end of the function
i++;
if (i<bookmarks.length){
bookmark_id = bookmarks[i].id;
bookmark_url = bookmarks[i].url;
parseArticle(i,bookmark_id,bookmark_url,callbackForParseArticle);
} else {
console.log("Every Thing is done ");
}
});
}else{
/* need to write update Query here */
var viewImage="thumbnail_default_bookmark1.png";
}
});
}else {
/* need to writeUpdate Query Here */
var mainPreviewImage= 'default_bookmark.png';
var viewImage="thumbnail_default_bookmark1.png";
}
});
}else{
/* need to write Update Query here */
var mainPreviewImage= 'default_bookmark.png';
var viewImage="thumbnail_default_bookmark1.png";
}
});
});
});/* download function closed */
}
};
if (bookmarks.length > 0){
parseArticle(i,bookmarks[i].id,bookmarks[i].url,callbackForParseArticle);
}
});
}
function AmazonUpload(uploadImage,callback) {
knox.putFile('images/'+uploadImage,'BookmarkPreviewImages/'+uploadImage, {"Content-Type": "image/jpeg",'x-amz-acl': 'public-read'}, function (err, result) {
if(!err){
if(result.statusCode==200){
callback(err,uploadImage);
}else{
callback(err,0);
}
}else{
callback(err,0);
}
});
}
function download(uri, filename, callback) {
request.head(uri, function(err, res, body) {
//request(uri).pipe(fs.createWriteStream(filename),{end:true}).on('close', callback);
var r = request(uri);
r.pause()
r.on('response', function (resp) {
if(resp.statusCode === 200){
r.pipe(fs.createWriteStream(filename),{end:true}).on('close', callback); //pipe to where you want it to go
r.resume()
}
});
});
};
function ImageMagic(local_image_name,display_image,width,height,callback){
console.log("local_image_name is"+local_image_name);
gm('images/'+local_image_name).resize(width, height, '^').gravity('Center').crop(width, height).write('images/'+display_image, function (err) {
if(!err){
console.log("Sucessfully Image converted is "+display_image);
console.log("Sucessfully image which is converted "+ local_image_name);
callback(null,display_image);
}else{
console.log("Graphic Magic Error "+err);
callback(err,0);
}
});
}
function parseArticle(i,bookmark_id,bookmark_url,callback) {
diffbot.article({uri: bookmark_url}, function(err, response) {
var callBackString= {};
console.log("Diffbot Parsing URL with id " +bookmark_id+"and loop id is"+i);
var bookmark_title = response.title;
var body = response.html;
var timestamp = new Date().getTime().toString();
var file_name = common_function.generateRandomString() + timestamp + '.txt';
var timestamp0 = new Date().getTime().toString();
var local_image_name = common_function.generateRandomString() + timestamp0 + i + '.jpg';
var preview_image = response.media[0]['link'];
if(response.media[0].primary=='true'){
mainPreviewImage = "thumb_" + local_image_name;
viewImage = "thumbnail_" + local_image_name;
mediaExist=1;
}else{
mainPreviewImage="default_bookmark.png";
viewImage="thumbnail_default_bookmark1.png";
mediaExist=0;
}
callBackString .bookmark_title=bookmark_title;
callBackString.body = body;
callBackString.file_name = file_name;
callBackString.preview_image = preview_image;
callBackString.local_image_name = local_image_name;
callBackString.mainPreviewImage = mainPreviewImage;
callBackString.viewImage=viewImage;
callBackString.mediaExist =mediaExist;
callback(null,callBackString);
});
};
Use async.js to manage your code flow
If you have multiple functions, func_1, func_2, func_3, that need to run in sequence, the code is
var async = require('async');
var functionList = [func_1, func_2, func_3];
async.series(functionList, function(err, result){
// results of func_1, func_2 and func_3
});

Categories

Resources