How to execute code written in codemirror textarea? - codemirror

I have written a basic code in CodeMirror's textarea and now facing problem in executing the code written.
Below is the HTML part:
<form id="preview-form" method="post" action="<?php echo
$_SERVER['PHP_SELF']; ?>">
<textarea class="codemirror-textarea" name="preview-form-comment"
id="preview-form-comment">
#include<stdio.h>
int main()
{
printf("Hello World!!");
}
</textarea>
<input type="test" name="testID" id="testID" value="aqsa shahid">
<br>
<input type="submit" name="preview-form-submit" id="preview-form-
submit" value="Submit" onclick="test();">
</form>
<div id="preview-comment"></div>
This is the function to execute code.
function test() {
//code goes here
alert(document.getElementById("preview-form-comment").value);
var code = $(".codemirror-textarea")[0];
var editor = CodeMirror.fromTextArea(code, {
lineNumbers: true,
matchBrackets: true,
mode: "text/x-csrc",
theme: "dracula"
});
CodeMirror.runMode(document.getElementById("preview-form-
comment").value, "text/x-csrc", document.getElementById('preview-
comment')); };

I know you probably solved this and it's old, but i will put this in case someone else is looking for the answer
i solved this using an iframe then in js
iframe.src = "data:text/html;charset=utf-8," + encodeURI(new_textarea.value)
and it worked for me .

You probably should use a second textarea. Look at this code:
// on and off handler
CodemirrorInstance.on('change',function(e){
// get value from instance
new_textarea.value = e.getValue();
});
I could not test my code yet so I'm not sure if if will work.
Greetings.

Related

How can I stop default submission of form using Vanilla JavaScript

I would like to stop default submission using Vanilla JavaScript. I created a sample of little form. But it gets refreshed when I submit the form even though I call the preventDefault() method. When I use input type="button" it works. But not works with input type="submit".
What will be the reason? Can anyone explain me what is the right method and what's wrong with the code?
My code is as follows:
let validation = () => {
let form = document.querySelector(".form");
form.addEventListener("submit", (event) => {
event.preventDefault();
});
}
<form action="" class="form" method="post" onsubmit="return validation()">
<input type="text">
<input type="submit" value="submit">
</form>
Optional Help: Can anyone give me a proper method or any good references on creating forms. Because when I search, I got lots of tutorials where all are says different methods and I really struggle to find out which method is the standard one.
Try the following changes to your code:
HTML
<form action="" class="form" method="post" onsubmit="validation(event)">
<input type="text">
<input type="submit" value="submit">
</form>
Try removing the return keyword and add event parameter.
JavaScript
const validation = event => {
event.preventDefault();
}
Using the preventDefault() method of event, the form is hopefully not submitted! Hopefully it works for you.

Use two buttons in the same form for invisible recaptcha

I'm trying to implement the new invisible recaptcha, from Google.
It's all working perfectly, but my forms always have two submit buttons, that does different things with the input.
I tried to simply add another in my form, but google only recognize the first one in code.
I can't think of any reason that would prevent the other button to work properly. Here is a simple example of what I tried :
<form action="page.php" method="POST">
<input type="text" value="textfield"/><br/>
<button class="g-recaptcha" data-sitekey="mysitekey" data-callback='onSubmit' value="anaction">An action</button>
<button class="g-recaptcha" data-sitekey="mysitekey" data-callback='onSubmit' value="anotheraction">Another action</button>
</form>
I usually tell apart the two buttons by making an isset on the POST values. Here it doesn't seem to work with the second button. If I switch the two lines, it will make the other button submit properly.
If someone has an idea about this, I'll thank him for enlightments.
Thank you :)
I had same issue and I fixed it like below:
<button type="submit" class="g-recaptcha"
id="captcha1"
data-sitekey="YOUR_SECRETKEY"
data-callback="sendData">button</button>
<button type="submit" class="g-recaptcha"
id="captcha2"
data-sitekey="YOUR_SECRETKEY"
data-callback="sendData">button</button>
<script type="text/javascript">
$( document ).ready(function() {
$(".g-recaptcha").each(function() {
var object = $(this);
grecaptcha.render(object.attr("id"), {
"sitekey" : "YOUR_SITEKEY",
"callback" : function(token) {
object.parents('form').find(".g-recaptcha-response").val(token);
object.parents('form').submit();
}
});
});
}
);
</script>
Yes I created a function sendData like below:
<script type="text/javascript">
function sendData(){
var test = $("#test").val();
if(test != ""){
$.post( "page.php",
{ 'g-recaptcha-response': grecaptcha.getResponse(), 'test' : test})
.done(function( data ) {
console.log(data);
}
);
}else{
console.log(data);
}
grecaptcha.reset(); //important
}
</script>
Stash the token in a hidden field and use it instead of the g-recaptcha-response value to send your verification request. You can distinguish between the two submissions by saving the action item in the JSON return object. I have no idea why this works, by the way.
<head>
...
<script src="https://www.google.com/recaptcha/api.js"></script>
<script>
function onSubmit(token) {
document.getElementById("token").value = token;
document.getElementById("form").submit();
}
</script>
...
</head>
<body>
...
<form id="form" action="page.php" method="POST">
<input type="hidden" id="token" name="token">
...
<button type="submit" class="g-recaptcha" data-sitekey="..." data-callback="onSubmit" data-action="action">An Action</button>
<button type="submit" class="g-recaptcha" data-sitekey="..." data-callback="onSubmit" data-action="anotheraction">Another Action</button>
</form>

submiting form on div click with js

I have a div element and I want that when I click on it i submit a form which is hidden.
div code
<div class="a15 training-exercise">
some text
<form accept-charset="UTF-8" action="/trainings/1/training_exercises/5" data-remote="true" method="post"><div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="✓"><input name="_method" type="hidden" value="put"></div>
<input id="training_exercise_done" name="training_exercise[done]" type="text" value="false">
<input name="commit" type="submit" value="subit">
</form>
</div>
coffescript
$ ->
$('.training-exercise').click ->
if $(this).hasClass('done')
$(this).removeClass('done')
$(this).find('input:text').val(false)
$(this).closest("form").submit()
else
$(this).addClass('done')
$(this).find('input:text').val(true)
$(this).closest('form').submit()
corresponding JS code
$(function() {
return $('.training-exercise').click(function() {
if ($(this).hasClass('done')) {
$(this).removeClass('done');
$(this).find('input:text').val(false);
return $(this).closest("form").submit;
} else {
$(this).addClass('done');
$(this).find('input:text').val(true);
return $(this).closest('form').submit;
}
});
});
i didn't put checkbox for true and false because f.checkbox gave me some strange results
The problem here is:
1) Everything is happening except form submitting
2) form has visibility: hidden; and it is hidden, but there is empty space where the form is, I want that it looks like there is nothing there
For 1st problem, try
$(function() {
$('.training-exercise').click(function() {
var element = $(this);
if (element.hasClass('done')) {
element.removeClass('done');
element.find('input:text').val(false);
element.closest('form').submit(); //<-- brackets here.
} else {
element.addClass('done');
element.find('input:text').val(true);
element.closest('form').submit();
}
});
});
For 2nd problem use display:none; instead of visibility:hidden.
It seems that form selecting didn't work (although it work when I tried from console)
The solution that works is:
$(this).find('input:submit').submit()

