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.
Related
This is wordpress plugin code The following code works, but no text comes into the modal window. Error is this enter image description here
<?php
$phpvariabletext = get_post_meta( $post_id, '_billing_satis_sozlesme', true );
// $phpvariabletext large text along with html codes
?>
<a class="classa" id="view" onclick="openmodal()"> Show Contract </a>
<script type="text/javascript">
var content = '<?php echo $phpvariabletext; ?>';
var newmodal = new tingle.modal();
function openmodal() {
newmodal.open();
newmodal.setContent(content);
}
</script>
You can use PHP variable in JQuery/Javascript easily check below steps
1) Stored PHP variable value in HTML input tag as type hidden
<input type="hidden" value="<?php echo $phpvariabletext;?>" id="phpvariable">
2) After assign variable value in HTML input tag. You can get value in JQuery/Javascript.
<script type="text/javascript">
var content = $('#phpvariable').val();
var newmodal = new tingle.modal();
function openmodal() {
newmodal.open();
newmodal.setContent(content);
}
</script>
Creating extra DOM elements solely to transport a value is needless extra markup.
I always pass php data to javascript as json_encode() output (without manually quoting) because it will automatically double-quote your string and escape any of the double-quotes in the actual data.
<a class="classa" id="view" onclick="openmodal()"> Show Contract </a>
<script type="text/javascript">
let newmodal = new tingle.modal();
function openmodal() {
newmodal.open();
newmodal.setContent(<?= json_encode(get_post_meta($post_id, '_billing_satis_sozlesme', true)); ?>);
}
</script>
The above technique outputs the php value using php "short tags".
P.s. you could also consider removing the inline js function call and use an event listener in your js to keep all of the behaviors/events in one place.
<html>
<head>
<script type="text/javascript">
function showdivv(el, idclicked) {
var iddd = idclicked;
var display = document.getElementById(el).style.display;
if(display == "none")
document.getElementById(el).style.display = 'block';
else
document.getElementById(el).style.display = 'none';
}
</script>
<?php $showw = "<script>document.write(iddd)</script>"; ?>
</head>
<body>
<div id="myDiv" style="display: none;">ID Selected: <?php echo $showw; ?></div>
<?php $variable = 4; ?>
<button type="button" onclick="showdivv('myDiv', '<?php echo $variable; ?>')">Show / Hide</button>
</body>
I'm trying to make a way when a person presses the button pass the variable, in this case ID, to JavaScript and then show the hidden div in PHP. It does not work, can someone help me? THX
If you're okay with the page reloading, you can simply do
window.location.href('php_script_that_needs_your_input.php?id=input_id_from_js');
If not, I absolutely recommend using JQuery as it makes Ajax queries a breeze.
Inside the <head> tags:
<script src='http://code.jquery.com/jquery-2.2.0.min.js'></script>
Upload the script to your own server for production purposes, obviously.
in the <body>, where you want the results from the PHP script to appear (skip this if you don't want output from PHP):
<div id="phpResult"><!--content to be set by ajax--></div>
and put this JS directly below this <div>:
function ajax_on_button_press(resultDiv, id) {
var phpUrl = "php_script.php?id="+id+"&other_variable=cheese&more_info=rats";
$(resultDiv).load(phpUrl);
}
I have used example values here, but you can easily use variables from JavaScript like this:
var other_variable=$('#otherVariableInput').val(); //gets input from a textbox with the html id otherVariableInput
var phpUrl = "php_script.php?id="+id+"&other_variable="+other_variable+"&more_info=rats";
To start the process, you need a button that runs this script. Change your button markup to
<button type="button" onclick="ajax_on_button_press('#phpResult', '<?php echo $variable; ?>')">Show / Hide</button>
If I have understood you correctly, that should solve your problem.
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:


Like so:
write some thing
write other thing
...or:
write some thing
write other thing
...or:
write some thing
write other thing
Demo
<textarea>write some thing
write other thing</textarea>
<textarea>write some thing
write other thing</textarea>
<textarea>write some thing
write other thing</textarea>
so I'm trying to set up upload size limit, but it has been unsuccessful.
I have included the code with explanations, please hava a look and I would be very thankfull if you could help me.
More information on wha I needм help with is after the " // "
Here's the code: `
<html>
<p id="check"></p>
//ok so this part of <script> sends the user to "email.html"
<script type="text/javascript">
function getFile(){
document.getElementById("file").click();
}
function sub(obj){
var file = obj.value;
document.myForm.submit();
}
</script>
//here's the code for the button to upload a file (or image in my case)
<form action="e-mail.php" method="post" enctype="multipart/form-data" name="myForm">
<div id="yourBtn" onclick="getFile()">Yes</div>
<div style="text-align: center; overflow: hidden;">
<input type="file" value="upload" id="file" accept="image/*"
onchange="sub(this)"
size="1" style="margin-top: -50px;" "margin-left:-410px;" "-moz-opacity: 0;
"filter:
alpha(opacity=0);" "opacity: 0;" "font-size: 150px;" "height: 100px;">
</div>
</form>
<script>
var attachement = document.getElementById('file');
attachement.onchange = function() {
var file = attachement.files[0];
if (file.size < 1000000) {
function sub(obj){return true; }
//ok so here's the problem,
when I include this code between
'script' the user is not taken
to "e-mail.html" anymore... please help!!!
else { return false;}
}
}
</script>
</html> `
Thanks a lot:)
To go to a different page when the file is too big, you can assign the new URL to document.location. Note that the URL should be absolute (i.e. http://.../email.html).
I suggest to display an error when the file is too big and simply not submit the page. Otherwise, the user will see the new page and believe that everything was all right.
Also note that you need to do the same check on the server because an attacker might just create a POST request from scratch (without using the code from your page) to send files of arbitrary size to your server.
Because the funtion inside of the onchange is not global. It is only available to the onchange.
would would need to change it to
window.sub = function (obj){return true; }
BUT the flaw with this is the user can change the file a second time and submit since you just removed the return false. You could either add it back in on the else OR you can do validation when the form is submitted and not onchange.
Because of a Flex bug uploading files in a secure environment, I'm attempting to hack together a workaround for this in javascript.
To do so, I'm attempting to create a hidden form in javascript, to which I'll attach a file and some xml meta data, then send it to the server in a multipart form post. My first thought is to get this to work in HTML and then port this javascript code into my Flex project.
My first problem is attaching the file to the hidden form in javascript. I'm doing something wrong here. I'm pretty inexperienced with javascript so if there's a better way to do this, I'm eager to learn.
Here's the code I'm current playing with.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>hidden form post demo</title>
</head>
<body>
<script>
//helper function to create the form
function getNewSubmitForm(){
var submitForm = document.createElement("FORM");
document.body.appendChild(submitForm);
submitForm.method = "POST";
submitForm.enctype = "multipart/form-data";
return submitForm;
}
//helper function to add elements to the form
function createNewFormElement(inputForm, inputType, elementName, elementValue) {
var inputElement = document.createElement("INPUT");
inputElement.name = elementName;
inputElement.type = inputType;
try {
inputElement.value = elementValue;
} catch(err) {
alert(err.description);
}
inputForm.appendChild(inputElement);
return inputElement;
}
//function that creates the form, adds some elements
//and then submits it
function createFormAndSubmit(){
var submitForm = getNewSubmitForm();
var selectedFileElement = document.getElementById("selectedFile");
var selectedFile = selectedFileElement.files[0];
createNewFormElement(submitForm, "HIDDEN", "xml", "my xml");
createNewFormElement(submitForm, "FILE", "selectedFile", selectedFile);
submitForm.action= "my url";
submitForm.submit();
}
</script>
<div id="docList">
<h2>Documentation List</h2>
<ul id="docs"></ul>
</div>
<input type="file" value="Click to create select file" id="selectedFile"/>
<input type="button" value="Click to create form and submit" onclick="createFormAndSubmit()"/>
</body>
</html>
You can see, I have a try/catch block in createNewFormElement. An exception is being thrown there, but the message says "undefined".
In FireBug, I can see that the elementValue is set to a File object, so I'm not really sure what's going on.
For security reasons, you cannot set the value attribute of an input[type=file]. Your current code doesn't need JavaScript, and can be written using pure HTML:
<form method="post" enctype="multipart/form-data" action="myurl">
<input type="file" value="Click to create select file" name="selectedFile" />
<input type="hidden" name="xml" value="my xml" />
<input type="submit" value="Click to create form and submit" />
</form>
If you want to, it's possible to dynamically add additional non-file form elements, by binding an event to the onsubmit handler.
<form ... onsubmit="addMoreinputs();" id="aForm">
...
<script>
function addMoreInputs(){
var form = document.getElementById("aForm");
// ...create and append extra elements.
// once the function has finished, the form will be submitted, because
// the input[type=submit] element has been clicked.
}
add
var dom=document.getElementById("formdiv");
dom.appendChild(submitForm);
in your createFormAndSubmit function.
and add <div id="formdiv" /> on your page.