How to convert contents saved from markdown back to html - javascript

I have rendered simplemde-markdown-editor in jsp page as
<article class="post">
<div class="form-style-2">
<form:form method="post" commandName="post">
<form:input cssClass="input-field" path="postTitle"/>
<form:textarea id="editor" path="postBody"/>
<input type="submit" value="Save Post"/>
</form:form>
</div>
</article>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/latest/css/font-awesome.min.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/simplemde/latest/simplemde.min.css">
<script src="https://cdn.jsdelivr.net/simplemde/latest/simplemde.min.js"></script>
<script>
new SimpleMDE({
element: document.getElementById("editor"),
spellChecker: false,
});
</script>
all set perfectly working good, but when I browse saved contents of markdown I get same symbols as of
#### Unordered
* Lists are a piece of cake
* They even auto continue as you type
* A double enter will end them
* Tabs and shift-tabs work too
any help please.
Thanks

just use simplemde.markup(simplemde.value());

Related

Distance converter keeps navigating to PHP page

I'm working on a basic distance converter and clicking the form to submit keeps redirecting to the somephpfile.php (which doesn't exist as this is an exercise) instead of posting the converted number in kilometers (mi > km) to the div "container bottom." Here is what I've got so far, any help would be much appreciated:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Miles to Kilometers Converter</title>
<!--/ /-------- Normalize CSS --------/ /-->
<link href="https://cdnjs.cloudflare.com/ajax/libs/normalize/8.0.1/normalize.min.css" rel="stylesheet">
<!--/ /-------- Google Fonts --------/ /-->
<link href="https://fonts.googleapis.com/css?family=Oswald|PT+Sans&display=swap" rel="stylesheet">
<!--/ /-------- My Styles --------/ /-->
<link href="styles.css" rel="stylesheet">
</head>
<body>
<h1>Miles to Kilometers Converter</h1>
<div class="container top">
<p>Type in a number of miles and click the button to convert the distance to kilometers.</p>
<form method="post" action="somephpfile.php" id="convert">
<input type="number" name="distance" id="distance" placeholder="distance">
<input type="submit" name="convertdist" value="Convert Distance">
</form>
</div>
<div class="container bottom" id="answer">
<h2 class="invisible">Answer goes here</h2>
</div>
<script>
var miles = parseInt(document.getElementById("distance").value);
var kilometers = (miles * 1.609344);
var answer = document.createElement("P");
answer.innerHTML = `"${miles} miles converts to ${kilometers} kilometers"`;
document.getElementsByName("convertdist").addEventListener("click", function(event){
event.preventDefault();
document.getElementById("answer").appendChild();
});
</script>
</body>
</html>
<form method="post" action="somephpfile.php" id="convert">
<input type="number" name="distance" id="distance" placeholder="distance">
<input type="submit" name="convertdist" value="Convert Distance">
</form>
This form will be submitted when you click on the submit button. Make the form as follows.
<form id="convert"> <!-- Taken out the attributes method and action -->
<input type="number" name="distance" id="distance" placeholder="distance">
<input type="button" name="convertdist" value="Convert Distance" onclick="convert()"> <!-- Changed the button type submit->button -->
</form>
For JavaScript, you have to enclose the JS logic in a function or so, and call it during onclick of the submit button, like:
<script>
function convert(){
var miles = parseInt(document.getElementById("distance").value);
var kilometers = (miles * 1.609344);
var answer = document.createElement("P");
answer.innerHTML = `"${miles} miles converts to ${kilometers} kilometers"`;
document.getElementById("answer").appendChild(answer);
}
</script>
Things you got wrong are:
Conversion + Appending the answer should be callable, meaning it should be a function.
The conversion function should be invoked whenever the button is clicked. So, it should be bound to the onclick event of the convert button.
Any HTML form with a button of type submit will be submitted to the target specified by action attribute no matter what, unless you block that with event.preventDefault() in your JS. You did that, but not where it should have been done.
The following in your code makes no sense from where you have put it.
document.getElementsByName("convertdist").addEventListener("click", function(event){
event.preventDefault();
document.getElementById("answer").appendChild();
});
Put the working version in this fiddle. Find time to check out.

Unclosed img tag breaks site but is not shown