Checking if text area is blank prior to form submission?

So I wrote this code so that every time someone clicks the submit button, a javascript
function, called check, will see if the text area is empty. If it is not, then the form will be submitted.
This is my code. Why isn't it working?
<form method=post name='form_post' id='form_post' action='SUBMITIT.PHP'>
<textarea id=message name=message class=post onfocus=this.className='post_focus';
placeholder='Share your thoughts' maxlength=500></textarea>
<br>
<button onclick='check()' id=button name=button>Post</button>
</form>
<script type="text/javascript">
function check()
{
if(!document.textArea.message.value=="")
{
document.forms["form_post"].submit();
}
}
</script>
Thanks!
EDIT: I finally got it to work. Here's a template if you are having a similar problem.
<!--The form-->
<form action="mypage.php" method="post" name="myForm" id="myForm">
<textarea name=myTextArea id=myTextArea>
</textarea>
</form>
<br>
<button onclick='check()'>
Post
</button>
<!--The script that checks-->
<script type="text/javascript">
function check(){
String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g, ""); };
var textAreaValue=document.getElementById('myTextArea').value;
var trimmedTextAreaValue=textAreaValue.trim();
if(trimmedTextAreaValue!="") {
document.forms["myForm"].submit();
}
}
</script>
The following woks, and it also wipes unnecessary spaces, the form will only submit when given a character
<form action="yourpage.php" method="post" onsubmit="return check(this)">
<textarea id="message"></textarea>
<input type="submit" value="Post" />
</form>
<script>
function check(form){
if (form.message.value.trim() == ""){
return false
}
}
</script>
This is the most simple way to do this, and the advised one.
You could simply add "required" to the textarea field in HTML.
Note: Although the question is quite old, I am adding the answer for the future references.

