In my web page, I am passing the value of a textarea to PHP via the POST Method. That value is supposed to be written into a file, but in the $_POST key which contains the value, it has no line breaks, so when it is written to the file, there are no line breaks (as if some one replaced \n with nothing).
Is there some PHP/JS function that replaces JS textarea newlines into PHP newlines that work in files?
Edit:
My code is supposed to be a file editor. Here it is:
<!DOCTYPE html>
<html>
<head>
<title>File Editor</title>
<meta charset="UTF-8"/>
<style>h1{text-align:center;font-size:40px;padding:10px;border:2px solid black;border-radius:10px;}textarea{width:90%;height:90%}</style>
</head>
<body>
<h1>File Editor</h1>
<?php
if(isset($_POST["save"],$_POST["extra"]))
file_put_contents($_POST["save"],$_POST["extra"]);
if(isset($_POST["delete"]))
unlink($_POST["delete"]);
if(!isset($_POST["filename"],$_POST["submit"])){
?>
<form action="editor.php" method="post">
<label for="filename" id="n">Enter a file to edit: </label>
<input type="text" name="filename" placeholder="Enter file name to edit"/>
<button type="submit" name="submit">Submit</button>
</form>
<?php }else{ ?>
<textarea><?php echo htmlspecialchars(file_get_contents($_POST["filename"])); ?></textarea>
<span style="display:none"><?php echo $_POST["filename"]; ?></span>
<form action="editor.php" method="post" style="display:none" id="a">
<input name="close" id="v" />
<input name="extra" id="e" />
</form><br/>
<button id="save">Save</button>
<button id="close">Close file</button>
<button id="delete" style="color:red">Delete file</button>
<script>
function submit(v,x,c){
document.getElementById("v").name=v;
document.getElementById("v").value=x;
document.getElementById("e").value=c;
document.getElementById("a").submit();
}
document.getElementById("save").onclick=function(){
submit("save",document.getElementsByTagName("span")[0].innerHTML,document.getElementsByTagName("textarea")[0].value.replace(/\n/g,"\r\n"));
}
document.getElementById("close").onclick=function(){submit("close");}
document.getElementById("delete").onclick=function(){
if(confirm("Are you sure you want to delete this file?"))submit("delete",document.getElementsByTagName("span")[0].innerHTML);
}
</script><br/><br/>
<?php } ?> </body>
</html>
I see that the purpose of your javascript code is only to fill in any input values. This can be done by utilizing <form> directly. Most likely, copying your data into a <input tye="text"> (text is the default type) will mangle your newlines.
Something like this should be equivalent and without the presented issue:
<!DOCTYPE html>
<html>
<head>
<title>File Editor</title>
<meta charset="UTF-8"/>
<style>h1{text-align:center;font-size:40px;padding:10px;border:2px solid black;border-radius:10px;}textarea{width:90%;height:90%}</style>
</head>
<body>
<h1>File Editor</h1>
<?php
if(isset($_POST["save"],$_POST["extra"]))
file_put_contents($_POST["filename"],$_POST["extra"]);
if(isset($_POST["delete"]))
unlink($_POST["filename"]);
if(!isset($_POST["filename"],$_POST["submit"])){
?>
<form action="editor.php" method="post">
<label for="filename" id="n">Enter a file to edit: </label>
<input type="text" name="filename" placeholder="Enter file name to edit"/>
<button type="submit" name="submit">Submit</button>
</form>
<?php }else{ ?>
<span style="display:none"><?php echo $_POST["filename"]; ?></span>
<form action="editor.php" method="post">
<textarea name="extra"><?php echo htmlspecialchars(file_get_contents($_POST["filename"])); ?></textarea>
<br/>
<input type="hidden" name="filename" value="<?= $_POST['filename'] ?>">
<button name="save">Save</button>
<button name="close">Close file</button>
<button name="delete" style="color:red">Delete file</button>
</form>
<script>
document.getElementById("delete").onclick=function(e){
if(!confirm("Are you sure you want to delete this file?")) e.preventDefault();
}
</script>
<br/><br/>
<?php } ?>
</body>
</html>
Also as mentioned, you will probably need to format the newlines for html when displaying.
When needing to pass the same or hidden data you can use <input type="hidden" name=".." value="..">. This is used to pass the filename. The desired action is passed with the button press. The name of button you press will be passed in the request.
In your PHP code, you can do:
$text = nl2br($_POST['name_of_textarea']);
Then save $text into the file.
This will preserve line breaks.
Related
How can I change a web page title for everyone on that site and not to be changed with refreshing, using javascript or PHP?
I've tried HTML DOM title but it gets back to its first title after refreshing.
I've tried giving variable in PHP and changing it by after a button pressed but the title didn't change!
These were my codes:
<?php
$title = "Chat";
?>
<html>
<head>
<title><?php echo $title ?></title>
</head>
<body>
<div id="chat_messages"></div>
<form enctype="multipart/form-data" method="post">
<input onClick="dokme()" class="button2" type="submit" name="send" value="Send">
</form>
</div>
<?php
if(isset($_POST['send'])){
$title = "new message";
}
?>
</body>
</html>
Any idea what should I do?
Glad to help.
Of course the title won't change, because php reads your code from 1st line to the end, and you have already added $title = "Chat";
what to do is to change the code like this:
<?php
if(isset($_POST['send'])) $title = "new message";
else $title = "Chat";
?>
<html>
<head>
<title><?php echo $title ?></title>
</head>
<body>
<div id="chat_messages"></div>
<form enctype="multipart/form-data" method="post">
<input onClick="dokme()" class="button2" type="submit" name="send" value="Send">
</form>
</div>
</body>
</html>
This will change the title.
Also, if you want to change the title without refreshing the page, you need JS.
Just use
document.title = '***'; //use your title to replace "***"!
Have a good day~
There are some mistakes in your code like you have used onClick instead you should use onclick
you have not putted a semicolon ; while you are typing
You have not assigned action to your form
Action will be echo htmlspecialchars($_SERVER['PHP_SELF'])
And we will use if else
This will work
<?php
if (isset($_POST['send'])) {
$title = "new message";
} else {
$title = "Chat";
}
?>
<html>
<head>
<title><?php echo $title;?></title>
</head>
<body>
<div id="chat_messages"></div>
<form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']) ?>" enctype="multipart/form-data" method="post">
<input onclick="dokme()" class="button2" type="submit" name="send" value="Send">
</form>
</div>
</body>
</html>
I hope this will Help you
When I am trying to enter data into using php its give me an error Cannot POST /test.php please how I can solve it I am trying so much but it's not working please anyone can help me to solve this problem. It is my project work
this is my html code
<html>
<head>
<title>Login and Registration Form </title>
<link rel="stylesheet" href="style.css" >
</head>
<body>
<div class ="login-page">
<div class ="form">
<form class="login-form">
<h1>Log In </h1>
<input type="text" placeholder="Email id"/>
<input type="password" placeholder="Password"/>
<button type="submit">Log In </button>
<p class="message">Not Registered? Signup</p>
</form>
<form class="register-form" action="test.php" method="post">
<h1>Sign up </h1>
<input type="text" name="name" required placeholder="User Name"/>
<input type="email" name="email" required placeholder="Email id"/>
<input type="password" name="password" required placeholder="Password"/>
<button name="subject" type="submit" value="Register">Sign up</button>
<p class="message">Already Registered?Login</p>
</form>
</div>
</div>
<script src='https://code.jquery.com/jquery-3.4.0.min.js'></script>
<script>
$('.message a').click(function(){$('form').animate({height:"toggle", opacity : "toggle"}, "slow");
});
</script>
</body>
</html>
this is my php code
<?php
$name = $_POST['name'];
$email =$_POST['email'];
$password = $_POST['password'];
$con = mysqli_connect('localhost','root','','registeration');
$query = "INSERT INTO `signup`(`name`, `email`, `password`) VALUES ('$name','$email','$password')";
$run=mysqli_query($con,$query);
if($run==TRUE)
echo "Data Insert Successfully";
else
echo "Error !";
?>
This problem usually occurs when the PHP file you're trying to POST to isn't in the same directory as the HTML file.
If the PHP file is in a different directory you need to give the path to the file (either relative or absolute). For instance for a directory structure such as
root
- html
- index.html
- php
- test.php
your HTML form should point to "../php/test.php".
As an aside, your code is vulnerable to SQL Injection. Please look into using prepared statements using PDO.
I'm still learning Web programming and I'm having a problem on how I'm going to fill my 3 textBoxes based from chosen option in combobox.
I tried using php inside javascript but it seems I'm not doing it right. What I'm trying to do is to load the name, age and address of of a user based from the chosen option combobox so that I can update their data.
<?php
include("myconnection.php");
session_start();
?>
<!DOCTYPE html>
<html>
<head>
<title>
</title>
<script>
function listUpdate()
{
var ddl=document.getElementById("userlist");
var selectedOption=ddl.options[ddl.selectedIndex];
var nameNya=selectedOption.getAttribute("value");
console.log(nameNya);
var tb1=document.getElementById("nameid");
var tb2=document.getElementById("ageid");
var tb3=document.getElementById("addressid");
tb1.value="gago";
<?php
/*
$sql="SELECT * from users WHERE fullname='nameNya'";
mysqli_query($db,$sql);
$nameNyaa=$_POST['nameNya'];
echo $nameNyaa;*/
?>
}
</script>
</head>
<body>
<form action="updateuserprocess.php" method="POST">
<h1>UPDATE USER</h1>
<?php
$sql="SELECT * from users";
$result=mysqli_query($db,$sql);
echo '<select id="userlist" onChange="return listUpdate()">';
while($row=mysqli_fetch_array($result))
{
echo "<option value='".$row[3]."'>".$row[3]."</option>";
}
echo '</select>';
?>
<br>
<label>Name: </label>
<input type="text" name="name" placeholder="" id="nameid"><br>
<label>Age: </label>
<input type="text" name="age" placeholder="" id="ageid"/><br>
<label>Address: </label>
<input type="text" name="address" placeholder="" id="addressid"/><br>
<br>
<input type="submit" name="submit" value="OK"/>
<button type="submit" formaction="/myhome.php">Back</button>
</form>
</body>
</html>
<?php
if(isset($_POST["submit"]))
{
include("updateuserprocess.php");
}
?>
Try doing it like this
$('#mycomboboxID').change(function() {
var combobox_value = $('#mycomboboxID').val();
$('#myInput1').val('First');
$('#myInput2').val('Second');
$('#myInput3').val('Third');
}
You can do if statement inside as well,
and remember you need a jquery extension for this to work
I wanna submit/write content to a .txt file and i have to used php to do it, but i don't wanna open the php page and wanna stay on the same page.
How can I do this?
Index.html
<form action="writer.php" method="POST">
<input name="field1" type="text" />
<input name="field2" type="text" />
<input type="submit" name="submit" value="Save Data">
</form>
writer.php
<?php
if(isset($_POST['field1']) && isset($_POST['field2'])) {
$data = $_POST['field1'] . '-' . $_POST['field2'] . "|| \n";
$ret = file_put_contents('mydata.txt', $data, FILE_APPEND | LOCK_EX);
if($ret === false) {
die('There was an error writing this file');
}
else {
echo " written to file";
}
}
else {
die('no post data to process');
}
?>`
You could simply use iframes, easier alternative to AJAX.
<iframe name="panel" style="display:none;"></iframe>
<form action="writer.php" method="POST" target="panel">
<input name="field1" type="text" />
<input name="field2" type="text" />
<input type="submit" name="submit" value="Save Data">
</form>
...and as everyone here is yelling, consider learning AJAX.
create a php file with following in it.
<?php
if(isset($_POST['SubmitButton'])){ //check if form was submitted
$input = $_POST['inputText']; //get input text
file_put_contents('mydata.txt', $input, FILE_APPEND | LOCK_EX);
$message = "Success! You entered: ".$input;
}
?>
<html>
<body>
<form action="" method="post">
<?php if(isset($message)) echo $message; ?>
<input type="text" name="inputText"/>
<input type="submit" name="SubmitButton"/>
</form>
</body>
</html>
I've got a really simple form that displays a single field. When you punch in a value and hit submit, it gives you a list of checkboxes. You check some and then click another button below and it displays a success/failure message.
I'm trying to convert this to a jQuery mobile app but am having nothing but problems. For example, I can pragmatically call a popup using $("#element").popup("open"); when the page first loads, but after the post when I call the popup open like above I see the URL change but no popup is visible and it's pretty much the exact same page. I also tried just posting the checkboxes to a secondary URL (/update) and then use an HTTP redirect back to the original page, but somehow jQuery Mobile is breaking that.
I've pasted the majority of the code below. If anyone can point me in the correct direction, that's all I'm looking for.
<!DOCTYPE html>
<html>
<head>
<title>Search</title>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/jquerymobile/1.4.2/jquery.mobile.min.css" />
<script src="//ajax.googleapis.com/ajax/libs/jquerymobile/1.4.2/jquery.mobile.min.js"></script>
<script type="text/javascript">
$(document).on("pagecreate", function() {
$(document).on("click", "#button", function(e) {
// Do ajax stuff here
$("#popupBasic").popup("open");
});
});
</script>
</head>
<body>
<div id="lookup" data-role="page">
<div data-role="header">
<h1>Lookup Order</h1>
</div>
<div data-role="content">
<?php if (validation_errors()): ?>
<div class="errors"><?=validation_errors()?></div>
<?php endif; ?>
<?php if ($this->session->flashdata('error')): ?>
<div class="errors"><?=$this->session->flashdata('error')?></div>
<?php endif; ?>
<form method="post" id="search_form" action="/search">
<label for="term">Term:</label>
<input type="number" data-clear-btn="true" name="term" id="term" value="<?=set_value('term')?>" />
<input type="submit" value="Search" />
</form>
<?php if (!empty($fish) && $fish->num_rows()): ?>
<form method="post" action="/update">
<br /><strong>Species:</strong> <?=$species?><br />
<hr />
Uncheck All / Check All<br />
<?php foreach ($fish->result_array() as $k => $f): ?>
<fieldset data-role="fishgroup">
<?php if (!$f['is_deleted']): ?>
<input type="checkbox" name="fish[]" id="checkbox-<?=$f['id']?>" value="<?=$f['id']?>" checked="checked" />
<?php else: ?>
<input type="checkbox" name="fish[]" id="checkbox-<?=$f['id']?>" value="<?=$f['id']?>" checked="checked" disabled="disabled" />
<?php endif; ?>
<label for="checkbox-<?=$f['id']?>">
<?php if ($f['type']): ?>
<?= $f['1'] ?> <?= $f['2'] ?> Attr: <?= $f['3'] ?> Attr: <?= $seat['4'] ?>
<?php else: ?>
<?= $f['3'] ?> <?= $f['4'] ?>
<?php endif; ?>
</label>
</fieldset>
<?php endforeach; ?>
Uncheck All / Check All<br /><br />
<input type="button" value="Update Fish(s)" id="button" />
</form>
<?php endif; ?>
<div data-role="popup" id="popupBasic">
<p>This is a completely basic popup, no options set.</p>
</div>
</div> <!-- end content -->
</div><!-- end page -->
</body>
</html>
Using the following prevents the click handler from being called twice but I still don't get the actual popup after the initial page load:
$(document).off("click").on("click", "#button", function() {
$(" #popupBasic").popup("open");
});
All I'm getting is #&ui-state=dialog added to the URL, and calling $("#button").popup("close"); removes that.
It might be that youre attaching same handler multiple times add
<script type="text/javascript">
$(document).on("pagecreate", function() {
$("#button").off();
$(document).on("click", "#button", function(e) {
// Do ajax stuff here
$("#popupBasic").popup("open");
});
});
</script>