Complete HTML in notify.js - javascript

I am using library Notify js for showing success or error messages on my php web page.
When I use normal text like
$.notify("Changes are made successfully", "success");
Then it works fine.
But sometimes, I need to show message in unordered list like as follows:
var message = '<p> Please correct following errors and then try again </p><ul><li>value1 is wrong</li><li>value 3 is wrong</li><li>value 5 is wrong</li></ul>';
$.notify(message, "error");
Then message is shown as it is, means whole html is displaying, instead I want to display like
Please correct following errors and then try again
- value1 is wrong
- value3 is wrong
- value5 is wrong
Any suggestion would be highly appreciated!

you can add an own Class with the HTML Content like a Template System.
$.notify.addStyle('saved', {
html:
"<p>Saved blabla...</p>"
});
$.notify(..., {
style: 'saved'
});

Other two ways (beside the utterly noisy addStyle method)
Use \n newline escape character
use \n and expect <br>! Therefore instead of using UL > LI use just some combination of newline escapes \n like:
Store your possible errors inside an Array and than simply use then inside the Notify mesage:
const errors = [ // Or however you can push() errors into this array...
"value 1 is wrong",
"value 2 is wrong",
"value 3 is wrong",
];
// Add dashs "-" to each error and join with newline
const errorsList = errors.map(err => ` - ${err}`).join("\n");
const message = `Please correct following errors and then try again\n\n${errors.join("\n")}`;
$.notify(message, "error");
which will result in:
Please correct following errors and then try again
- value 1 is wrong
- value 2 is wrong
- value 3 is wrong
Modify the plugin source
A simple edit to the source code to allow for HTML is:
at line 205 add to the pluginOptions:
encode: true,
at line 513 change d = encode(d); to be:
if (this.options.encode) {
d = encode(d);
}
Finally, when you use the plugin simply set the new Option encode to false:
// Use like:
$.notify("Lorem<br><b>Ipsum</b>", {encode: false});
Here's my pull request related to this Issue#130

Related

My javascript code can't recognise my array element defined in Python

So I'm trying to open a new window by executing a script in Selenium using driver.execute_script("window.open('');")
But I want to open a link given by the user.
So I got the link input from my array and put it to my javascript code just like this:
driver.execute_script("window.open(data[0]);")
Now It's giving an error like this:
selenium.common.exceptions.JavascriptException: Message: javascript error: data is not defined
How to fix this? Thanks for your time.
EDIT: A part of my code is something like that:
from selenium import webdriver
import PySimpleGUI as sg
import time
global data
data = []
layouts = [[[sg.Text("Enter the Wordpress New Post link: "), sg.InputText(key=0)]],
[sg.Button('Start The Process'), [sg.Button('Exit')]]]
window = sg.Window("Title", layouts)
def selenium_process():
# Getting the driver path
driver = webdriver.Chrome(r'Driver\path')
driver.get('https://google.com')
driver.execute_script(f"window.open({data[0]});")
time.sleep(10000)
while True:
event, values = window.read()
if event in (sg.WIN_CLOSED, 'Exit'):
break
data.append(values[0])
selenium_process()
did you try string interpolation ?
Try this:
driver.execute_script(f"window.open({data[0]});")
Your solution does not work since data[0] is a string, not a variable. You instead need to substitute data[0] with its value (must be a value that JS can understand).
Please read the description of Javascript window.open : https://developer.mozilla.org/fr/docs/Web/API/Window/open
If you just need to get to an URL:
driver.get(data[0])

Parsing errors in Chrome

