I'm trying to upload an image without submit button. My code works fine for submiting without button.
My HTML code
<form name="service_image_form" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
Add new image <input name="userfile" type="file" id="userfile" onchange="return subForm()" />
</form>
<script>
function subForm() {
document.service_image_form.submit();
};
</script>
But I'm little confused in retriving data at PHP.
In php I tried something like this to retrieve data.
if (isset($_POST['service_image_form']))
{
echo "working";
}
Here I'm trying to echo "working" just for confirmation. If my condition works then then I can save my image to server and db. I know its very simple but stumbed here for a while. surfed lots of links, but no idea. Please help me out with this.
I know if I had a submit button with name="submit" then I can retrive like this
if(isset($_POST['submit']))
{
upload code comes here..
}
I dont wan't submit button..
To check if a post request is made:
if($_SERVER['REQUEST_METHOD']=='POST'){
echo "working";
}
Note that uploaded files data will be in the $_FILES superglobal, not $_POST, and as mentioned by Fred, you will need to add the enctype attribute on your form
You need to add enctype attribute into your for like this
<form name="myform" method="post" enctype="multipart/form-data" action="<?php echo $_SERVER['PHP_SELF']; ?>">
Add new image <input name="userfile" type="file" id="userfile" onchange="return subForm()" />
</form>
And in your php you get the uploaded files using the $_FILE
<?php
if ($_FILES['userfile']['error'] > 0) {
echo $_FILES['userfile']['error'];
} else {
echo 'Name: ' . $_FILES['userfile']['name'];
echo 'Temp file location in: ' . $_FILES['userfile']['tmp_name'];
}
?>
So basically you are trying to check if upload is correct, right? Well, it's not how it's done.
PHP has great manual for that http://php.net/manual/pl/features.file-upload.php
You miss:
correct form encoding, add attribute enctype="multipart/form-data" to your form tag
your file will be placed in $_FILES['userfile'] variable
you can check $_FILES['userfile']['error'] to determine if upload was successful (if so, it will be equal to constant UPLOAD_ERR_OK, 0)
After that you are good to go, you can find all the details here http://php.net/manual/pl/features.file-upload.post-method.php it's pretty straightforward.
Related
I currently have 2 forms, which adds data to my database. They both work, but they each have their own submit button - and I only want one submit button to collect the data from all the forms.
I found some javascript that should set the deal;
$("#submitbutton").click(function(){
$("#form1").submit();
$("#form2").submit();
});
The button I'm targetting is outside of both forms and looks like this:
<input id="submitbutton" type="button" value="add">
I'm pretty sure the reason why it doesn't work, is because of the way my php is written. I'm targetting the submit button in each form to excecute the php.
You can see the forms and php below.
One of the forms allows you to upload a picture;
<form id="form1" action="addimage.php" method="post" enctype="multipart/form-data">
<input type="file" name="image" />
<br/><br/>
<input type="submit" name="sumit" value="Upload" />
</form>
The action file contains this php;
<?php
if(isset($_POST['sumit']))
{
if(getimagesize($_FILES['image']['tmp_name'])== FALSE)
{
echo "Please select an image.";
}
else
{
$image= addslashes($_FILES['image']['tmp_name']);
$name= addslashes($_FILES['image']['name']);
$image= file_get_contents($image);
$image= base64_encode($image);
saveimage($name,$image);
}
}
displayimage();
function saveimage($name,$image)
{
$con=mysql_connect("localhost","root","");
mysql_select_db("ssdb",$con);
$qry="insert into pictures (name,image) values ('$name','$image')";
$result=mysql_query($qry,$con);
if($result)
{
//echo "<br/>Image uploaded.";
}
else
{
//echo "<br/>Image not uploaded.";
}
}
function displayimage()
{
$con=mysql_connect("localhost","root","");
mysql_select_db("ssdb",$con);
$qry="select * from pictures";
$result=mysql_query($qry,$con);
while($row = mysql_fetch_array($result))
{
echo '<img height="300" width="300" src="data:image;base64,'.$row[2].' "> ';
}
mysql_close($con);
}
?>
The other form lets you choose between multiple categories collected from my database;
<form id="form2" action="checkbox.php" method="post">
<label for="Category">Category</label>
<br />
<!-- iterate through the WHILE LOOP -->
<?php while($row = mysqli_fetch_array($result_category)): ?>
<!-- Echo out values {id} and {name} -->
<input type="checkbox" name="category[]" value=" <?php echo $row['id']; ?> "><?php echo $row['name'] . '<br />'; ?>
<?php endwhile; ?>
<input type="submit" name="Submit" value="Submit" class="btn btn-default"/>
</form>
And has the following php;
<?php
include("config.php");
$checkbox = $_POST['category'];
if($_POST["Submit"]=="Submit")
{
for ($i=0; $i<sizeof($checkbox);$i++) {
$query = "INSERT INTO placecategory (category_id) VALUES ('".$checkbox[$i]."')";
mysql_query($query) or die(mysql_error());
}
echo "Category is inserted";
}
?>
I've tried targetting the new button I made that should excecute the javascript, but it doesn't seem to work because that button is out of the form.
Is there a way to target the button outside of the form so the php excecutes when that is clicked? Or how can I rewrite this?
Any help is appreciated!
Not sure I understand completely what you're trying to do but try this with HTML5 add form="form1" and form="form2" for your second one and let me know if this works.
<form id="form1" action="addimage.php" method="post" enctype="multipart/form-data">
<input type="file" name="image" />
<br/><br/>
<input type="submit" name="sumit" value="Upload" />
</form>
<input type="submit" name="sumit" value="Upload" form="form1" />
Taking in account your complementary comment, then your proposed javascript sequence would work, assumed you have:
suppressed buttons such as <input type="submit"... /> from both forms
added the new button <button name="submitbutton">...</button> outside of the forms
modified the PHP parts accordingly, referencing $_POST['submitbutton'] instead of sumit and Submit respectively
You didn't report how it currently don't work, so the above steps target only the changes precisely related to the fact you replace two in-form buttons by a unique out-form one.
But something may turn wrong elsewhere. I notably noticed the non-usual way (at least for me) you get and process the image. Also you must ensure that your javascript part have really been executed.
Let me know if it doesn't work yet, than adding precise description of what turns wrong.
Edit, based on your provided comments and live preview.
Fully testing is not really possible because the server PHP part is out of reach, bue we can use Firebug to debug JS part.
So adding a breakpoint we can observe that, as soon as $("#form1").submit(); has been executed, the server returns a new page with the "Place has been added!" message.
In the other hand, without any breakpoint set, the server returns returns a new page with the "Categorie inserted!" message.
Though the OP didn't show the addingplace.php part of the current live preview, and comparing with the checkbox.php part, we can guess that:
In the reduced execution part, the first step addingplace.php did work as expected.
What we observe while whole execution merely means that all three parts have worked as expected, but each one having its returned message overwritten by the next one, but for the last one.
In other terms, when you comment "it only seems to submit the last form", this is a false impression based on what you only can see.
To ensure this is true or not you should control what is really updated or not in your database.
Let me know.
That said, it must be noted that this illustrates how the couple server-browser works in those circumstances: as already pointed by #David in a comment under the OP, to submit a form causes the browser to immediately receive a new page which overwrites the current one.
In the current example, it works because there are only few forms, and all three are submitted in a very reduced time, almost instantly: so the 3rd submit() can get executed before the 1st one's returned page comes.
So the recommended way to achieve the whole work in your example is merely to use only one form, with its unique submit button. BTW I wonder why you wanted to have this more complicated structure with three forms: what is the expected benefit?
Last point, outside of the precise issue you reported: you should pay attention to how you're coding. There is a lot of inconstencies in the HTML part, e.g.: a <html><body> part inside the already existing <body>; an exotic <br></br>; also you kept a supplemental button in the 1st form.
Basically I've got a form with 5 radio buttons. No submit button. I want the form to run when the user clicks on any of the radio buttons, so this is what I did.
<input id="5" type="radio" name="star" onchange="this.form.submit();" <?php if ($row["star"] =="5") echo "checked";?> value="5"/>
a querystring is required for the form so I'm using a form action like this
<form name="submit" action="http://example.com/page.php?id=<?php echo $urlid;?>&title=<?php echo $title;?>" method="POST">
and my php is
if ($_POST["submit"]) {
$rating = $_POST['star'];
$title = $_GET['title'];
$verification = ($_GET['verification']);
} else {
//run the page like usual
}
After testing, I found that onclick, it runs the form action, but on the php side, it goes to "else" where is runs the page like usual instead. Any ideas?
Your PHP is checking if $_POST['submit'] contains a value. Your form does not contain a form element with the attribute name="submit", so therefore it fails and moves straight to the else statement.
If you want to check if the form was posted then you should instead check for:
if (!empty($_POST)) {}
or
if ($_SERVER['REQUEST_METHOD'] == 'POST') {}
The form element seems to have invalid attributes, missing a quote and space.
It's generally easier to write a little more code, and keep it clearer
<?php
$url = "http://example.com/page.php?id=". $urlid ."&title=". $title;
?>
<form name="submit" action="<?php echo $url; ?>" method="POST">
Since you are checking with -
if ($_POST["submit"]) { // this checks whether there is any item named 'submit' inside the POST or not
} else {
//run the page like usual
}
The easiest would be to put a hidden item with name submit so that the check validates to true-
<form .. >
....
<input type='hidden' name='submit' value='submit' />
</form>
I have spent way too much time on this and browsed various questions/answers here on stackoverflow.
I am using dropzone.js to add a basic drag and drop upload feature to our HTML/PHP form. The drag and drop is working great however when the form is submitted or a file is uploaded the $_FILES returns empty and I cant figure it out.
I checked a tutorial and no luck, also checked some Q & A's from stackoverflow before posting here but nothing has helped.
Here is the form in its simplest form:
<form action="<? echo BASE_URL; ?>/process-uploads.php" method="POST" class="form-signin" role="form" enctype="multipart/form-data">
<div class="upload_container dropzone">Drag & drop file here or
<div class="fallback">
<input name="ad" type="file" />
</div>
</div><!--fileUpload btn btn-primary-->
<div class="dropzone-previews"></div>
<input class="btn btn-lg btn-primary btn-block btn-forward" style="background:#00a85a;" type="submit" name="submit" value="Next Step" />
</form>
The JS is:
<script type="text/javascript">
var myDropzone = new Dropzone(".dropzone", {
url: "<? echo BASE_URL; ?>/process-uploads.php/",
paramName: "ad",
addRemoveLinks: true,
//maxFiles: 1,
autoProcessQueue: false,
//uploadMultiple: false,
acceptedFiles: "image/png",
dictInvalidFileType: "This file type is not supported.",
});
</script>
And process-upload.php just checks to see if anything was sent, but returning empty:
<?php
if (!empty($_FILES)) {
echo 'We have a file';
if($_FILES['ad']) {
echo 'We grabbed the ad<br />';
echo '<pre>';
var_dump($_FILES);
echo '</pre>';
}
}
?>
Any help would be greatly appreciated. For reference I already checked enyo's tutorial for combining a form with dropzone and php
I had the same issue today getting no response, no error whatsoever when uploading a file and search through all SO questions, i read your code couple of time but no solution.
i later found out that post_max_size = 8M is set too small, large files cannot be uploaded. Make sure you set post_max_size large enough, so kindly create/add this to your .htaccess file, i needed to upload a file of 2gb
php_value upload_max_filesize 2047M
php_value post_max_size 2047M
php_value max_execution_time 10800
You need to add name to your field:
<input type="file" name="ad" />
I think you took reference of this article...
Dropzone Demo
Can you please add class 'dropzone' to your form like following and try
<form action="<? echo BASE_URL; ?>/process-uploads.php" method="POST" class="dropzone form-signin" role="form" enctype="multipart/form-data">
I have an image upload script that works well on its own but fails when I try to run in via a PHP function that I was hoping would just keep the PHP file in the DIV
function Upload()
{
print'<div>';
include('../a/multi-image_uploader_thumbnail_creator.php');
print'</div>';
}
The PHP file runs well but once a user submits it leaves the PP function completely. The form code is:
while($i++ < $upload_image_limit){
$form_img .= '<label>Image '.$i.': </label> <input type="file" name="uplimg'.$i.'"><br />';
}
$htmo .= '
<p>'.$feedback.'</p>
<form method="post" enctype="multipart/form-data">
'.$form_img.' <br />
<input type="submit" value="Upload Images!" style="margin-left: 50px;" />
</form>
';
echo $htmo;
Your include() statement is outside of PHP. You shouldn't be ?> and <?phping around it. It's a PHP function.
Also, why are you using .= if you didn't define the variable before? You can just use =.
You should consider using templates, too, but that's a bit further down the road.
Edit: Try looking at the answer to this question or this other question to send images via AJAX.
I have a form to post content into a database. The existing database content for the form is posted into the form as the value. enalbeing the form to show the existing database content.
On submit the database is updated and to view the newly updated content in the form the page must be reloaded.
I have produced a reload script in javascript to reload the page on submit. The page reloads but the php content doesn't update. The page still need to be reloaded manually for the new content to show up.
This is the code for my form.
<form method="POST" action="">
<input type="text" name="title" <?php echo "value=\"" .$row['title']."\">"?>
<textarea id="editor" name="content"><?php echo $row['content']; ?></textarea>
<input type="submit" name="save" value="Save" class="submit" onclick="reload();">
</form>
Javascript
function reload(){
document.location.reload(true);
}
I have also tried
window.location = window.location.href;
Both are relaoding the page but the php isn't being refreshed.
you should first update the db with submitted value before selecting the records to display in the form value.
use <?php $_SERVER['PHP_SELF'] ?> in form action.
mysql_query("UPDATE xyz SET title=$_request['title'],... WHERE id = 1") .
2.Then select query mysql_query("SELECT * from xxx where id =1").
These may solve your problem of reloading to get new values.
java script excecute only on the client side. php is Server side. you need to reload the PHP.
<form method="POST" action="<<NAME OF YOUR PHP>>.php">
<input type="text" name="title" <?php echo "value=\"" .$row['title']."\">"?>
<textarea id="editor" name="content"><?php echo $row['content']; ?></textarea>
<input type="submit" name="save" value="Save" class="submit" onclick="reload();">
</form>
Is there a reason it needs to be done with ajax? If you don't need ajax it's better to handle it with php. ajax is more work and doesn't have the same rate of success as submitting a form via php, sometimes weird things happen. You can just do a redirect after saving the form:
header("Location: /routeToYourPage&id=".$ID,TRUE,303);