I know this question has been asked before, but I'm trying to diagnose why this isn't working. I want to write form data into a .txt file using a post request. I don't know much PHP at all, as this is a quick program I'm patching together. Here's the code:
Javascript:
function submitdata() {
document.querySelector("#val").innerHTML = input.value + ": " + input1.value;
document.querySelector("#submitform").submit(); }
HTML:
<form style="display: none;" method="POST" name="myform" id="submitform">
<input id="val" name="val">
</form>
PHP:
<?php
if(isset($_POST['val']))
{
$data=$_POST['val'];
$fp = fopen('data.txt', 'a+');
fwrite($fp, $data);
fclose($fp);
}
?>
How does your browser know where to send the form data?
You need to specify the php file name in form action attribute.
Edit- added relevant point from comment below.
I have pointed out the obvious error based on what you have provided, but it might not be the only one. Other error is you are using innerHTML on an input element. So this may not set the value for #val (some browsers may set the value, some may not).
Related
i want to capture input variables sent via form from one page to another.html page and obtain these values as JavaScript variables. Can this be done.
This is my form;
<form action='another.html' id='form' data-ajax='false'>
<input id='sent_by' value='tom'/>
<input type='submit' value='Submit'/>
</form>
And in my another.html i tried to get the values as;
var sent_by = $.session.get("sent_by");
But i am not able to get the values. All help is appreciated.
You can use the browser's localStorage to achieve this. Before submitting and going to the other page store all the values of the form in the localStorage and you can access it on the other page:
Page1.html
Field Name = "name" <input type="text" name="name" id="name" />
Read the value and store it to localStorage
localStorage.setItem('name', document.getElementById('name').value);
and so on.
You can make a function in JavaScript that saves all the fields of the form in localStorage on / before submit.
To read these values on the other page:
Page2.html
Value stored for key name can be get using the following JavaScript:
localStorage.getItem("name");
NOTE
the page1.html and page2.html should be in the same domain for you to access the localStorage.
Read more about localstorage at https://developer.mozilla.org/en-US/docs/Web/API/Storage/LocalStorage
Have you tried using Window.localStorage? It's similar to sessionStorage but with no expiration date. So, be sure to clear it once the browsing session ends.
I think the answer provided by #Shakti Phartiyal is probably the most practical and a sweet trick I might add. The main reason I'm writing this post is because I had also taken a long path of using javascript to pass along this kind of information. It resulted in me bewildered at how powerful PHP can be for some tasks that you dedicated javascript to do. (Yea I know some javascript wizards out there can do everything with it, I'm just talking about basic programming tho). So if you wondered what the PHP way of passing this around:
Your modified html form:
<form action='another.html' id='form' data-ajax='false' method='post'>
<input id='sent_by' value='tom' name='uname'/>
<input type='submit' value='Submit'/>
</form>
and then in "another.php" you would have this to retrieve the input from the form:
<?php
$uname= htmlspecialchars($_POST['uname'];
?>
Great. But how to make this php variable into javascript?
Ah, the fun part. You're going to write javascript to your webpage with php - you do something like this:
var uname = "<?php echo $uname; ?>";
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
Trying to allow file upload along with a form that is otherwise working. I cut out the relevant form/input/processing rules. Hopefully someone who is more than ankle-deep in PHP (as I am) can point me in the right direction?
<form name="form-quote" id="form-quote" enctype="multipart/form-data" action="<?php echo $_SERVER['../WPTheme/REQUEST_URI' . '#form-quote'] ?>" method="POST">
<div class="form_labels">
<p><label for="fileupload">Upload File (optional):</label></p>
</div>
<div class="form_inputs">
<input type="hidden" name="MAX_FILE_SIZE" value="5242880" />
<p><input type="file" name="fileupload" id="fileupload" accept=".pdf, .txt, .rtf, .doc, .docx, .xls, .xlsx" style="margin-bottom:2px;"/>
<span style="color:#777;">(pdf, txt, rtf, doc, docx, xls, xlsx, <5MB)</span></p>
</div>
<input type="hidden" name="formtype" id="formtype-quote" value="quote">
<div class="form_labels submit">
<p> </p>
</div>
<div class="form_inputs">
<input type="submit" value="Submit" name="action" class="btn-red" >
</div>
</form>
<?php
//$formerrors is set to false unless one of the validation rules for the OTHER fields fails - no validation on the file upload, although I would like to trim & sanitize it if possible.
if (!($formerrors) && isset($_POST['fileupload'])):
$tmp_name = $_FILES["fileupload"]["temp_name"];
$uploadfilename = $_FILES["fileupload"]["name"];
$savedate = date("mdy-Hms");
$newfilename = "/wp-content/uploads_forms/" . $savedate . "_" . $uploadfilename;
$uploadurl = 'http://' . $_SERVER['SERVER_NAME'] . $newfilename;
if (move_uploaded_file($tmp_name, $newfilename)):
$msg = "File uploaded.";
else:
$msg = "Sorry, your file could not be uploaded." . $_FILES['file']['error'];
$formerrors = true;
endif; //move uploaded file
endif;
?>
Thanks to Alexander's answer below, I was able to modify my validator to work and to achieve my original goals (check for null, and give files unique names before uploading). Here's my "final draft," which is working now.
//Check form errors, check file name not null, rename file with unique identifier to avoid overwriting existing files with same name
if (!($formerrors)) {
$tmp_file = $_FILES["fileupload"]["tmp_name"];
if ($tmp_file != "") {
$savedate = date("mdy-Hms");
$target_dir = "wp-content/uploads/";
$target_file = $target_dir . $savedate . '_' . $_FILES["fileupload"]["name"];
if (move_uploaded_file($tmp_file, $target_file)) {
$msg = "File uploaded.";
} else {
$msg = "Sorry, your file could not be uploaded.";
$formerrors = true;
}//move successful
}//end null check
}//end form errors check
The code you are using above is Javascript. In case you depend on that please change the tags of the post. If not here is a possibility for a PHP-Uploadscript:
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileupload"]["name"]);
if (move_uploaded_file($_FILES["fileupload"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["fileupload"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
SOURCE: http://www.w3schools.com/php/php_file_upload.asp
EDIT: The script above has be placed in the file receiving the POST from the form.
The code you posted is a big mess!
Let's try to clarify some basic points...
File-upload mechanism
For file-upload to work you must have a <form> with action attribute addressing the script where you'll check and use the uploaded file.
This script may be the same as the one where the <form> is generated, assumed you take care of the pitfalls that come with this situation.
At a first general glance your current code seems to correspond to the latter case.
But your form action looks weird:
action="<?php echo $_SERVER['../WPTheme/REQUEST_URI' . '#form-quote'] ?>"
As a first intent, if you want to address the same page where you already are, you can simply omit action attribute.
Here you seem to explicitely try the same, adding the precision of #form-quote, but:
This #form-quote has no effect here, since such a hash is made to target a <a>, while it's currently affected to your <form>.
The other part of the url you build is a non-sense mixing REQUEST_URI (which is the name of one of the $_SERVER members) with the hard-core expression of a path in your context.
Anyway all the above doesn't matter, because this end with $_SERVER[...something which is not a known $_SERVER member...], so it actually returns NULL, and somewhat ironically it has the same effect as if you didn't specify action at all!
PHP in a SO snippet
So ou put your code in a snippet, but SO snippets work only with HTML, CSS, and Javascript, so you can't expect it allows to demonstrate how your code is working or not.
Note that at this step, despite the errors mentioned above, we didn't point something which would make your code to fail.
And in your question you didn't mention how it fails!
Uploaded file processing
So looking at your PHP code part, I first note this statement:
$tmp_name = $_FILES["fileupload"]["temp_name"];
where you're looking for temp_name, while the true involved key is tmp_name. This alone is enough to make your code to fail.
Furthermore looking at these two statements:
$uploadurl = 'http://' . $_SERVER['SERVER_NAME'] . $newfilename;
if (move_uploaded_file($tmp_name, $newfilename))
In the 1st one you use $newfilename as the complement of the url you're building, so obviously $newfilename can't target an absolute physical path.
It means that in the 2nd one you try to move_uploaded_file() to a wrong place!
Last point, you currently don't take care of possible errors before trying to use the uploaded file.
You should complete your primary condition like this:
if (!($formerrors) && isset($_POST['fileupload'])) && !$_FILES["fileupload"]["error"])
And if you effectively get some errors and have trouble to understand why, you should also look at this interesting PHP manual page.
I did also creating a different class. but still not working...
but if I place the '<script>console.log("message here");</script>' will work..
//index.html
assuming that this is a complete code.
<form action="post.php" method="post">
<input type="text" name="name" id="name"/>
<input type="submit" value="submit"/>
</form>
//post.php
<?PHP
if(isset($_POST['name'])){
echo "<script>console.log('".$_POST['name']."');</script>";
}
?>
my problem is , i cant use console.log in submitting a form. but if I did this in redirection It will work..
The Function under my class is ...
public function console($data) {
if(is_array($data) || is_object($data)) {
echo("<script>console.log('".json_encode($data)."');</script>");
} else {
echo("<script>console.log('".$data."');</script>");
}
}
It does not work within PHP because of the missing " around the String argument of console.log.
The output would've been
<script>console.log(name);</script>
instead of
<script>console.log("name");</script>
Solution
echo '<script>console.log("'.$_POST['name'].'");</script>';
If you are trying to debug or see the value that was posted from the front end to back end then you can simply use the chrome inspector.
Right click anywhere in browser and click inspect element.
click on network tab.
submit your form with desired values.
on the left click on the post.php.
Click on the headers on the right and scroll down to find Form Data.
You will have all your post variables listed there with respective values.
You seem to be trying to debug the $_POST variable, If thats the case, then Please note, that console.log() is a frontend debugging tool used in javascript, and has nothing to do with php.
Few good way of checking the content of variables in php.
1. print_r
This will output the content of a variable that can be an array, object or string in a nice human readable format.
echo '<pre>';
print_r($_POST);
echo '</pre>';
die();
2. var_dump
This will output the content of the variable with extra respective details like datatypes and length.
var_dump($_POST);
die();
Ok I am confused with php, javascript and html and dont know what to do. On researching on the internet, i found js is client side and php is server side. when a php file is run on the browser, it converts everything into html and the page is loaded. Now let me tell you guys what i am doing.
I have a php file that give me some stats from a particular url (in the sample i am just showing url)
<?
$url="www.example.com";
echo "URL = " .$url;
?>
Result URL = www.example.com
The above code echoes the url which is www.example.com. I added a textbox to this code which i believe is javascript+html
<script>
function myFunction() {
$url=myurl.value;
}
</script>
<input type="text" name="myurl" id="myurl">
<input onclick="myFunction()" type="submit" name="btnurl" id="btnurl" value="Submit">
<br><br>
<?
$url="www.example.com";
echo "URL = " .$url;
?>
Here the result is same. only difference is that it has a textbox and button above the result.
When I enter another url in the textbox and press submit, it does nothing probably because the page is already loaded. I want to replace the result of www.example.com to the one which is entered in the textbox without changing the .php file. There will always be a default url in the .php file. whenever the file is opened in the browser, the default statistics will be shown... only when the user enters new url and clicks submit, the stats should change.
How can I achieve this? I am behind this since more than a couple of hours now and not sure how to get this done. Please help me.... Thank you.
EDIT
Can I have two .php files? one for the user to enter url and submit and another one to get the entered url and echo it? If yes, how? If I understand this logic, i can get a start for what I am doing.
I think you are trying to do more with your js function, but syntactically it is combining js and php. It should look like this
function myFunction() {
var url = document.getElementById('myurl').value;
}
Although this doesn't really do anything other then assign the content of the text box to a variable.
EDIT
<script>
function myFunction() {
document.getElementById('url').innerHTML = document.getElementById('myurl').value;
}
</script>
<input type="text" name="myurl" id="myurl">
<input onclick="myFunction()" type="submit" name="btnurl" id="btnurl" value="Submit">
<br><br>
<? $url = "www.example.com"; ?>
URL = <span id="url"><?= $url; ?></span>
natzim is correct if you are wanting to write the url back to the php file. If you use javascript to change the action of the form, it will submit to a different page.
//javascript
function myFunction() {
//this should change the page that loads after submit.
//If you want to go to a new page that the user enters, leave this code in...
//If not, remove it
document.getElementsByTagName("form")[0].action = document.getElementById("myUrl").value;
}
That is assuming you have a form tag somewhere (which you will need to submit the page). Also I am not sure this code will run if you use a submit and not a button. If you used a button instead you could append this to the code above to submit the form:
//This would be part of your myFunction if you used a button instead of a submit input
document.getElementsByTagName("form")[0].submit();
as per my comment -
this code is your old php:
<?
$url="www.example.com";
echo "URL = " .$url;
?>
and this is the php I suggested:
<?php
$url=isset($_POST['myurl']) ? $_POST['myurl'] : 'www.example.com';
echo "URL = " .$url;
?>
this would check the myurl input from that was submitted to the server and set the value of $url to its value if it existed then the $url variable would be echoed to the page under the inputs.
This code is assuming you are using the POST method rather than the GET method when your form was submitted.
**EDIT: **
To clarify - here is your page with the modifications I am suggesting. (Please ignore the javascript above as it seems you will not need it):
<form action='www.example.com' method='post'>
<input type="text" name="myurl" id="myurl">
<input type="submit" name="btnurl" id="btnurl" value="Submit">
<br><br>
<?php
$url=isset($_POST['myurl']) ? $_POST['myurl'] : 'www.example.com';
echo "URL = " .$url;
?>
</form>
I trying to store CSV data to database using onclick function. Unfortunately, I am using php code inside javascript function which is not efficient enough. Therefore, I hope that I can get any suggest or solution to improve efficiency of my project by using javascript instead of php to store CSV data into database.
This is javascript with php code :
<script>
function storeQueEmail(){
<?php
$file = $_FILES[csv][tmp_name];
$handle = fopen($file,"r");
//loop through the csv file and insert into database
do {
if ($data[0]) {
$record['contact_first'] = $data[0];
$record['contact_last'] = $data[1];
$record['contact_email'] = $data[2];
$record['subject'] = $_REQUEST['subject'];
$record['message'] = $_REQUEST['message'];
$record['status'] = 0;
$oAdminEmail->insertQueEmail($record);
}
} while ($data = fgetcsv($handle,1000,",","'"));
?>
}
</script>
This is HTML code :
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Import a CSV File with PHP & MySQL</title>
</head>
<body>
<form action="" method="post" enctype="multipart/form-data" name="form1" id="form1" >
Subject : <br/>
<input type="text" name="subject" id="subject" required/> <br/>
Choose your upload type: <br />
<input name="csv" type="file" id="csv" accept=".csv" required/> <br/>
Content : <br/>
<textarea name="message" cols="50" rows="10" required></textarea><br/>
<input type="submit" name="submit" value="Submit" onclick="storeQueEmail()"/>
</form>
</body>
</html>
what are you trying to do there? I think you are speaking about a PHP in
HTML document. So your PHP code inside your function is interpreted on server. As your PHP code has no output your Javascript function is simply empty. Thus as you have registered your Javascript function as onclick handler just nothing would happen.
Remember that standard Javascript code is interpreted on Client (that means in browser) though you PHP code is interpreted on server. As mentioned in the comments above it is possible to use an AJAX or POST/GET - Request to send data to your server and then write it to your DB or file etc.
Another way to do this directly with Javascript is Node.js - serverside Javascript that is able to write to your Database like PHP can do.
The easiest way for you to do it with your HTML code you presented above is to fill in your
action - attribute
in your
form tag
For example:
<form action="proccessData.php" ...>
...
</form>
Don't forget to remove your onclick - attribute inside form's submit input field.
If you know press your submit button your entire form and its content will be send to http://www.xyz.de/proccessData.php. Inside that file you can work with your form data: In your case two text fields and one file upload field. As you may know you could get to the content of text input field send via post via:
$_POST['<name of field>']
To get your uploaded file and proccess it you could use PHP's global
$_FILE[] - Array
Just refer to PHP's manual on php.net or some other online documentation. There's pretty much to find on the web.
I just give you a helpful link to php.net on how to handle file uploads in a correct and therefor secure manner: http://us2.php.net/manual/en/features.file-upload.php
Once you have read your uploaded file via PHP's global $_FILE[] - array just proccess that file via fgetcsv in your proccessData.php and write it line for line to your database.
Hope that helps! It is really not that hard :)