How to write input value to a file in PHP? - javascript

i am quite a beginner in PHP and i wanted to create a input: If you click a button, Javascript will submit it and add linebreak (\n) at the end of what you wrote in the input box, and PHP will write the final result into a file called result.txt. However, when checking result.txt, there is nothing written at all.
HTML
<input id="test" type="text">
<form id="formie" action="test.php" method="post">
<input id="testz" type="text" name="really" hidden="hidden" disabled="disabled"><br>
<button onclick="trigger1()">Submit</button>
</form>
<!-- 2 input boxes, the hidden one is meant to be set to have the final result and with it i do the request -->
<script>
var int;
function trigger1() {
int = document.getElementById('test').value;
document.getElementById('testz').value = int + "\n";
document.getElementById('formie').submit();
}
</script>
PHP
<?php
$postreq = $_POST["really"];
$finaldata = $postreq;
file_put_contents("result.txt", $finaldata, FILE_APPEND);
header("Location: https://domain.tld/test.html");
exit;
?>
No error when stopping the redirect (domain.tld/test.html) and no error in server logs. Why is this happening? I even tried to check this with jshint.com and phpcodechecker.com and both told me no errors

Credit to #user3783243: The problem lies here:
<input id="testz" type="text" name="really" hidden="hidden" disabled="disabled">
Disabled elements cannot have values
Working code:
<input id="testz" type="text" name="really" hidden="hidden">

To answer the question, elements with the disabled attribute are not submitted or you can say their values are not posted
Try removing the "disabled" attribute from your hidden input.
Refer to: Disabled form inputs do not appear in the request, which has reference to the w3 specs explaining that as well.

Related

$_POST variable empty despite javascript autofill

I have a html form, that is filled out with javascript when a button is clicked. In php, I would like to get the $_POST variable, but it is empty dispite setting the element.value to something (obviously after form submission).
THE FIELD ACTUALLY CHANGES TO THE DESIRED VALUE, BUT THE $_POST is still empty.
Html:
<form enctype="multipart/form-data" action="upload_file.php" method="post">
...
<input name="price" id="price" type="text"">
...
</form> ...
<span style="float:left"><a onclick="fill_again()" class="button alt
small">Get last values</a></span>
js:
function fill_again(){
document.getElementById("price").value =5800;
}
php:
echo $_POST["price"]; //<--this should be 5800, but it is ""
I have found the solution to my own problem.
I have a js before that modifies the same element:
reNewElement2 = ';'
document.getElementById("size").innerHTML=reNewElement2;
And I don't know why, but even though this is executed prior to the above script, the value remains as declared here, i.e. there is no value.

Make hyperlink a form submit button

I am trying to get a hyperlink element to act as a form submit button. This sort of question has been answered multiple times over the years but, for some reason, I am not able to get it to work even with cut-n-pasted code and I'm wondering if I'm missing something trivially simple that my eyes are too bugged out to see. The full code is here:
<html>
<head>
<script language="JavaScript" type="text/javascript">
<!--
function signup() {
alert("Form is " + document.signup_form);
document.signup_form.submit() ;
}
-->
</script>
</head>
<body>
<?php
echo("Submit is [" . $_POST['submit'] . "]");
?>
<form method="post" name="signup_form" id="signup_form" action="" >
<input type="text" name="from_email" placeholder="e-mail address"><br>
<input type="submit" name="submit" value="Send Email">
Sign Up!<br>
</form>
</body>
</html>
The input submit element ("Send Email") works fine. The hyperlink ("Sign Up!") also works fine and calls the javascript function so that the alert() box in the function shows up.
So, it's just the submit() call that's not doing anything--I even printed out document.signup_form in an alert() box to confirm that it's defined (it is). So what am I missing here?
Thanks for any help!
There is a weird thing with how forms work with Javascript - each field is accessible by using formElement.fieldName. Unfortunately, that means that if you name a field input submit, all of a sudden the built-in formElement.submit() function is replaced by your input element. So in your code, document.signup_form.submit() is failing because it is calling the element, not the method, and you can't call an element as a function. See this SO QA for details.
The fix is easy - change:
<input type="submit" name="submit" value="Send Email">
to:
<input type="submit" name="submitBtn" value="Send Email">
Also, as others have noted, you will want to give your form a valid action. Also, in general it might be preferred to access things by id (document.getElementById()) instead of by things like document.signup_form.
Your <form> element is missing a value in it's action attribute. Quoting the specs:
You also have to specify the URL of the service that will handle the
submitted data, using the action attribute
Link here

