how javascript send blank line to php? - javascript

I write a demo like this:
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<script type="text/javascript">
window.onload = init;
function init() {
var btn = document.getElementById('submit');
btn.onclick = function() {
var str = document.getElementById('testText').value;
alert(str);
var xmlHttp = new XMLHttpRequest();
var url = 'test.php?str=' + str;
xmlHttp.onreadystatechange = function(){
var str = xmlHttp.responseText;
document.getElementById('testText').value = str.toLocaleUpperCase();
};
xmlHttp.open('GET', url, true);
xmlHttp.send(null);
};
}
</script>
</head>
<body>
<form action="test.php" method="POST">
<textarea name="testText" id="testText" cols="30" rows="10"></textarea>
<input type="button" value="submit" id="submit">
</form>
</body>
</html>
It send a GET to server, and the php just return what it get, then js show it by uppercase(write this because of system ask me to write more detail of code)
I write some text in textarea tag like
write some thing
write other thing
and output is
WRITE SOME THING WRITE OTHER THING
but I want to remain the blank lines, and expect output like this
WRITE SOME THING
WRITE OTHER THING
how should I do?

When you send your data to PHP, you need to convert your text into URL format.
var url = 'test.php?str=' + encodeURIComponent(str);
When you output the PHP into an HTML document, you need to convert your text into HTML.
Most elements do not treat whitespace as significant, so you need to convert the new lines into line break elements or do some other kind of formatting. (In general, you want to use something smarter, like Markdown syntax, but I'll use nl2br for this simplistic example):
<div>
<?php
$data = $_GET['str'];
$safe_data = htmlspecialchars($data);
$formatted_data = nl2br($safe_data);
echo $formatted_data;
?>
</div>
or, if you are outputting into an element with significant whitespace
<textarea>
<?php
$data = $_GET['str'];
$safe_data = htmlspecialchars($data);
echo $safe_data;
?>
</textarea>

You can use the NewLine character entity, which can be expressed using any of the following:
&NewLine;
Like so:
write some thing&NewLine;write other thing
...or:
write some thing
write other thing
...or:
write some thing
write other thing
Demo
<textarea>write some thing&NewLine;write other thing</textarea>
<textarea>write some thing
write other thing</textarea>
<textarea>write some thing
write other thing</textarea>

Related

Trying to use array.push(); with newlines but in plain text, not html <br> tags

recently I have been trying to grab HTML form input data, add a prefix, then write that back into a <div> For example:
HTML:
<h1>Please enter Details</h1><hr>
GUID (Generator):<div id="guidInput" style="display:inline;">
<!-- Changed to an onkeyup="" method. Works the same but with less code. -->
<input onkeyup="gen()" id="guidText" style="height: 16px;"></input>
</div>
ID:<div id="idInput" style="display:inline;">
<!-- Changed to an onkeyup="" method. Works the same but with less code. -->
<input type="number" type="number" onkeyup="gen()" id="idText" style="height: 16px;"></input>
</div>
<div id="command" class="command"></div>
JS:
$(document).ready(function(){
var command = ""; /*Here for future developement*/
command += ""; /*Here for future developement*/
document.getElementById('command').innerHTML = command;
});
function gen() {
var id = $('#idText').val();
var guid = $('#guidText').val();
var command = ""; /*Here for future developement*/
var tags = [];
tags.push("GUID "+guid);
tags.push("ID "+id);
command += tags.join("<br>");
command += ""; /*Here for future developement*/
document.getElementById('command').innerHTML = command;
}
This does what I want it to: https://imgur.com/a/QrwD7 But I want the user to download the output as a file. To do this I implemented FileSaver.js, and added this code to my files:
HTML (placed above the <div id="command" class="command"></div>):
<button onclick="saver()">Save</button>
JS:
function saver() {
var text = document.getElementById("command").innerHTML;
var newText = text.replace(/(<([^>]+)>)/ig,"");
var filename = ("File")
var blob = new Blob([text], {type: "text/plain;charset=utf-8"});
saveAs(blob, filename+".txt");
}
That grabs the content of the <div> containing the output, and triggers a download of File.txt. The contents of this file look like this (from imgur.com link above.):
GUID qwertyuiop<br>ID 12345
This is where I'm having my problem. I NEED the file to look like this:
GUID qwertyuiop
ID 12345
With a line break after every part. the <br> is for displaying it on the site, but I need some way to make sure it's on a separate line in the downloaded file, and having no HTML tags in the file.
var newText = text.replace(`<br>`, `\n`).replace(/(<([^>]+)>)/ig,"");
or
function gen(delimiter) {
// ... //
command += tags.join(delimiter);
return command;
}
function saver() {
// ... //
var newText = gen(`\n`);
// ... //
}
Your code is violating SRP: Single Responsibility Principle.
You are trying to do two things at the same time.
Prefixing and formatting in HTML are two different concerns and they should be separated.
After that, the answer will become obvious.

Why I lost the filename value when I click the submit button

I have made a form to pass xml files on a server. Although when it correctly sends the file to the server, it seems that the pages reloads and the value of the file name is lost and my javascript code returns nothing.
However if I remove the line
<input type="submit" />
from the code below it keeps the filename in the variable x but it doesn't send the file to the server.
I want to send the file on the server and keep its name into a variable in order to use in any other javascript functions.
<?php
$uploads_dir='/web/stud/external/scomvs2/epicurus';
if(isset($_FILES['xml_file1'])){
$errors= array();
$file_name = $_FILES['xml_file1']['name'];
$file_size =$_FILES['xml_file1']['size'];
$file_tmp =$_FILES['xml_file1']['tmp_name'];
$file_type=$_FILES['xml_file1']['type'];
$file_ext=strtolower(end(explode('.',$_FILES['xml_file1']['name'])));
$expensions= array("xml","XML");
if(in_array($file_ext,$expensions)== false){
$errors[]="extension not allowed, please choose an xml file.";
}
if($file_size > 2097152){
$errors[]='File size must be excately 2 MB';
}
if(empty($errors)==true){
move_uploaded_file($file_tmp,"$uploads_dir/$file_name");
echo "Success";
}else{
print_r($errors);
}
}
?>
<html>
<body>
<form action="" method="POST" enctype="multipart/form-data">
<input type="file" id="uploading" name="xml_file1"/>
<input type="submit" />
</form>
<button type="button" onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var x = document.getElementById("uploading").value;
document.getElementById("demo").innerHTML = x;
}
</script>
</body>
</html>
You can add in our Javascript part the following:
<script>
function myFunction() {
var x = <?=json_encode($file_name)?>;
document.getElementById("demo").textContent = x;
}
</script>
Now when in Javascript you call that function, the demo element will show the file name. Note that it is better to use textContent instead of innerHTML, although with filenames you don't risk to have special characters that HTML would interpret (<>&).
Now you should also make sure that $file_name is always defined. So at the top of your PHP code, add:
$file_name = '';
Instead of injecting the file name in your Javascript code, you could also let it be injected directly in the demo tag, like this:
<p id="demo"><?=htmlspecialchars($file_name)?></p>
Then you don't need Javascript to fill it in, if that is all you wanted to do.