<script type="module" id="user-code">
try {
someUnknownReference;
} catch (error) {
console.log(error) // correct
console.log(error.toString()); // incorrect
console.log(error.stack.toString().split('\n')); // incorrect - line number and filename is wrong
}
//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbImluZGV4LmpzIl0sIm5hbWVzIjpbImxrc2xrcyJdLCJtYXBwaW5ncyI6IkFBQUFBLE1BQU0iLCJmaWxlIjoiYnVuZGxlLmpzIiwic291cmNlc0NvbnRlbnQiOlsibGtzbGtzIl19
</script>
I'm building a browser based code editor using Babel. All is working well, however I can't for the life of me extract the line number and file name out of the errors that happen during run time.
The example above is a simplified version of what I'm doing. I'm injecting a string into a script tag e.g scriptTag.innerHTML = bundledCode;
The first console.log prints exactly what I want to parse e.g it has the file name and correct line number which it gets from the sourcemap
ReferenceError: someUnknownReference is not defined
at index.js:1
However, as soon as I try to do anything with the error e.g the second console.log, I lose the line number and file name.
ReferenceError: someUnknownReference is not defined
My guess is maybe it's losing the reference to the sourcemap when we try to parse the object?
Thanks in advance for any help!
I think Chrome console is automatically consuming source maps to provide the correct error msg if you're console logging the error. Not if you're grabbing the actual string. Do you need something like this: https://www.npmjs.com/package/sourcemapped-stacktrace?

Hyperledger-Composer: not able to access javaScript split()-function from within transaction processor function