HTML file input with possibility to input several files one after another

I'm looking for a possibility to input several files in a row in an HTML form. It strikes me that there seems to be no easy solution for this (or at least I haven't been able to find it despite several hours of searching). If I use the multiple attribute in an <input type="file" name="myFiles[]" multiple />, I can choose several files at a time holding Ctrl, but if I choose one file at first, then click the input field again and choose another one, the second file seems to overwrite the first one.
So I thought I might try to use javascript to add more <input type="file" name="myFiles[]" /> fields (with the same name), since I have seen something similar somewhere. I tried the following:
JavaScript:
function addInputFileEle() {
var field = document.getElementById("filesField");
var row = '<input type="file" name="myFiles[]" onchange="addInputFileEle();" />';
field.innerHTML += row; // add one more <input type="file" .../> element
}
HTML:
<form method="post" action="#" enctype="multipart/form-data">
<fieldset id="filesField"> <!--for adding more file-input rows-->
<input type="file" multiple name="myFiles[]" class="multi" onchange="addInputFileEle();" />
</fieldset>
<input type="submit"/>
</form>
The document indeed does create additional file-input elements whenever I click on one of them and select a file, BUT: The file does not get uploaded! I mean, after I select the file, the file name does not get displayed, instead, it still says "Choose a file" (or "Select a file", not sure about English). So apparently my onchange="addInputFileEle()" overwrites the normal reaction (the file getting 'loaded' into the input element)? Even though this does not seem logical to me. Can anyone help? Why does the file not get selected in the end? Or maybe there is a simpler solution than mine, which would of course be very welcome. Thanks in advance!
Ok I will just post my solution in case anyone else is searching for a way to select several files for upload one by one. As #CodingWithClass pointed out, I was resetting the input field by using something like parentElement.innerHTML += additionalInputElement;. Instead, I should have used appendChild as #JoshuaK suggested:
<html>
<head>
<meta charset="UTF-8">
<script>
function addFileInput(fieldsetName, firstInputId) {
var fs = document.getElementById(fieldsetName);
// only add one if the last file-input field is not empty
if(fs.lastElementChild.value != '') {
var firstInputFile = document.getElementById(firstInputId);
var newInputFile = document.createElement("input");
newInputFile.type = firstInputFile.type;
newInputFile.name=firstInputFile.name;
newInputFile.multiple=firstInputFile.multiple;
newInputFile.class = firstInputFile.class;
newInputFile.onchange=firstInputFile.onchange;
fs.appendChild(newInputFile);
}
}
</script>
<title>MultiFile-Testing</title>
</head>
<body>
<?php print_r($_FILES); // see if files were uploaded in the previous round ?>
<form method="post" action="#" enctype="multipart/form-data">
<fieldset id="filesFS">
<input type="file" multiple name="myFiles[] id="firstInputFile" onchange="addFileInput('filesFS', 'firstInputFile');" />
</fieldset>
<input type="submit"/>
</form>
</body>
</html>

Calling PHP function from Javascript then change form action

I'm trying to change my form action in my HTML then submit using javascript.
The conditions are in PHP .
I need help if anyone can assist me.
This is my PHP function :-
<?php
error_reporting(0);
if(isset($_POST['email'])){
$email=$_POST['email'];
if(!empty($email)) {
$chrono = 0;
} else {
$chrono = 1;
}
}
?>
The motive of the PHP is to check null email entry.
Here's the javascript function :-
<script type="text/javascript">
function fireform(val){
// missing codes
document.forms["demoform"].action=val;
document.forms["demoform"].submit();
}
// missing codes
</script>
HTML :-
<form name="demoform" action="">
<input type ="text" name="name" id="name">
<input type="hidden" name="buttonpressed" id="buttonpressed">
<input type="button" value="submit B" onclick="fireform('b')">
I want to do it in a way , when the user entered an empty email , the PHP will read it as chrono = 0.
Then goes to javascript , if the chrono equal to 0 , the action will remain empty.
If the chrono = 1 , the javascript will change the action of the form and submit.
I need help thanks.
Your flow is unclear: it seems that you want to change the form action from PHP, but PHP is triggered after the form submission. So there's something weird in your flow. You also don't seem to have a field called email in your markup. Add it (or rename the field name):
<input type="text" name="email" id="email">
Nonetheless, having an empty action means the form will be submitted to the page itself.
Probably what you need is a client side validation of the email field. In the fireform() JavaScript function, just add a check for email field:
function fireform(val){
if (document.forms["demoform"].email.value.length > 0){
document.forms["demoform"].action = val;
document.forms["demoform"].submit();
}
}
This should be enough to get what you need.
I would recommend checking the email field (for being empty) in javascript, and when you have set the proper action submit the form in javascript.
Check the field:
$('#<enter id of field>').val();
Update the action:
$('form').attr('action', 'Enter your updatet action here');
Submit the form:
http://api.jquery.com/submit/