Loading .txt file into textarea Javascript?

I was trying to get the text file into textarea. The result is "http://mywebsite.com/textfile/(txtinput).txt and the text file doesn't load into textarea.
<html>
<head>
<title>textbox</title>
<script type="text/javascript">
function readBOX() {
var txtinput = document.getElementById('txtinput').value;
document.forms[0].text.value = ("http://mywebsite.com/textfile/") + txtinput +(".txt");
}
</script>
</head>
<body>
<p> Type</p>
<input type="text" id="txtinput" />
<input id="open" type="button" value="READ" onClick="readBOX()" />
<form>
<textarea name="text" rows="20" cols="70">loaded text here</textarea>
</form>
</body>
</html>
You have to use something like its posted in this Answer
jQuery
$(document).ready(function() {
$("#open").click(function() {
$.ajax({
url : "helloworld.txt",
dataType: "text",
success : function (data) {
$("#text").text(data);
}
});
});
});
Read more on the jQuery Documentation of .ajax()
Non jQuery
I you do not want to use jQuery you have to use the XMLHttpRequest-Object something like that:
var xmlhttp, text;
xmlhttp = new XMLHttpRequest();
xmlhttp.open('GET', 'http://www.example.com/file.txt', false);
xmlhttp.send();
text = xmlhttp.responseText;
But this can be read on the SO-Answer here or the complete and understandable documentation on Wikipedia
Note: But this is not cross browser compatible, for older IE version you have to use the ActiveXObject("Microsoft.XMLHTTP") object
Thanks everyone. Javascript didn't work for me. I changed to PHP and it's working very well.
<!DOCTYPE HTML>
<html>
<head>
<title>textbox</title>
</head>
<body>
<form action="process.php" method="post">
<input type="text" name="name" />
<input type="submit" />
</form>
</body>
</html>
Process.php
<textarea name="text" rows="20" cols="70">
<?php $name = $_POST["name"]; echo file_get_contents("$name");?>
</textarea>
This is how I load text into a textarea
Main.css
.textbox{
font-size: 12px;
float : left;
height : 197px;
width : 650px; }
Default.html
<!DOCTYPE html>
<html>
<head>
<!-- Charactor set allowed to use -->
<meta charset="utf-8"/>
<title>Text from .txt file to TextArea</title>
<!-- External stylesheet -->
<link rel="stylesheet" href="main.css" />
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<textarea class="textbox" id="Brief" readonly></textarea>
<script> $( "#Brief" ).load( "text.txt" ); </script>
</body>
</html>
google textarea to find format of text area
One of the easiest way is to request the server to return the pre-filled textarea
(Here's an example using PHP):
<textarea name="text" rows="20" cols="70">
<?php
echo file_get_contents('yourFile.txt');
?>
</textarea>
Note: Something similar can be done with any server-side scripting language.
In the meantime, if you need to load it dynamically, your best bet is using an AJAX approach. Choose which approach is the best for you to code and maintain. While jQuery is a popular approach, you are free to use anything you feel confortable with and probably want to know about XmlHttpRequest first.
Dynamic AJAX requests with Pure JavaScript can be tricky so make sure that your solution is cross-browser. A common mistake is using XmlHtpRequest directly and failing to make it compatible with older IE versions, which leads to random bugs depending on which browser / version you use. For example, it could look like this (would need to be tested on all targeted browser so you can add fallbacks if needed):
Pure JS:
if (typeof XMLHttpRequest === "undefined") {
XMLHttpRequest = function () {
try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); }
catch (e) {}
try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); }
catch (e) {}
try { return new ActiveXObject("Microsoft.XMLHTTP"); }
catch (e) {}
throw new Error("This browser does not support XMLHttpRequest.");
};
}
function readBOX() {
function reqListener () {
document.forms[0].text.value = this.responseText;
}
var txtinput = document.getElementById("txtinput").value;
var filePath = "http://mywebsite.com/textfile/" + txtinput + ".txt";
var oReq = new XMLHttpRequest();
oReq.onload = reqListener;
oReq.open("get", filePath, true);
oReq.send();
}
But if you don't mind to sacrifice some performances to ensure maximum support, you should use jQuery's implementation:
jQuery:
function readBOX() {
var txtinput = document.getElementById("txtinput").value;
var filePath = "http://mywebsite.com/textfile/" + txtinput + ".txt";
$.ajax({
url: filePath
}).done(function(data){
document.forms[0].text.value = data;
});
}
Note: jQuery's library is kind of huge, but keep in mind that if you include it directly from google servers, your user more likely has it already in cache.
Hope this helps :)
window.addEventListener('DOMContentLoaded', (e) => {
let input = document.getElementById('input');
// load default.txt into input box
try {
let fileToLoad = './default.txt';
let xmlhttp = new XMLHttpRequest();
xmlhttp.open('GET', fileToLoad, false);
xmlhttp.send();
input.innerHTML = xmlhttp.responseText;
} catch(DOMException) {
input.innerHTML = "Error loading file. Maybe related to filepath or CORS?";
}
});

