How can I execute callback after multiple Ajax requests complete? [duplicate] - javascript

This question already has answers here:
jQuery Deferred - waiting for multiple AJAX requests to finish [duplicate]
(3 answers)
Closed 6 years ago.
I'm trying to execute a callback after multiple jQuery Ajax have completed.
In my code both Ajax requests call another function and when I try to use these functions I get undefined.
I think the problem has to do with using deferred/promise, but I don't know how to use them.
Here is my code:
<link rel="stylesheet" type="text/css" href="https://tag/sites/ocean1/maker/captions/shared%20documents/Web_ComplianceCSS.txt">
<div id = "cabbage" style="font-size:10px">
<p>Web Compliance Stats</p>
</div>
<script type = "text/javascript">
var WebComplianceReportApp = {} || WebComplianceReportApp;
WebComplianceReportApp.GetStatuses = (function() {
var pub = {},
_userId,
_ultimateObjectHolderArr = [],
_items = [],
_options = {
listName: "M_Web_Compliance",
container: "#cabbage",
};
pub.init = function() {
var clientContext = new SP.ClientContext.get_current();
_userId = clientContext.get_web().get_currentUser();
clientContext.load(_userId);
clientContext.executeQueryAsync(getUserInfo, _onQueryFailed);
};
function getUserInfo() {
_userId = _userId.get_id();
getSpecifiedList(_options.listName, _userId);
}
function buildObject(results, listName) {
_items = results.d.results;
$.each(_items, function(index, item) {
_ultimateObjectHolderArr.push({
"Division": item.ParentOrg,
"ORG": item.ORG,
"URL": item.URL,
"Status": item.Site_Status
});
});
//createStatusView2(_ultimateObjectHolderArr);
}
function getSpecifiedList(listName, userId) {
var counter = 0;
var baseUrl = SP.PageContextInfo.get_webServerRelativeUrl() + "/_vti_bin/listdata.svc/" + listName;
var url1 = baseUrl + "?$select=ParentOrg,ORG,URL,Site_Status&$inlinecount=allpages";
var call1 = $.ajax({
url: url1,
type: "GET",
headers: {
"accept": "application/json;odata=verbose",
}
}).done(function(results) {
buildObject(results, listName);
}).fail(function(error) {
console.log("Error in getting List: " + listName);
$(_options.container).html("Error retrieving your " + listName + ". " + SP.PageContextInfo.get_webServerRelativeUrl());
});
var url2 = baseUrl + "?$select=ParentOrg,ORG,URL,Site_Status&$inlinecount=allpages&$skiptoken=1000";
var call2 = $.ajax({
url: url2,
type: "GET",
headers: {
"accept": "application/json;odata=verbose",
}
}).done(function(results) {
buildObject(results, listName);
}).fail(function(error) {
console.log("Error in getting List: " + listName);
$(_options.container).html("Error retrieving your " + listName + ". " + SP.PageContextInfo.get_webServerRelativeUrl());
});
}
function createStatusView2(Arr) {
var divisionArr = [];
var oRGArr = [];
var divisionCount = 0;
var oRGCount = 0;
for (var i = 0; i < Arr.length; i++) {
if ($.inArray(Arr[i].Division, divisionArr) === -1) {
divisionArr.push(Arr[i].Division);
var divisionHolderElement = $("<div id='p_" + Arr[i].Division + "' class='division_row_holder'></div>");
var divisionElement = $("<div id='" + Arr[i].Division + "' class='division_div ORG'></div>").text(Arr[i].Division);
$("#cabbage").append(divisionHolderElement);
$(divisionHolderElement).append(divisionElement);
}
if ($.inArray(Arr[i].ORG, oRGArr) === -1) {
oRGArr.push(Arr[i].ORG);
var orgElement = $("<div class='org_div ORG' id='" + Arr[i].ORG + "' style='font-size:10px;'></div>").text(Arr[i].ORG);
$("#p_" + Arr[i].Division).append(orgElement);
}
}
}
//automatically fired by init
function _onQueryFailed(sender, args) {
alert('Request failed.\nError: ' + args.get_message() + '\nStackTrace: ' + args.get_stackTrace());
}
return pub
}());
$(document).ready(function() {
SP.SOD.executeFunc('sp.js', 'SP.ClientContext', function() {
//After the SP scripts are run, we access the WebComplianceReportApp.GetStatuses
WebComplianceReportApp.GetStatuses.init();
});
});
</script>