In my hyperledger composer app I added some programmatic access control to a transaction processor function (in file logic.js).
One of the lines of code I added throws an error:
Here is the line of code:
for (consultantRef of transaction.newConsultants) {
//the following line of code does NOT work:
let consultantId = consultantRef.split('#')[1];
In the console I get the following error message:
"transaction returned with failure: TypeError: consultantRef.split is not a function"
For clarification:
transaction.newConsultants is an array of the following type:
["resource:org.comp.app.Consultant#id1", "resource:org.comp.app.Consultant#id2",
"resource:org.comp.app.Consultant#id3"]
I want to get the id of the respective consultants (e.g. "id1").
According to the docs (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split), the split function DOES exist.
But it doesn't work.
How can I get the ids of the consultants?
UPDATE:
When I look at the attributes of the transaction in the console, I see the following for the attribute "newConsultants":
newConsultants: Array (1)
0 "resource:org.comp.app.Consultant#john.doe#gmail.com_1535655902439"
Array Prototype
For clarification:
transaction is an object, namely the following (copied from the angular front-end):
this.transaction = {
$class: 'org.comp.app.AddToConsultantsOfProject',
'project': 'resource:org.comp.app.project#' + this.projectId,
'newConsultants': this.selectedConsultants,
'timestamp': new Date().getTime()
};
its because its a Resource. You would likely convert it to a String (then split would be available on the string object - but you would still need to remove trailing characters (of the resource converted)).
There is a better way -try something like:
trxn.newConsultants.forEach((consultantRef) => {
console.log("identifier is " + consultantRef.getIdentifier());
});
getIdentifier() is described in the Composer API docs.

append method using the from inside an Jquery $getJSON

Ok, so I have 3 files,
First a JSON file that tells me all the information that I need,
A Html file that gives me like a skeleton of where to put all the javascript
A javascript file that will hook up the information from the JSON and put into the html.
So my HTML is something like:
<div class="hello">
<h2>Name</h2>
</div>
My JSON is this with root to data/bio.json:
{
"name" : "Olivia Palito",
"age" : "23"
}
My Javascript is like this:
var mockup = '<div class="work"></div>';
var mockup02 = '<div>%data%</div>';
var $addItem01 = $(".hello");
var $addItem02 = $(".work");
var jsonRoot = 'data/bio.json';
$.getJSON(jsonRoot, function(data){
var addMe = mockup.replace('%data%', data.name);
$addItem01.append(mockup);
$addItem02.append(addMe);
});
Now the problem,
When I run this on the browser, I can add the first mockup, and it will add the <div class="work"></div> but when I try to add also the addMe, it doesn't show anything.
What am I missing here?
And if I put console.log(data); it will show something, which means that I am receiving the file, but it just not adding to the html, because I can add also static text, instead of using the replace method, and won't add the content.
var mockup02 = mockup.replace(%data%, data.name);
It does not work because that is not valid JavaScript.
Open up the console and you should see the error
Uncaught SyntaxError: Unexpected token %
You need to make it a regular expression
var mockup02 = mockup.replace(/%data%/, data.name);
or a string
var mockup02 = mockup.replace("%data%", data.name);
And the second reason it fails is you are selecting the element with the class work before it is added to the page. It does not magically find the element.
Switching it to and it will add it.
$(".work").append(addMe);

Ajax in Dojo with Perl

Anyone can tell me what I'm doing wrong?
I am creating a simple system to get people in and out of user groups and for that purpose I am using Dojo and Perl. (If I could have it my way it would be PHP but I am not the boss.)
At the moment I only use three files, one for Perl, one for JavaScript and one for CSS styles.
The start of the CGI script routes to different functions as follows:
if ($search = $cgi->param('psearch')) {
dbConnect();
jsonSearchPersons($search);
dbDisconnect();
} elsif ($user_id = $cgi->param('person')){
dbConnect();
create_form($user_id);
dbDisconnect();
} elsif ($user_id = $cgi->param('saveuser')) {
save_user();
} else {
mainPage();
};
...
sub save_user {
print $cgi->header(-type=>'text/plain',-charset=>'utf-8');
print("success");
}
The problem I have now is when I want to save the new groups for the user though an Ajax call (a call to this URL: users.cgi?saveuser=xx). This should (in my point of view) be a POST call, so I made this and tried to append the resulting HTML/text in a <div> but it didn't work:
dojo.xhr.post({
url: "/cgi-bin/users.cgi?saveuser="+user_id,
content: {
new_groups: group_ids.toString()
},
load: function(html_content){
var element = document.getElementById("test_area");
element.innerHTML = html_content;
},
error: function(){
alert("An error has occured during the save of new user groups.");
}
});
When I do it with dojo.xhr.get(); it works fine, but when I do it with the POST it's like it jumps over that part of the if statement and just appends the mainPage() function. Is there something basic I don't understand between Dojo and Perl? Do I have to set up the pages so it will accept a POST call? Or what am I doing wrong?
NOTE: This is the first "system" I have made though Dojo and Perl. (I'm normally a PHP/jQuery kind of guy who makes everything UI by hand, so I'm kinda new to it.)
Try adding the saveuser-parameter to the content-object of dojo.xhrPost instead of passing it in the url.
You're trying to pass the saveuser-parameter as GET and the other as POST, maybe that confuses your serverside part.
Try it like that:
dojo.xhr.post({
url: "/cgi-bin/users.cgi",
content: {
new_groups: group_ids.toString(),
saveuser: user_id
},
load: function(html_content){
var element = document.getElementById("test_area");
element.innerHTML = html_content;
},
error: function(){
alert("An error has occured during the save of new user groups.");
}
});
Found a solution.
The problem was my javascript. When posting to a perl script you use $cgi=new CGI; and all that. This takes both GET and POST variables and validates them. In my javascript/dojo code, i then used an url with GET vars and then made a POST as well. This meant perl could not find out (or was mixing) the two variable types. So when i changed my ajax code (as below) it worked, since $cgi->param('saveuser') both fetches GET and POST of "saveuser" (no change to the perl was needed):
dojo.xhr.post({
url: "/cgi-bin/users.cgi",
content: {
saveuser: user_id,
new_groups: group_ids.toString()
},
load: function(html_content){
var element = document.getElementById("test_area");
element.innerHTML = html_content;
},
error: function(){
alert("An error has occured during the save of new user groups.");
}
});
Kinda wack bug, but im glad since it works great now :D
Line 675 of CGI.pm :
# Some people want to have their cake and eat it too!
# Uncomment this line to have the contents of the query string
# APPENDED to the POST data.
# $query_string .= (length($query_string) ? '&' : '') . $ENV{'QUERY_STRING'} if defined $ENV{'QUERY_STRING'};
Made me laugh !

Categories