Variable Transfer: Web Form that connects with PHP to Database

Hello and thank you for viewing my question. I am a complete beginner and am looking for simple ways to do the following...
What I have in seperate linked documents:
HTML, CSS, Javascript, PHP
What I am having trouble with:
I need to use something like JSON (although I would also accept XML requests or Ajax at this point if they work) to transfer variables from Javascript to PHP. I need the variables to search in a database, so they need to be literally available within PHP (not only seen on a pop-up message or something).
I have seen a LOT of different ways to do this, I have even watched tutorials on YouTube, but nothing has worked for me yet. The things I am having the biggest problem with is that when I add a submit button to my form it doesn't submit my form and I don't know why.
Form code snippet:
<form id="form" name="input" method="post" action="javascript:proofLength();">
<input id="userinput" type="text" autofocus />
<input id="submit" type="button" value="submit" onsubmit="post();">
</form>
The second to last line there doesn't work. Do I need javascript to submit the form? Because I really thought that in this case it was part of the functionality of the form just like method="post"...
The other thing is that for JSON, I have no idea what to do because my variables are determined by user input. Therefore, I cannot define them myself. They are only defined by document.getElement... and that doesn't fit the syntax of JSON.
Those are really my main problems at the moment. So if anyone could show me a simple way to get this variable transfer done, that would be amazing.
After this I will need to search/compare in my database with some php/sql (it's already connecting fine), and I need to be able to return information back to a in HTML based on what I find to be true. I saw one example, but I am not sure that was very applicable to what I am doing, so if you are able to explain how to do that, that would be great also.
Thank you very, very much.
April
You don't need ajax to submit this form. You don't even need javscript. Just do this:
<form id="form" name="input" method="post" action="mytarget.php">
<input id="userinput" name="userinput" type="text" autofocus />
<input id="submit" type="submit" value="submit" />
</form>
This will send the form data to mytarget.php (can be changed of course)
See that i have added the name attribute to your text-field in the form and i changed the type of the button to submit.
Now you can work the Data in mytarget.php like this:
<?
$username = $_POST['userinput'];
echo "Your name is: ".$username;
?>
You wanted to have a check for length in the submit. There are two ways to this:
Before the input is send (the server is not bothered)
Let the server Check the input
for 1 you will have to append a event listener, like this:
var form = document.getElementById("form");
form.addEventListener("submit", function(event){
console.log("test");
var name = form.elements['userinput'].value;
if(name.length < 3){
alert("boy your name is short!");
event.preventDefault();
}
});
Enter a name with less then 3 characters and the form will not be submitted. test here: http://jsfiddle.net/NicoO/c47cr/
Test it Serverside
In your mytarget.php:
<?
$username = $_POST['userinput'];
if(strlen($username) > 3)
echo "Your name is: ".$username;
else
echo "your name was too short!";
?>
You may also do all this with ajax. You will find a lot of good content here. But I'd recommend a framework like jQuery to do so.
The problem is in this line
<form id="form" name="input" method="post" action="javascript:proofLength();">
The action should be a PHP page (or any other type of server script) that will process the form.
Or the proofLength function must call submit() on the form
In the php page you can obtain variable values using $_GET["name"] or $_POST["name"]
To summarize; your code should look like this
<form id="form" name="input" method="post" action="yourpage.php">
<input id="userinput" type="text" autofocus />
<input id="submit" type="button" value="submit">
</form>
and for your php page:
<?php
$userinput = $_POST["userinput"];
//Do what ever you need here
?>
If you want to do something in your javascript before submitting the form, refer to this answer

Categories

Resources