I dont know if this will make your code dirty, but I would use a flag in this case
ex:
var ajaxCalls = 0;
function checkAjaxCalls()
{
if (ajaxCalls == 2)
{
//do your thing...
//and maybe you want to reset ajaxCalls value to zero if needed...
}
}
And from each Ajax response completes, increment ajaxCalls variable by one, and call the checkAjaxCalls function from both your Ajax responses.

Method One:
This time we'll have waited for the request to complete instead of waiting for the request to succeed
$(".ajax-form-button-thingy").on("click", function() {
$.ajax({
url: $(this).attr("href"),
type: 'GET',
error: function() {
throw new Error("Oh no, something went wrong :(");
},
complete: function(response) {
$(".ajax-form-response-place").html(response);
}
});
});
Method Two:
If you want to wait for ALL Ajax requests to complete without changing the async option to false then you might be looking for jQuery.ajaxComplete();
In jQuery every time an Ajax request completes the jQuery.ajaxComplete(); event is triggered.
Here is a simple example but there is more info on jQuery.ajaxComplete(); over here.
$(document).ajaxComplete(function(event, request, settings) {
$(".message").html("<div class='alert alert-info'>Request Complete.</div>");
});
Also you can take a look at the Ajax response by using request.responseText this might be useful in case you want to double check the response.
For more information about jQuery.ajax you can read the docs here

You could call createStatusView(); and then call createStatusView2(); after all of your Ajax requests are done
$(document).ready(function(){
createStatusView();
$(this).ajaxStop(function() {
// NOTE: I did not see you use createStatusView(); in your code
createStatusView2();
});
});

Related

Accessing the Forge Viewer From Two HTML Files