I want to create a simple site that can be broken with a Cross-Site Scripting vulnerability. The problem lies in the third and "hard" challenge which filters input with regex and removes everything that starts and ends with angle brackets. So, for example, <img> would be removed, but <img would not. That is also the key to solving the challenge - an unclosed void tag with malicious event attributes. The problem is that the <img tag (or any other unclosed tag) breaks the site but is not added to the DOM.
Everything is done by JavaScript. Clicking a button takes the value of the text box and assigns it to a paragraph's innerHTML. I have already tried other methods like outerHTML, or insertAdjacentHTML() but it all has the same result.
This is the HTML:
<head>
<title>Search</title>
<meta charset="UTF-8">
<link rel="stylesheet" href="stylesheet/stylesheet.css">
<script src="script/xss_hard.js"></script>
</head>
<body>
<div id="top">
<div id="Logo">
<img src="images/logo.png" style="margin-top: 0px; width:150px;display:block" />
<h2><span id="title">Search</span></h2>
</div>
</div>
<div id="logic">
<input type="text" onclick="javascript:clearBox()" value="Search" id="box">
<input type="submit" value="Check" onclick="javascript:submit()" id="butt">
</div>
<p id="searchReflect"></p>
</body>
And this is the corresponding JavaScript:
function submit(){
var reflect = document.getElementById('searchReflect');
var boxText = document.getElementById('box').value;
var blacklist = /<.*>/;
boxText = boxText.replace(blacklist, '');
reflect.HTML = "Your search for \"" + boxText + "\" returned nothing!";
}
The expectation is, is that it is possible to inject e.g. <img src="" onerror="alert(1)" and get an alert popup (XSS). What actually happens is this (taken from Firefox inspector with "Edit as HTML"):
<p id="searchReflect">Your search for "</p>
The strange thing is, is that it breaks the output, but is still not run. Same thing with svg, iframe, or other tags. It SHOULD be, when filtered or properly embedded (innerText, for example):
<p id="searchReflect">Your search for "foo" returned nothing!</p>
You need to improve your code.
<head>
<title>Search</title>
<meta charset="UTF-8">
<link rel="stylesheet" href="stylesheet/stylesheet.css">
<script src="https://code.jquery.com/jquery-3.4.1.js"integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU="crossorigin="anonymous"></script>
<script src="script/xss_hard.js"></script>
</head>
<body>
<div id="top">
<div id="Logo">
<img src="images/logo.png" style="margin-top: 0px;width:150px;display:block" />
<h2><span id="title">Search</span></h2>
</div>
</div>
<div id="logic">
<input type="text" value="" id="box" placeholder="Search" />
<input type="submit" value="Check" onclick="submit()" id="butt" />
</div>
<p id="searchReflect"></p>
</body>
And corresponding Javascript. I added jQuery in <Head> tag to make code simpler :) Javascript is too long to write so use jQuery instead of Javascript.
function submit(){
var reflect = $('#searchReflect');
var boxText = document.getElementById('box').value;
var blacklist = /<.*>/;
boxText = boxText.replace(blacklist, '');
reflect.html('Your search for \'' + boxText + '\' returned nothing!');
$('#box').val('');
}

How can I show a DIV element without creating a new row?

