I have been looking at converting a web app to an Electron desktop app. I am starting an http server in main.js to handle ajax requests from my app. I've created a button and defined its onclick function to call an ajax function and then update another element when the response arrives, e.g. $('#message').text('whatever'). This all works but the element ('#message') is not completely refreshed - I see the new text on top of the old text. If I click somewhere in the window the element is refreshed properly. I've tried calling blur() on the element and setting the focus to another element, but none of that helps.
Why does the BrowserWindow not erase the element's old text when I update it via jQuery, and how can I fix it?
Thanks in advance for your help!
Additional details
Here is the code that is called when the "Test" button is clicked.
function test_webapi() {
var url = 'http://localhost:8888/time';
console.log("Sending request: " + url);
$.ajax({
cache: false,
method: 'GET',
url: url,
error: function(xhr, status, err) { console.log("Ajax error from " + url + ": " + err); },
success: function(data) {
console.log("Have response from " + url, data);
$('#message').text(data.Data.Time);
}
})
}
And the code that sets up the http server and handles the ajax request.
var port = 8888;
var server = http.createServer(handle_time_request);
server.listen(port, function() {
console.log("API server listening on port " + port);
});
function handle_time_request(req, res) {
var tval = moment(new Date()).format('YYYY-MM-DD hh:mm:ss');
var reply = {
Success: true,
Message: "whatever",
Data: { Time: tval }
};
res.writeHead(200, {"Content-Type": "application/json"});
res.end(JSON.stringify(reply, null, 4));
}
Related
I want to append one more param at the end of the current url if the ajax call returns successfully. In this context, we can get back the identifier of the object has been persisted into the database, then append this identifier to the url.
The problem is curationNotes of data was lost if the line window.history.pushState({}, null, newHref); is uncommented. It means we cannot get 'params.curationNotes' in controller. The params.curationNotes, which is a map of user provided values on the form, is null when we try to parse it inside the controller.
Below is the snippet I am working on.
$('#btnSave').on("click", function(event) {
if ($('#curationNotesForm')[0].checkValidity()) {
var curationNotes = buildCurationNotesTC();
"use strict";
event.preventDefault();
$.ajax({
dataType: "text",
type: "POST",
url: $.jummp.createLink("curationNotes", "doAddOrUpdate"),
cache: true,
data: {
curationNotes: curationNotes,
model: "${id}"
},
processData: true,
async: true,
beforeSend: function() {
$('#txtStatus').text("The curation notes are being saved. Please wait...");
},
success: function(response) {
var response = JSON.parse(response);
var href = window.location.href;
if (href.indexOf("&cnId=") < 0) {
var newHref = href + "&cnId=" + response['cnId'];
//window.history.pushState({}, null, newHref);
}
$('#txtStatus').text(response['message']);
},
error: function(jqXHR, textStatus, errorThrown) {
// TODO: the error message doesn't show properly
$('#txtStatus').text("Error: ", jqXHR.responseText + textStatus + errorThrown + JSON.stringify(jqXHR));
}
});
} else {
$('#txtStatus').text("Please check required fields and click Save button again...");
}
});
If I comment this line window.history.pushState({}, null, newHref);, the code is working properly.
Notes: this snippet works fine in any web browsers on Linux but cannot work in any web browser of Windows 10. That's actually ridiculous to me.
Have you ever had any experience with this problem?
I am struggeling with the KendoUI tooltip helper. Currently I am doing the following to get some tooltip information on a grid row:
$("#grid").kendoTooltip({
filter: 'td:nth-child(10)',
content: function (e) {
var template = kendo.template($("#myToolTipTemplate").html());
var dataItem = $("#grid").data("kendoGrid").dataItem(e.target.closest("tr"));
var tooltipHtml;
$.ajax({
url: DetailsURL + "/" + dataItem.Id,
async: false
}).done(function (data) { // data.Result is a JSON object from the server with details for the row
if (data.Success) {
data.Result = data.Result.replace(/null/g, "\"N/A\"");
tooltipHtml = template($.parseJSON(data.Result));
} else {
tooltipHtml = "Ooops!<br>Something went wrong (" + data.Result + ")";
}
});
return tooltipHtml;
}
});
I would like to get rid of the synchronous ajax call and make it asynchronous. I saw some asynchronous examples where the server delivers the full html, but nothing that works with JSON data from the server, that is then "compiled" via a kendo.template() to html on the client. Any suggestions how to do this?
Set the content of the tooltip to be a placeholder value (e.g.
"Loading..")
Listen for the "Show" event of the tooltip.
When the show event is triggered, start the request for JSON from the server
In the 'done' callback, execute the template, and replace the content of the tooltip with the new html in the 'done' callback
$("#ID").data("kendoTooltip").popup.wrapper.find(".k-tooltip-content").html("........");
Telerik helped me here. And, as often, it's easier than guessed..
$("#grid").kendoTooltip({
filter: 'td:nth-child(10)',
content: function (e) {
var template = kendo.template($("#myToolTipTemplate").html());
var dataItem = $("#grid").data("kendoGrid").dataItem(e.target.closest("tr"));
var tooltipHtml;
$.ajax({
url: DetailsURL + "/" + dataItem.Id,
async: false
}).done(function (data) { // data.Result is a JSON object from the server with details for the row
if (data.Success) {
data.Result = data.Result.replace(/null/g, "\"N/A\"");
tooltipHtml = template($.parseJSON(data.Result));
} else {
tooltipHtml = "Ooops!<br>Something went wrong (" + data.Result + ")";
}
// set tooltip content here (done callback of the ajax req)
e.sender.content.html(tooltipHtml);
});
}
});
Trying out office-js-helpers instead of ADAL to authenticate and fetching data. I have followed instructions from github.com/OfficeDev/office-js-helpers and other similar questions here at stackoverflow.
This is the code - first from Office-initialize:
Office.initialize = function (reason) {
if (OfficeHelpers.Authenticator.isAuthDialog()) {
return;
}
authenticator = new OfficeHelpers.Authenticator();
// Register Microsoft endpoint by overriding default values
authenticator.endpoints.registerAzureADAuth(
azureADClientID, //clientId
// baseUrl,
'xxxxxxxxxx.onmicrosoft.com', // tenant
{
responseType: 'token',
scope: 'user',
redirectUrl: 'https://xxxxxxxxxx.azurewebsites.net/'
}
);
And the AJAX call that is connected to a button to retrieve info:
function getDataFromSelection() {
authenticator
.authenticate(OfficeHelpers.DefaultEndpoints.AzureAD)
.then(function (token) {
var url = "https://graph.microsoft.com/v1.0/me";
var html = "<ul>";
var response;
console.log("token: ", token);
// app.showNotification("token: ", JSON.stringify(token));
$.ajax({
// beforeSend: function (request) {
// request.setRequestHeader("Accept", "application/json");
// },
type: "GET",
url: url,
dataType: "json",
headers: {
'Authorization': 'Bearer ' + token.access_token,
}
}).done(function (response) {
html += getPropertyHtml("Namn", response.displayName);
html += getPropertyHtml("Titel", response.jobTitle);
html += getPropertyHtml("Avdelning", response.officeLocation);
// html += getPropertyHtml("Telefon jobb", response.businessPhones);
$("#results").html(html);
}).fail(function (response) {
app.showNotification('Error: ' + JSON.stringify(error));
app.showNotification('Inloggningen slutade att fungera!', 'Du får logga ut och prova att logga in igen'); //response.responseText
}).always(function () {
console.log("AJAX is done!!");
}).then(function (response) {
postDataToContentControlers(response);
})
});
}
Getting different errors regarding webbrowser:
Google Chrome:
I click the button and then get asked to approve to open a new window. I aprove it and it opens dialogwindow and goes to first login.microsoftonline.com and the to the addin, and then Closes the window. I get the data but in console I get errors:
I have included a function to be exetuced when I hit the button to populate contentControls called postDataToContentControlers(response);
Have to klick it twise to populate contencControls. At first klick I get this error:
Seems to be an Async-problem?
SOLVED: Well this was quiet simple to solve. Just moved the function into
$(document.ready(function() {}
Well on to the next webbrowser - Egde.
Here we get the same procedure as chrome exept that it doesnt Close the dialog and I don't get any data.
EDIT: This is still an isue but on older EDGE versions it is NOT an issue.
Microsoft edge 20.10240.16384.0
On that version it actually close the dialog and returns to addin were you now is logged in and retrieves the data.
Run by virtualBox were I have a Windows10 with an older edge =)
On desktop Word it works as expected =)
ON Explorer 11 similar problem as on edge
Is there anyone that have had similar problems or recognize some of it?
Hope to get some answers - thanks =)
I'm actually working on a special login page to redirect to that then close the dialog. Good or not? How to do?
I would like use PhantomJS with highcharts for generate a report. But for my chart, my data are in SQL database. Normally, for generating my chart I use ajax request with a file query.cfc (coldfusion) and my chart works. But with PhantomJS, if I add a function with my ajax request, I have an error in callback - error 404 but I don't no why. It's the same function what I use for my simple chart.
I launch PhantomJS with: phantomjs --web-security=no test.js
var system = require('system');
var page = require('webpage').create();
var fs = require('fs');
// load JS libraries
page.injectJs("jquery-2.1.1.js");
page.injectJs("highcharts.js");
page.injectJs("exporting.js");
// chart demo
var args = {
width: 600,
height: 500
};
page.onConsoleMessage = function(msg) {
console.log(msg);
};
page.includeJs("http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js", function() {
var svg = page.evaluate(function(opt) {
$('body').prepend('<div id="container"></div>');
function test() {
$.ajax({
type: "POST",
async: false,
url: "query3.cfc?method=test",
data: {
'arg1': 'aee',
'arg2': 'ss'
},
success: function(year) {
var lim_annee = jQuery.parseJSON(year);
console.log('success');
},
error: function(jqXHR, exception) {
console.log('erreur ' + jqXHR.status);
console.log('erreur2 ' + exception);
}
});
};
//chart Code
return chart.getSVG();
}, args);
page.render('img.jpeg', {
format: 'jpeg',
quality: '100'
});
phantom.exit()
});
If you don't open a page in PhantomJS, it will stay at "about:blank" and "about:blank/query3.cfc?method=test" doesn't seem like a correct URL. Either use a correct URL to your ColdFusion server:
url: "http://localhost:port/query3.cfc?method=test",
or initialize the base domain in PhantomJS before doing anything else:
page.setContent("", "http://localhost:port/");
Remember that if you were to open simple local HTML files, you would need to use the "file://" protocol and remove any query string.
Also, loading multiple jQuery versions might break your script.
I have a Html file locally with the following code
<h1>This is session token </h1>
<div id="noob"></div>
<script src="http://code.jquery.com/jquery-1.9.1.min.js" type="text/javascript"></script>
<script>
$(document).ready(function(){
var sessiontoken;
var randomUser = Math.round(Math.random() * 1000000);
var supportCors = $.support.cors;
var sessiontoken ;
$.support.cors = true;
$.ajax({
type: 'POST',
url: "https://abc.com/Gateway.Session/Session",
dataType: "json",
data: {
UserId: "TestUser" + randomUser,
CSK1: "abc",
CustId: "cde"
},
success: function (data) {
$.support.cors = supportCors;
sessiontoken=data.Token;
alert(sessiontoken);
document.getElementById('noob').innerHTML = sessiontoken;
},
error: function (xhr, textStatus, error) {
$.support.cors = supportCors;
alert("responseText: " + xhr.responseText);
alert("XHR statusText: " + xhr.statusText);
alert("textStatus: " + textStatus);
alert("error: " + error.message);
}
});
});
</script>
This code when run locally(ex: c:/development/mypage.html) is generating session token after enabling the pop-up 'allow running javascript' " of IE7.
i.e., ajax function in above javascript is returning 'success'
when run locally and session token is generated.
But when this code is deployed in server and opened in IE7 like (http:// localhost:8080/mypage.html), here ajax function of above script is returning 'error'.
As when we run the file locally we enabled the pop-up to allow running script.
But when the file is deployed in server we won't get such pop-up as javascript runs itself when a html page is accessed from server.
I am unable to figure out why control going to 'error' part o 'success' when we file from server
So how can i make this ajax function to return to 'success' part when accessed from server.
The file executes fine in chrome when accessed locally or from server.Now i need it to be working with IE7.