How to grab text from URL and place in JS array?

I've stated previously that I am very new to JavaScript and HTML. I'm creating a small search tool and I'm very confused as to how to get text from a URL and put it in my JS array.
For example, let's say the URL is: http://www.somethingrandom.com/poop
In that URL, there's a couple of words: "something", "everything", "nothing"
Literally just that. It's in a pre tag in HTML, and that's it.
Now, my JS code, I want it to open up that URL, and take those words and place them in a string/list/array, whatever, it could be anything as long as it can happen, I can manipulate it further later.
I have this so far:
<html>
<head>
<script type = "text/javascript">
function getWords(){
var url = "http://www.somethingrandom.com/poop"
var win = window.open( url );
window.onload = function(){
var list = document.getElementsByTagName("pre")[0].innerHTML;
var listLength = list.length;
alert( listLength);
}
}
</script>
</head>
<body>
<button id="1" onClick="getWords();">Click Here</button>
</body>
</html>
It doesn't work however.. And I'm not sure why. :( Please help.
Make an AJAX request and you will have access to the returned content.
Using jQuery:
function getWords(){
var url = "http://www.somethingrandom.com/poop"
$.get(url, function(data) {
var list = $('pre:eq(0)', data).html;
var listLength = list.length;
alert( listLength);
}, 'html');
}

Pass script tag value to input tag in html

I am trying to pass a particular variable value from the script tag to an input tag. But somehow it is not working.
I am trying to pass variable1 value from the below code from script tag to input tag.
So suppose variable1 value is John then this line in my code will look like this-
<input ONCLICK="window.location.href='some_url&textId=John'">
Below is the code
<html>
<head>
<title>Applying</title>
</head>
<body>
<script>
function getUrlVars() {
// some code
}
var variable1 = getUrlVars()["parameter1"];
var variable1 = unescape(variable1);
// some more code
</script>
<input ONCLICK="window.location.href='some_url&textId=variable1'">
</body>
</html>
Can anyone explain me what wrong I am doing?
Try it that way:
var variable1 = getUrlVars()["parameter1"];
variable1 = unescape(variable1);
document.getElementById('Apply').onclick = function() {
window.location.href = 'some_url&textID=' + variable1;
};
That attaches a function to the onclick event that exactly does what you want. For the initial input element simply remove the onclick attribute:
<input name="Apply" type="button" id="Apply" value="Apply" />
If you wish to perform inline functions, you need to wrap the code in an executable closure:
<input name="Apply" type="button" id="Apply" value="Apply" ONCLICK="(function() {window.location.href='your_data'})();">
As this can be largely unmaintainable, I recommend you abstract this functionality into a more organized place in your application.
(function(window, $, undefined) {
// assuming you use jQuery
$('#Apply').click(function() {
window.location.href = '';// your code
})
})(window, $);
I may be totally misunderstanding what you want to do, but I hope this helps.
The whole url parameters bit is surely unnecessary.
You can just set the value attribute in the field:
var field = document.getElementById('textfield');
var value = 'Some text';
field.addEventListener("click", function () {
this.setAttribute('value', value);
});
Here's a jsfiddle example: http://jsfiddle.net/LMpb2/
You have it inside the ' ' you need to add it into the string. So try
"window.location.href='some_url&textId='+variable1+';'"
I would change it to the following if your trying to bind the click handler to this input element:
<html>
<head>
<title>Applying</title>
</head>
<body>
<script>
function getUrlVars() {
// some code
}
var variable1 = getUrlVars()["parameter1"];
var variable1 = unescape(variable1);
document.getElementById("Apply").onclick = function() {
window.location.href='some_url&textId=' + variable1;
}
// some more code
</script>
<input name="Apply" type="button" id="Apply" value="Apply" >
</body>
</html>
I haven't tested it yet but it should work.
at onclick call a function, inside that function set window.locatio.href !
a sample
<script>
var url="www.google.com";
function myfunc(){
alert(url);
}
</script>
<input type="button" onclick="myfunc()" value="btn" >
http://jsfiddle.net/CgKHN/

Categories

Resources