I have been working on a website incorporating the autodesk-forge viewer (more details can be seen on my past questions). I have successfully made many autodesk-forge viewer functions in a standard javascript (.js) file. These functions include displaying the viewer, and isolating to a particular part, when an external button is pressed.
Currently I have a main html/php home page where I have included my javascript file with all my forge functions using <script src="MyForgeFunctions.js"></script>
These functions are accessed through a button, which successfully displays the viewer in the html page. Attached to my main php/html page, another html/php page was added through an iframe html reference (<iframe src="URL.php"></iframe>). My home page displays the main machines we make, while the embedded php/html page displays all the stations within the machine. I have also included the MyForgeFunctions.js inside this second php/html page. Because of the way the website is set up, I need to be able to access the viewer in both web pages. However, when I attempt to access the viewer from the second html page, I get a message that the viewer is undefined. Below is my code from MyForgeFunctions.js.
var ext = '';
var dim = '';
var assemblyname = '';
function getAssemblyName(){
assemblyname = sessionStorage.getItem("assemblyName");
//var ext = partname.substr(partname.lastIndexOf('.'));
ext = assemblyname.split('.');
dim = ext[0] + ':1';
console.log(assemblyname);
console.log(dim);
if (dim !== ''){
isolateSelected();
}
}
//function to get part name from __MachineParts.php
var partname = '';
var extension = '';
var namewithoutextension = '';
function getPartName(){
partname = sessionStorage.getItem("partName");
//var ext = partname.substr(partname.lastIndexOf('.'));
extension = partname.split('.');
namewithoutextension = extension[0] + ':1'
console.log(partname);
console.log(namewithoutextension);
if (namewithoutextension !== ''){
isolateSelectedPart();
}
}
/*******************************************************************************
*
* AUTODESK FORGE VIEWER CODE (HTTP REQUESTS)
*
*******************************************************************************/
//VARIABLE DECLARATION
var code = '';
var access_token = '';
const hub = 'xxxxxxxxxxxxxxxxxxxxxxxxxxx';
const project ='xxxxxxxxxxxxxxxxxxxxxxxxxxx';
const folder='xxxxxxxxxxxxxxxxxxxxxxxxx';
const item = 'xxxxxxxxxxxxxxxxxxxxxxxxx';
var itemid = '';
var urn = '';
var urn2 = '';
//allow the program to view data from autodesk
function authorize(){
window.location.href = "https://developer.api.autodesk.com/authentication/v1/authorize?response_type=code&client_id=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx&redirect_uri=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx&scope=data:read data:write bucket:read viewables:read bucket:create data:create";
}
//grab the code from the url
function getCode(){
const querystring = window.location.search;
// console.log(querystring);
const urlParams = new URLSearchParams(querystring);
code = urlParams.get('code');
// console.log(code);
}
//call the function to get the code right away, and obtain a token
getCode();
getToken();
//function to obtain access token
function getToken(){
$.ajax({
method: 'POST',
url: 'https://developer.api.autodesk.com/authentication/v1/gettoken',
headers: {
'Content-Type':'application/x-www-form-urlencoded'
},
data:'client_id=dm2VLfnwJ6rYHKPAg7dG6l9yVbBQPGlH&client_secret=HRMpOPusLhsVoIMk&grant_type=authorization_code&code=' + code + '&redirect_uri=http://team/__MachineViewerMV.php',
success:function(response){
// console.log(response);
access_token = response.access_token;
console.log(access_token);
}
})
}
//Grab desired file id from project folder
function getItem(){
$.ajax({
method:'GET',
url: 'https://developer.api.autodesk.com/data/v1/projects/' + project + '/folders/' + item + '/contents',
headers:{
Authorization:'Bearer ' + access_token
},
/* beforeSend:function(before){
if(access_token !== '' && viewer !==''){
destroyViewer();}
},*/
success:function(response){
//console.log(response);
// folder = response.data[0].id;
// console.log(folder);
// itemid = response.data[0].id;
//console.log(itemid);
console.log(response);
for (var i = 0; i<response.data.length; i++){
//console.log(response.data[i].attributes.displayName);
if(response.data[i].attributes.displayName == fileName){
//console.log('hooray');
itemid = response.data[i].id;
console.log(itemid);
getVersion();
break;
}
else if (response.data[i].attributes.displayName !== fileName){
itemid = '';
}
}
},
error:function(error){
authorize();
}
})
}
function get2dItem(){
$.ajax({
method:'GET',
url: 'https://developer.api.autodesk.com/data/v1/projects/' + project + '/folders/' + item + '/contents',
headers:{
Authorization:'Bearer ' + access_token
},
/*beforeSend:function(before){
if(access_token !== '' && viewer !== ''){
destroyViewer();}
},*/
success:function(response){
//console.log(response);
// folder = response.data[0].id;
// console.log(folder);
// itemid = response.data[0].id;
//console.log(itemid);
console.log(response);
for (var i = 0; i<response.data.length; i++){
//console.log(response.data[i].attributes.displayName);
if(response.data[i].attributes.displayName == fileName2d){
//console.log('hooray');
itemid = response.data[i].id;
console.log(itemid);
getVersion();
break;
}
else if (response.data[i].attributes.displayName !== fileName2d){
itemid = '';
}
}
},
error:function(error){
authorize();
}
})
}
//get version of the file using its id
function getVersion(){
$.ajax({
method:'GET',
url: 'https://developer.api.autodesk.com/data/v1/projects/' + project + '/items/' + itemid + '/versions',
headers:{
Authorization:'Bearer ' + access_token
},
success:function(response){
//console.log(response);
urn = btoa(response.data[0].relationships.storage.data.id);
console.log(urn);
translateToSVF();
}
})
}
function translateToSVF(){
$.ajax({
method: 'POST',
url:"https://developer.api.autodesk.com/modelderivative/v2/designdata/job",
headers:{
"content-type": "application/json",
Authorization: "Bearer " + access_token
},
data:JSON.stringify({
"input":{ "urn":urn
},
"output": {
"formats": [
{
"type": "svf",
"views": [
"2d",
"3d"
]
}
]
}
}),
success:function(response){
// console.log(response);
urn2 = response.urn;
console.log(urn2);
checkStatus();
}
})
}
function checkStatus(){
$.ajax({
method: 'GET',
url: "https://developer.api.autodesk.com/modelderivative/v2/designdata/" + urn2 + "/manifest",
headers:{
Authorization: "Bearer " + access_token
},
success: function(response){
console.log(response);
if (response.progress == 'complete'){
displayViewer();
}
else if (response.progress !== 'complete'){
alert('File Still Uploading, Press the Display Button Again!');
}
}
})
}
//function to get list of viewables\
var guid = '';
function getViewable(){
$.ajax({
method:'GET',
headers:{
Authorization: "Bearer " + access_token
},
url: 'https://developer.api.autodesk.com/modelderivative/v2/designdata/' + urn2 + '/metadata',
success:function(response){
console.log(response);
guid = response.data.metadata[0].guid;
console.log(guid);
}
})
}
//funciton to get the list of items within a model
function getTree(){
$.ajax({
method: 'GET',
headers:{
Authorization: "Bearer " + access_token
},
url:'https://developer.api.autodesk.com/modelderivative/v2/designdata/' + urn2 + '/metadata/' + guid + '/properties',
success:function(response){
console.log(response);
}
})
}
/**********************************************************************************
*
* FUNCTION TO DISPLAY THE VIEWER IN THE HTML PAGE
*
**********************************************************************************/
var viewer;
function displayViewer(){
//var viewer;
var options = {
env: 'AutodeskProduction',
api: 'derivativeV2', // for models uploaded to EMEA change this option to 'derivativeV2_EU'
getAccessToken: function(onTokenReady) {
var token = access_token;
console.log(token);
var timeInSeconds = 3600; // Use value provided by Forge Authentication (OAuth) API
onTokenReady(token, timeInSeconds);
}
};
Autodesk.Viewing.Initializer(options, function() {
var htmlDiv = document.getElementById('forgeViewer');
viewer = new Autodesk.Viewing.Private.GuiViewer3D(htmlDiv);
var startedCode = viewer.start();
// sessionStorage.setItem("viewer", viewer);
if (startedCode > 0) {
console.error('Failed to create a Viewer: WebGL not supported.');
return;
}
console.log('Initialization complete, loading a model next...');
});
var documentId = 'urn:'+urn2;
Autodesk.Viewing.Document.load(documentId, onDocumentLoadSuccess, onDocumentLoadFailure);
function onDocumentLoadSuccess(viewerDocument) {
var defaultModel = viewerDocument.getRoot().getDefaultGeometry();
viewer.loadDocumentNode(viewerDocument, defaultModel);
console.log(viewer);
}
function onDocumentLoadFailure() {
console.error('Failed fetching Forge manifest');
}
}
//function to hide the viewer
function destroyViewer(){
console.log(viewer);
viewer.finish();
viewer = null;
Autodesk.Viewing.shutdown();
}
/*****************************************************************************
* FUNCTIONS TO MODIFY THE VIEWER TO ZOOM INTO THE CORRECT PART/ASSEMBLY
*/
function isolateSelected(){
console.log(dim);
console.log(viewer);
viewer.search(dim, function(dbIds) {
// viewer.search('"' + 'M-109408 FOLDING PLOUGH:2' + '"', function(dbIds) {
console.log(dbIds.length);
getSubset(dbIds, 'label', dim, function(dbIds) {
// getSubset(dbIds, 'label', 'M-109408 FOLDING PLOUGH:2', function(dbIds) {
// getSubset(dbIds, property.name, 'M-54439 POST TUBING:1', function(dbIds) {
//getSubset(dbIds, property.name, property.value, function(dbIds){
var it = viewer.model.getData().instanceTree;
//console.log(it);
for (i = 0; i<dbIds.length; i++){
var namepart = it.getNodeName(dbIds[i]);
if (namepart !== undefined){
console.log(dbIds);
console.log(namepart);}}
/* for (i = 121; i<381;i++){
var dbId = i;
var it = NOP_VIEWER.model.getData().instanceTree;
var name = it.getNodeName(dbId);
console.log(name);}*/
viewer.isolate(dbIds)
viewer.select(dbIds);
viewer.utilities.fitToView();
})
}, function(error) {})
}
function isolateSelectedPart(){
console.log(namewithoutextension);
viewer.search(namewithoutextension, function(dbIds) {
// viewer.search('"' + 'M-109408 FOLDING PLOUGH:2' + '"', function(dbIds) {
console.log(dbIds.length);
getSubset(dbIds, 'label', namewithoutextension, function(dbIds) {
// getSubset(dbIds, 'label', 'M-109408 FOLDING PLOUGH:2', function(dbIds) {
// getSubset(dbIds, property.name, 'M-54439 POST TUBING:1', function(dbIds) {
//getSubset(dbIds, property.name, property.value, function(dbIds){
var it = viewer.model.getData().instanceTree;
//console.log(it);
for (i = 0; i<dbIds.length; i++){
var namepart = it.getNodeName(dbIds[i]);
if (namepart !== undefined){
console.log(dbIds);
console.log(namepart);}}
/* for (i = 121; i<381;i++){
var dbId = i;
var it = NOP_VIEWER.model.getData().instanceTree;
var name = it.getNodeName(dbId);
console.log(name);}*/
viewer.isolate(dbIds)
viewer.select(dbIds);
viewer.utilities.fitToView();
})
}, function(error) {})
}
//function to find the dbid of the part/assembly
function getSubset(dbIds, name, value, callback) {
console.log("getSubset, dbIds.length before = " + dbIds.length)
viewer.model.getBulkProperties(dbIds, {
propFilter: [name],
ignoreHidden: true
}, function(data) {
var newDbIds = []
for (var key in data) {
var item = data[key]
// console.log(item.properties);
if (item.properties[0].displayValue === value) {
newDbIds.push(item.dbId)
}
}
console.log("getSubset, dbIds.length after = " + newDbIds.length)
callback(newDbIds)
}, function(error) {})
}
Because of how the webpage is set up, when I needed to use a variable from the second web page in the first, I used sessionStorage.getItem and sessionStorage.setItem. I have also made a simple function as so inside MyForgeFunctions.js:
function checkViewer(){
console.log(viewer);
}
I then included a button in both html pages to execute the function with an onclick event. When the function is run from the first/home html page the following is displayed:
T {globalManager: e, clientContainer: div#forgeViewer, container: div.adsk-viewing-viewer.notouch.dark-theme.quality-text, config: {…}, contextMenu: o, …}. Which is normal for the viewer, but when the function is executed from the second html page, the viewer is undefined. Any help as to why this is happening or any solutions will be greatly appreciated. Cheers!
From the iframe, in order to access the viewer inside the main web page, I had to use (parent.viewer).

How to send data from javascript function to Django View

I am trying to send data from a javascript function that generates a random string upon the page loading to a Django view. I don't know how to structure the script tag to send the data after the page has loaded and the views.py to receive the data. I am new to javascript and don't quite know how to go about this. I appreciate any help provided.
index.html
<script>
function makeid(length) {
var result = '';
var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
var charactersLength = characters.length;
for ( var i = 0; i < length; i++ ) {
result += characters.charAt(Math.floor(Math.random() * charactersLength));
}
return result;
}
console.log(makeid(9));
</script>
You can use ajax to send data to Django view like following code.
javascript:
function makeid(length) {
var result = '';
var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
var charactersLength = characters.length;
for ( var i = 0; i < length; i++ ) {
result += characters.charAt(Math.floor(Math.random() * charactersLength));
}
$.ajax({
type: "GET",
url: '/my_def_in_view',
data: {
"result": result,
},
dataType: "json",
success: function (data) {
// any process in data
alert("successfull")
},
failure: function () {
alert("failure");
}
});
}
urls.py:
urlpatterns = [
url(r'^my_def_in_view$', views.my_def_in_view, name='my_def_in_view'),
...
]
views.py:
def my_def_in_view(request):
result = request.GET.get('result', None)
# Any process that you want
data = {
# Data that you want to send to javascript function
}
return JsonResponse(data)
If it was successfull it goes back to "success" part.
you can do that in two ways:
Tradicional with ajax
Websockets: With django channels
If you want to send a bit of information, an ajax request is enough, you have to set and address and a view to receive the POST or GET ajax request.
I recommend to you use pure JS, not jquery
For example, this is a call to refresh a captcha image....
/*Agregar boton refresh al lado del campo input*/
let captcha_field =
document.getElementById('captcha-field-registro_1').parentNode;
let refresh_button=document.createElement('BUTTON');
refresh_button.addEventListener('click',refresh_captcha)
refresh_button.innerHTML = "Refrescar Captcha"; // Insert text
captcha_field.appendChild(refresh_button);
let url_captcha= location.protocol + "//" +
window.location.hostname + ":" +
location.port + "/captcha/refresh/";
let id_captcha_0="captcha-field-registro_0"
function refresh_captcha(){
let xhr = new XMLHttpRequest();
xhr.open('GET', url_captcha, true);
xhr.onload = function recv_captcha_load(event){
console.log("event received", event,
"state",xhr.readyState);
let data_txt = xhr.responseText;
let data_json = JSON.parse(data_txt);
console.log("Data json", data_json);
if (xhr.readyState==4){
if (xhr.status==200){
console.log("LOAD Se ha recibido esta información", event);
let captcha_img=document.getElementsByClassName('captcha')[0];
console.log("Catpcha img dom", captcha_img);
captcha_img.setAttribute('src', data_json['image_url'])
document.getElementById(id_captcha_0).value=data_json['key']
}
else{
console.log("Error al recibir")
}
}
};
var csrftoken = getCookie('csrftoken');
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xhr.setRequestHeader("X-CSRFToken", csrftoken);
xhr.send();
}
function getCookie(name) {
let cookieValue = null;
if (document.cookie && document.cookie !== '') {
var cookies = document.cookie.split(';');
for (let i = 0; i < cookies.length; i++) {
let cookie = cookies[i].trim();
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) === (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}

Converting array variable back to string for ajax post

Someone helped me with this yesterday but it's now messed up how I send a string query to my endpoint in the AJAX call.
Functionally, this script works but by converting searchResult to an array, it screwed up my ajax call and what I send as a string query to an endpoint.
How can I modify this to make sure it sends searchResult as a string again to my ajax?
$('#productInput').on('input', function () {
let _this = $(this);
let foundOption;
let searchResult = [];
let optSelector = `option[value='${_this.val()}']`;
if (_this.val() === '') {
return;
} else if ((foundOption = $('#returnedProducts').find(optSelector)).length) {
$("#groupName").val(searchResult[$(foundOption).attr('srindex')]._source);
$("#groupNum").val(searchResult[$(foundOption).attr('srindex')]._source);
} else {
$.ajax({ url: '/account/autocomplete',
data: {
search_result: searchResult
},
"_token": "{{ csrf_token() }}",
type: "POST",
success: function (response) {
console.log(response);
let searchResult = response.hits.hits;
console.log(searchResult);
$("#returnedProducts").empty();
for(let i = 0; i < response.hits.hits.length; i++) {
$("#returnedProducts").append("<option value=" + searchResult[i]._source.category + ">" + searchResult[i]._source.category + "</option>");
}
}
});
}
});

Render issue with Angular

I'm facing a problem I cannot get my head around. Server side I generate HTML code using Node.JS and JADE:
table#login-table.table.condensed
tbody
tr(ng-repeat="item in dailyTodoItems")
td
input(name="dailyTask", type="checkbox", ng-model="item.done", ng-change="todoChecked('{{item.id}}', '{{item.done}}')")
td {{item.description}}
td
a(href="" ng-click="dailyTodoRemoveTask('{{item.id}}')") d
If you see line 5 (Input field) and the last line (a(href...) I use the same way to bind my items with Angular. The problem is that one works the other ( a(href... ) does not.
As you can see I call two JS functions:
$scope.todoChecked = function(id, done) {
alert('change = ' + id);
};
$scope.dailyTodoRemoveTask = function(id) {
alert('remove = ' + id);
};
todoChecked() returns the ID as it should but
dailyTodoRemoveTask() returns: {{item.id}}
The really strange thing is the when I inspect the code i the browser id do not see {{item.id}} but the correct ID for both places.
Any help will be appreciated. Below you see the full client JS code:
$( document ).ready(function() {
var messages = [];
var socket = io.connect('http://localhost:3000');
var field = document.getElementById("field");
var sendButton = document.getElementById("send");
var content = document.getElementById("content");
socket.on('history', function (data) {
if(data.message) {
messages.push(data.message);
var html = '';
for(var i=0; i<messages.length; i++) {
html += messages[i] + '<br />';
}
content.innerHTML = html;
} else {
console.log("There is a problem:", data);
}
});
sendButton.onclick = function() {
var text = field.value;
socket.emit('send', { message: text, token: token });
};
socket.emit('send', { message: "Login: " + token });
});
//
// Allegro
//
var AllegroApp = angular.module('Allegro', []);
AllegroApp.controller('dailyTodoController', function($scope, $http) {
// Model
$scope.dailyTodoItems = [];
$scope.newDailyTodoItem = '';
// Load daily todo items
$http({
method: 'POST',
url: "/todo/get/12",
data: {tkn: token}
}).success(function(data, status) {
// Push the data to the Model
for (var i = 0; i < data.result.length; i++) {
$scope.dailyTodoItems.push({
description: data.result[i].task,
done: data.result[i].done,
id: data.result[i]._id
});
}
}).error(function(data, status) {
// TODO handle error gracefully
alert('Technical error: Could not save new daily todo task. Please try again :-( ');
});
// Events
$scope.addDailyTodoItem = function() {
// Check for empty input
if ($scope.newDailyTodoItem.length < 1) { return; }
// Update the database
$http({
method: 'POST',
url: "/todo/new/" + $scope.newDailyTodoItem,
data: {tkn: token}
}).success(function(data, status) {
// Push the data to the Model
$scope.dailyTodoItems.push({
description: $scope.newDailyTodoItem,
done: false,
id: data.id
});
}).error(function(data, status) {
// TODO handle error gracefully
alert('Technical error: Could not save new daily todo task. Please try again :-( ');
});
};
$scope.todoChecked = function(id, done) {
alert('change = ' + id);
if (done == 'true') { var newStatus = 'false' } else newStatus = 'true';
$http({
method: 'POST',
url: '/todo/update/' + id + '/' + newStatus,
data: {tkn: token}
}).success(function(data, status) {
// UI already updated. No need to do anything
}).error(function(data, status) {
// TODO handle error gracefully
alert('Technical error: Could not update task status. Please try again :-( ');
});
};
$scope.dailyTodoRemoveTask = function(id) {
alert('remove = ' + id);
};
$scope.todoLoadTodaysTasks = function() {
};
});
Usually you dont't have to interpolated model values inside directive. Please check this code.
table#login-table.table.condensed
tbody
tr(ng-repeat="item in dailyTodoItems")
td
input(name="dailyTask", type="checkbox", ng-model="item.done", ng-change="todoChecked(item.id, item.done)")
td {{item.description}}
td
a(href="" ng-click="dailyTodoRemoveTask(item.id)") d

Multiple Javascript functions, need confirm dialog before executing any

I have three separate javascript/jquery functions, all of which fire off after the user clicks a button. One function posts to a form handler. Another function creates a new tab. And the third function grabs the id of the new tab and posts sends new information into the tab via an ajax call. They all work together and depend on one another.
I have tried many different configurations, and I cannot figure out how to properly get a confirmation dialog (e.g., "Do you want to perform this action?) to work with all three of these simultaneously. If the user clicks "yes," the process should fire. If the user clicks "no," the process should die. Any help is greatly appreciated.
Edit: I've posted my code below. I'm sure it's really noobish, which is why I didn't post it the begin with. Trying to learn though. Thanks!
jQuery(".update_form").click(function(e) { // changed
e.preventDefault();
jQuery.ajax({
type: "POST",
url: "/eemcontrolpanel/process.cshtml",
data: jQuery(this).parent().serialize() // changed
});
return false; // avoid to execute the actual submit of the form.
});
jQuery(".update_form").click(function () {
var form = jQuery(this).parents('form:first');
title = jQuery("input[name='process']", form).val();
$('#tt').tabs('add',{
title:title,
content:'Script starting',
closable:true
});
$('div.panel-body:last').attr("id","tab" + panelIds[panelIds.length - 1] + 1);
panelIds.push(panelIds[panelIds.length - 1] + 1);
});
jQuery(".update_form").click(function (e) {
e.preventDefault();
//var j = jQuery.noConflict();
var form = jQuery(this).parents('form:first');
var fileName = jQuery("input[name='process']", form).val();
jQuery(document).ready(function () {
var XHR;
var stopMe = 1;
var isSame = 0;
var oldhtml;
var tabID = "tab" + panelIds[panelIds.length - 1];
jQuery("#"+ tabID).everyTime(1000, function (i) {
if (stopMe != 2){
XHR = jQuery.ajax({
url: "/eemcontrolpanel/jobs/" + fileName + ".txt",
cache: false,
success: function (html){
if (html === oldhtml){
isSame++;
if (isSame === 10){
stopMe = 2;
}
}
jQuery("#"+ tabID).html("<pre>" + html + "</pre>").scrollHeight;
oldhtml = html;
}
});
} else {
jQuery("#"+ tabID).stopTime();
}
jQuery("#"+ tabID).css({ color: "white" });
});
});
});
This is what I ended up doing. I basically combined all the functions into one big function.
var panelIds = new Array();
panelIds.push('0');
jQuery(".update_form").click(function (e) {
if (confirm('Are you sure?')) {
e.preventDefault();
jQuery.ajax({
type: "POST",
url: "/eemcontrolpanel/process.cshtml",
data: jQuery(this).parent().serialize() // changed
});
var form = jQuery(this).parents('form:first');
var title = jQuery("input[name='process']", form).val();
$('#tt').tabs('add',{
title:title,
content:'Script starting',
closable:true
});
$('div.panel-body:last').attr("id","tab" + panelIds[panelIds.length - 1] + 1);
panelIds.push(panelIds[panelIds.length - 1] + 1);
//var j = jQuery.noConflict();
var fileName = jQuery("input[name='process']", form).val();
var XHR;
var stopMe = 1;
var isSame = 0;
var oldhtml;
var tabID = "tab" + panelIds[panelIds.length - 1];
//alert(tabID);
jQuery("#"+ tabID).everyTime(1000, function (i) {
//alert(stopMe);
//add also if stopme=false else quit/end/whatever
if (stopMe != 2){
//alert(stopMe);
XHR = jQuery.ajax({
url: "/eemcontrolpanel/jobs/" + fileName + ".txt",
cache: false,
success: function (html){
//alert(html);
if (html === oldhtml){
isSame++;
//alert(isSame);
if (isSame === 10){
stopMe = 2;
//alert(stopMe);
}
}
jQuery("#"+ tabID).html("<pre>" + html + "</pre>").scrollHeight;
oldhtml = html;
//alert(oldhtml);
}
});
} else {
jQuery("#"+ tabID).stopTime();
}
jQuery("#"+ tabID).css({ color: "white" });
});
} else {
return false;
}
});
Have you tried this:
Function onButtonPush(){
if(confirm('confirm message')){
function1();
function2();
function3();
}
}

Categories