I crated a small login form where I check the username in a external php file. After that I give back an error message or redirect to another site.
My problem is to show the error message. I want a short message above the login form if the username != „test“. In my script, the errormessage appears above the login form, but the login form jumps one row deeper.
Question 1:
How can a create a placeholder above the login form? So that the login form is fix?
Question 2:
Is it the right way to fill a JavaScrpt Variable in PHP as in my Code?
Thanks for your help!
< script >
var error_login;
if (error_login == 1) {
$('#errorText').show();
} else {
$('#errorText').hide();
} <
/script>
<?php
//debug
error_reporting(-1);
ini_set('display_errors', true);
session_start();
session_unset();
session_destroy();
?>
<!doctype html>
<html lang="de">
<head>
<title>Hello World</title>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">
</head>
<body>
<?php include ("login.php"); ?>
<div class="container">
<div id="errorText" class="row justify-content-center">
Login failed!
<!-- This should be a placeholder -->
</div>
<!-- Formular Beginn -->
<div class="row justify-content-center">
<div class="col-md-6">
<form class="form" role="form" method="post" action="?login=1" accept-charset="UTF-8" id="login">
<div class="input-group" id="frmGrpBenutzer">
<input type="password" class="form-control input-lg" id="user" name="user" placeholder="Username" required autofocus>
<span class="input-group-btn">
<button type="submit" class="btn btn-primary btn-custom btn-lg" title="login" id="loginbtn"><span>Go</span></button>
</span>
</div>
</form>
</div>
</div>
</div>
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" integrity="sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js" integrity="sha384-alpBpkh1PFOepccYVYDB4do5UnbKysX5WZXm3XxPqe5iKTfUKjNkCk9SaVuEZflJ" crossorigin="anonymous"></script>
</body>
</html>
Here the login.php file:
<?php
session_start();
if(isset($_GET['login'])) {
$user = $_POST['user'];
if ($user == "test") {
$_SESSION['username'] = $user;
header('Location: site2.php');
} else {
echo "<script>
var error_login = 1;
</script>";
}
}
There are a few possibilities. The easiest would be to set your div with an opacity:0 or visibility:hidden this will make it still take space in the document flow.
Another option, could be to set it's position:absolute this will prevent it to take space inside your login form. Doing this will make it overlap tough, so there would need to be a padding or margin to offset the content of the form.
As for setting your javascript variable with PHP, that's one way to do it yes, but your script already defines error_login... Another way to do it, is use a holder HTML element, give it an id, and a data-* attribute. This will make it very easy to read the information from code:
$('button').click(function() {
console.log($('#login_status').data('login-error'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="login_status" data-login-error="1"></div>
<button>Click me to get result</button>
You could also add all the data you want into a JSON string as the div's content, and parse it once the page loaded.

Php search form shows results without pressing the search button when it should wait until the button is pressed to show them

As the title suggests I'm trying to show the results of a query and it works properly, but it shows the results automatically beneath the search button, when it should wait for the button to be pressed and then reload the page and show the results. I'm kind of sure that it's a problem with the code but I cannot find where. I know it's a stupid question but all help is appreciated.
Here is my code:
<?php
mysql_connect('localhost', 'root', 'Passw0rd') or die(mysql_error());
mysql_select_db("cvtool") or die(mysql_error());
include("include/session.php");
$username = $_SESSION['username'];
?>
<!DOCTYPE html>
<html lang="en">
<head>
<!--The viewport tag is used in order to scale the page properly inside any screen size -->
<meta charset="utf-8" name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<title>CV Tool</title>
<link rel="shortcut icon" href="images/favicon.ico" />
<link rel="stylesheet" href="css/main.css"/>
<!--Import JQuery from stored file -->
<script src="js/jquery-1.11.1.min.js"></script>
<!--Import JQuery from Google's Content Delivery Network -->
<!--<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">-->
<link href='http://fonts.googleapis.com/css?family=PT+Sans:400,700' rel='stylesheet' type='text/css'>
<script type="text/javascript" src="js/menu.js"></script>
<script type="text/javascript" src="js/backToTop.js"></script>
</head>
<body>
<!--Big wrapper contains the whole site (header,navigation menu,....,footer-->
<div id="big_wrapper">
<header id="top_header">
<img src="images/cvlogo.png">
</header>
<br>
<nav class="clearfix">
<ul class="clearfix">
<li>Home</li>
<?php
/**
* User has already logged in, so display relavent links, including
* a link to the admin center if the user is an administrator.
*/
if($session->logged_in){
echo "<li>Search</li>"
."<li>My CV(s)</li>"
."<li>My Account</li>"
;
echo "<li>Logout</li>";
}
else
?>
</ul>
Menu
</nav>
<section id="main_section">
<?php
/**
* User not logged in, display the login form.
* If user has already tried to login, but errors were
* found, display the total number of errors.
* If errors occurred, they will be displayed.
*/
if($form->num_errors > 0){
echo "<font size=\"2\" color=\"#ff0000\">".$form->num_errors." error(s) found</font>";
}
?>
<form action="search.php" method="GET" >
<h1>Search for an CV</h1>
<h3>Department</h3>
<br/>
<select id="dropDown">
<option value="">Choose a department</option>
<option value="Comp">Computer Science</option>
<option value="Bus">Business Studies</option>
<option value="Psy" >Psychology</option>
<option value="Eng">English Studies</option>
</select>
<br/>
<h3>Skills</h3>
<br/>
<div id="Comp"class="drop-down-show-hide">
<input type="checkbox" name="whatever" />
Java
<input type="checkbox" name="whatever" />
AI
<input type="checkbox" name="whatever" />
Web Development
</div>
<div id="Bus"class="drop-down-show-hide">
<input type="checkbox" name="whatever" />
Business 1
<input type="checkbox" name="whatever" />
Business 2
<input type="checkbox" name="whatever" />
Business 3
</div>
<div id="Psy"class="drop-down-show-hide">
<input type="checkbox" name="whatever" />
Psychology 1
<input type="checkbox" name="whatever" />
Psychology 2
<input type="checkbox" name="whatever" />
Psychology 3
</div>
<div id="Eng"class="drop-down-show-hide">
<input type="checkbox" name="whatever" />
English Studies 1
<input type="checkbox" name="whatever" />
English Studies 2
<input type="checkbox" name="whatever" />
English Studies 3
</div>
<script>
$(document).ready();
$('.drop-down-show-hide').hide();
$('#dropDown').change(function () {
$(this).find("option").each(function () {
$('#' + this.value).hide();
});
$('#' + this.value).show();
});
</script>
</form>
<form action="search_result.php">
<input type="submit" name="search" id="search" value="Search" />
<div id="search"></div>
<script>
$(document).ready(function(){
$("#dropDown").change(function(){
var data = $(this).val();
$.ajax({
type:'POST',
data:'search_value='+data,
url:'search_result.php',
success:function(data){
$("#search").html(data);
}
});
});
});
</script>
</form>
</section>
<footer id="the_footer">
City CV Tool 2014
</footer>
</div>
</body>
</html>
it's because of this line
$("#dropDown").change(function(){
add a submit button in the form if that's what you want then run the function off that
<input type="submit" value="Submit" />
Edited after rwacarter's correct comments below about accessability
Add an Id to the form tag
<form id="searchformSubmit"
then do
$("#searchformSubmit").on('submit',function(){
this should also work if the user presses the enter key to submit rather then the button provided you have only the one form on the page
The reason why the page is reloading is because any <button> or or <input type='submit'> inside a HTML form will reload the page, unless you have onClick='return false;' on them. I think you need to add:
onClick="startsearch();return false;"
on the submit button. You'll also have to send the form data with it. To do this, make a variable with this:
var form_data = $('#form').serialize();
and send it with:
$.post('search_result.php', {form: form_data}, function(data) {$("#search").html(data);})
Your ajax call (result search) is called when your dropdown change (click, user input, ...), but you should bind the action to your form click
$(document).ready(function(){
$("#search").click(function(){
var data = $("#dropDown").val();
$.ajax({
type:'POST',
data:'search_value='+data,
url:'search_result.php',
success:function(data){
$("#search").html(data);
}
});
});
});
In addition, this is not necessary to specify the action in your form however it will trigger the form action and redirect you to the page search_result.php, I suggest you to update it and set action="#"

In Sinatra, how do I make a multi-page pop-under form which stays on the same page as you fill it out?

I've made a form that appears in a pop-under window, but I can't figure out how to make it multi-step.
Here's my code:
1) main.rb file:
[
'rubygems',
'sinatra',
'sequel'
].each{|g| require g}
DB = Sequel.sqlite('database.sqlite')
DB.create_table? :data_table do
primary_key :id
varchar :img_path
varchar :form1_name
varchar :form2_option
end
before do
#img_path = nil
#form1_name = nil
#form2_option = nil
end
get '/?' do
erb :index
end
post '/form2' do
user_img = params['user_img']
#img_path = './public/images/uploads/' + user_img[:filename]
File.open(#img_path,'wb'){|f| f.write(user_img[:tempfile].read)}# Copying the upload file to the server directory
#form1_name = params['form1_name'] # !!!DATAPOINT!!!
end
2) layout.erb file
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Multi-page form test</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css"> <!-- jQuery UI CSS -->
<script src="http://code.jquery.com/jquery-1.9.1.js"></script> <!-- jQuery -->
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script> <!-- jQuery UI -->
<script src="./js/script.js"></script>
</head>
<body>
<%= yield %>
</body>
3) index.erb file
<button id="upload_form_opener" type="button">Click here to upload</button>
<div id="upload_form_container" title="Form container title">
<form action="form2" method="post" enctype="multipart/form-data" accept-charset="utf-8">
<img id="upload_preview" style="width: 300px; height: 300px;" />
<input id="upload_image" accept="image/*" type="file" name="user_img" onchange="PreviewImage();" />
<script type="text/javascript">
// This JavaScript snipppet is for previewing the image upload
function PreviewImage() {
var oFReader = new FileReader();
oFReader.readAsDataURL(document.getElementById("upload_image").files[0]);
oFReader.onload = function (oFREvent) {
document.getElementById("upload_preview").src = oFREvent.target.result;
// document.getElementById("upload_image").disabled = true
}; // DONE: function (oFREvent)
}; // DONE: function PreviewImage()
</script>
<p>Name <input type="text" name="form1_name" /></p>
<input type="submit" value="Next" />
</form>
</div>
4) script.js
$(document).ready(function(){
var uFormContainer = $('#upload_form_container');
// This snippet is for opening the pop-under form
uFormContainer.dialog({autoOpen: false});
$('#upload_form_opener').click(function(){
uFormContainer.dialog('open');
});
});
5) I want the second step of the form to look like this...
<form action="form2" method="post" enctype="multipart/form-data" accept-charset="utf-8">
<p>Some other text field <input type="text" name="form2_option" /></p>
<input type="submit" value="Next" />
</form>
...but I don't want to leave the page (which is '/', as far as Sinatra is concerned). Is this possible in Sinatra?
There are multiple ways to implement this:
Save some cookie or session, which step is now, and depends on that yield different forms. After submitting write next step id into session and redirect to root_url.
Use ajax to send form and render next step's form.
You can even not really send form, but just switch to next, just hidding previous fields with javascript and show next step's fields. After submitting all parameters will be sent.

Categories

Resources