REST Codeigniter, jquery/ajax does not display response

I'm trying to get a helloworld type program working with REST CI/jquery. I've included my (really rudimentary) REST controller, view file and javascript file and am hoping that the error that has eluded me jumps out at you.
Two issues:
The response I get from the server does not get displayed - the screen gets refreshed instead (I know this is some very basic thing I've missed). If I step through the code, I see the display of the result but then, screen gets refreshed. And somehow, I cannot step into my "success" function. Why, oh why?
2.Upon success, I'd like to redirect the user to another url, say, www.google.com. Would I do this in the javascript file? or server side?
Thank you in advance for helping me!
[Added after solving the issue: My problem has nothing to do with REST or Codeigniter. A purely javascript problem]
The REST Controller:
<?php
require APPPATH.'/libraries/REST_Controller.php';
class Myex extends REST_Controller {
function contact_post(){
$result=array();
$fname=$this->post('fname');
$lname=$this->post('lname');
$result['message']="contact_post has your name";
$result['fname']=$fname."XX";
$result['lname']=$lname."YY";
$this->response($result,200);
}
}
?>
The view file:
<?php $this->load->view('includes/header')?>
<div id="input-div">
<form name="cookieform" id="login" method="post">
First Name: <input type="text" name="fname" id="fname" class="text"/>
Last Name: <input type="text" name="lname" id="lname" class="text"/>
<input type="submit" name="submit" value="Submit" id='submit' class="page"/>
</form>
</div>
<div id="resp-div">
response goes here
</div>
<?php $this->load->view('includes/footer')?>
The javascript file:
function postsuccess(output) {
$('#soln-div').html(output.message +'for user '+output.fname+' whose last name is '+output.lname).show('slow');
}
function post_contact() {
$('#submit').click(function(){
var output;
var fdata,res;
var furl=global_siteurl+'/myex/contact';
var fname=$('#fname').val();
var lname=$('#lname').val();
fdata='fname='+fname+'&lname='+lname;
res=$.ajax({
url: furl,
type: 'POST',
dataType: 'json',
data:fdata,
success: function(output) {
postsuccess(output);
}
});
});
}
$(document).ready(function() {
get_contact();
post_contact();
});
You have called your ajax function upon submission of form you can prevent refreshing of page in 2 ways:
(a) Use <input type="button" /> instead of submit call your ajax function on this button or
(b) Use return false; in your success function of ajax request.
You can redirect to any url in javascript using window.top.location = 'url-to-redirect';