Hello I would like to upload some images to my server. It works when I'm not loading the page with ajax.load into another page. So with a direct link to it it works fine. But I would like to click on a link, open the upload form and upload the picture (all in one window). Is this because the page is refreshing before uploading or is it another problem? don't know how to solve this.
code:
<?php
include('includes/connect.php');
if(isset($_POST['uploadImg'])){
$extension = end(explode(".", $_FILES["file"]["name"]));
$name = $_FILES["file"]["name"];
if (file_exists("upload/" . $_FILES["file"]["name"]))
{
mysql_query("INSERT INTO images (itemID,imgPath,imgName,imgExtension,imgAlt) VALUES (".$_POST['itemNumber'].",'upload','".$name."','".$extension."','".$name."')")or die('kan niet uploaden'.mysql_error());
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],
"upload/" . $_FILES["file"]["name"]);
echo "Uw afbeelding is toegevoegd aan item".$_POST['itemNumber'];
echo "<a id='uploadNew' href='#'>Nog een item uploaden</a>";
}
mysql_query("INSERT INTO images (itemID,imgPath,imgName,imgExtension,imgAlt) VALUES (".$_POST['itemNumber'].",'upload','".$name."','".$extension."','".$name."')")or die('kan niet uploaden'.mysql_error());
}
?>
<form method="post" enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file" />
Toevoegen aan:
<select name="itemNumber">
<?
$result = mysql_query("SELECT * FROM items");
while($row = mysql_fetch_array($result))
{
echo '<option name="itemVal" value="'.$row['itemID'].'">'.$row['itemTitle'].'</option>';
echo "<br />";
}
?>
</select>
<input type="submit" name="uploadImg" value="submit" />
</form>
The problem comes from the fact that the form is sent to the parent page before the AJAX is loaded. The Partial page that you posted is retrieved through a second HTTP request and doesn't have any POST parameters set.
Your best bet would be to add the php script in the parent page from which the AJAX is loaded. Also specify a "target" attribute in your form element so you keep track of which server page is handling the request.
ajax not directly upload your image, you should have to use some plugin to upload the image,
Previous i have used this plugin (ajax.form) to instant image upload.
follow the link, in this link a simple example that how to use this plugin and upload an image.. http://blog.webtech11.com/2012/03/18/ajax-based-instant-image-upload.html
Related
I'm using Form-Submit(website for sent message to gmail without back-end) and File upload. is it possible to upload multiple attachment at a time in form-submit
Please help me i am using html form....And I want to know...It's working or not if yes ...How can I upload or send multiple attachment through form-submit cause single file already working....And I am also use the files attribute in file attribute place....But it's only select the multiple times file not sent in my mail ...Only sent one attachment at a time....Hlp me
The following code is a very basic mechanism of uploading files. Nowadays there are more advanced libraries that you have to search for.
<?php
if(isset($_POST['upload'])){
$numberOfFiles = sizeof($_FILES["song"]["name"]);
echo "<br>Number of selected files: ".$numberOfFiles.'<br>';
for($i=0; $i<$numberOfFiles; $i++){
$tempName = $_FILES['song']['tmp_name'][$i];
$desPath = realpath(dirname(__FILE__))."/" . $_FILES['song']['name'][$i];
if (file_exists(realpath(dirname(__FILE__))."/" . $_FILES['song']['name'][$i]))
{
echo $_FILES['file']['name'] . " already exists. ";
}
if(!move_uploaded_file($tempName, $desPath))
{
echo "File can't be uploaded";
}
}
}
?>
<form method="post" action="<?php echo 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; ?>" enctype="multipart/form-data">
<input type="file" multiple="multiple" name="song[]" accept="audio/mpeg3"><br></br>
<div class="uploadbtn" align="center">
<input type="submit" name="upload" value="Upload"></div>
</form>
I hope it helps.
this is a normal HTML method of attaching a file.
form enctype=<"multipart/form-data" action="savefile.php" method="POST" name="myform">
Send this file:
input name="myfile" type="file" onchange="document.forms['myform'].submit() ;"
</form>
savefile.php
move_uploaded_file($_FILES["myfile"]["tmp_name"],
"upload/" . $_FILES["myfile"]["name"]);
echo "Stored in: " . "upload/" . $_FILES["myfile"]["name"];
it works perfectly, my difficulty is that when I attach a file and it sends when I refresh the page, the file I attached still remains in the attachment, how can I clear it so it shows "No chosen file"
You need to redirect the user with
header("Location: yourpage.php");
Also, submitting your form that way might not work on every browser.
<input name="myfile" type="file" onchange="document.forms['myform'].submit() ;" />
And JAVASCRIPT
var myInput = $("#input[name='myfile']");
function resetInput(){
myInput.replaceWith( myInput.val('').clone( true ) );
};
Call resetInput() after the upload.
Ripped and adapted From this thread
I want to view data stored in an uploading session but all I get is 'Null', am I going about this the wrong way?
session_start();
if(isset($_POST['submit'])){
$target = "test/";
$target = $target . basename('test') ;
$file = ($_FILES["uploaded"]["name"]);
$key = ini_get("session.upload_progress.prefix") . $_POST[ini_get("session.upload_progress.name")];
var_dump($_SESSION[$key]);
if(move_uploaded_file($_FILES['uploaded']['tmp_name'], $target)){echo "done";}else echo "error";
}
and the html:
<form action="upload.php" method="POST" enctype="multipart/form-data">
<input type="hidden" name="<?php echo ini_get("session.upload_progress.name"); ?>" value="test" />
<input type="file" name="uploaded" />
<input type="submit" name='submit' />
</form>
You're trying to get upload progress status when upload is already done.
If you want to make it working, then you can for example send your form to iframe and during the upload ask server, using ajax, what is the status.
I would suggest to use it rather as a fallback for older browsers cause currently browsers are supporting ajax upload and you can display upload progress without making additional requests to server and creating some strange hidden iframes ;)
I'm trying to post form data through ajax
form1.php
I use request to get all URL parameter data
$_REQUEST["Ename"];
$_REQUEST["eImg"];
To upload the image,i use this code http://www.9lessons.info/2011/08/ajax-image-upload-without-refreshing.html
In the above link,you can see the source code,in the place of $_FILES['photoimg']['name'];,i use $_FILES['image']['name']; but it is not uploading the file and giving success message.
include('db.php');
session_start();
$session_id='1'; // User session id
$path = "uploads/";
I removed script that is marked with **
$valid_formats = array("jpg", "png", "gif", "bmp","jpeg");
**if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
{**
$name = $_FILES['image']['name'];
$size = $_FILES['image']['size'];
if(strlen($name)) {
list($txt, $ext) = explode(".", $name);
if(in_array($ext,$valid_formats)) {
if($size<(1024*1024)) { // Image size max 1 Mb
$actual_image_name = time().$session_id.".".$ext;
$tmp = $_FILES['image']['tmp_name'];
if(move_uploaded_file($tmp, $path.$actual_image_name)) {
mysql_query("UPDATE users SET profile_image='$actual_image_name' WHERE uid='$session_id'");
echo "<img src='uploads/".$actual_image_name."' class='preview'>";
} else {
echo "failed";
}
} else {
echo "Image file size max 1 MB";
}
} else {
echo "Invalid file format..";
}
} **else {
echo "Please select image..!";
exit();
}**
you simply can't upload files via $.ajax().
you'll have to use some trycky iframe-stuff or something like that to make this work. luckily, there are ready-to-go plugins for jquery to handle this for you (like $.ajaxForm() for example wich seems to be the one that's used in the tutorial you're reading).
EDIT:
the plugin also allows to add extra data thats not present in the form itself. to quote the documentation:
data
An object containing extra data that should be submitted along with the form.
data: { key1: 'value1', key2: 'value2' }
For upload image by ajax you should use an iframe and set its id to form target.
Please have a look at
http://www.coursesweb.net/ajax/upload-images
It is very simple code to upload image
That won't work!
Images are handled differently from the text data in Ajax so you would have to do more than just post it using the $.ajax({}) method.
You can however use the jquery.form.js plugin it works perfect http://jquery.malsup.com/form/#download there is a tutorial on how to use it
here
Any ways I have used it my self so let me elaborate for you.
The JavaScript code is here
$('.uploadForm').live('click', function(evt){
$('#feedback').html(' ');
$('#feedback').html('<img src="images/loader_image.gif" alt="Uploading...."/>');
$("#formID").ajaxForm({
target: '#feedback'
}).submit();
evt.preventDefault();
});
If your PHP code is fine this should work .....
Just post the rest of the form fields in the normal way way
This should work for you. If the PHP code is fine
For example if you had other form fields like firstname and lastname in form like this one
<div class="form">
<fieldset class="ui-corner-all">
<h3 class="ui-widget-header ui-corner-top" align="center">Client information</h3>
<form action="save_new_client.php" enctype="multipart/form-data" id="clientForm" method="POST">
<label>First Name</label>
<input name="firstname" type="text" id="firstname" class="required" minlength="3"/>
<label>Lastname</label>
<input name="date_added" type="text" id="date_added" class="dateEst" />
<label>Image</label>
<input name="photo" type="file" id="photo" />
<input type="submit" name="button" id="button" value="Save" class="uploadForm"/>
<input type="reset" name="reset" id="button" value="Cancel" /></td>
</form>
</fieldset>
<div id="feedback"></div>
</div>
Below it you'll just need to add a div or paragraph to hold your feedback message ....
then the rest will be just fine (like I said if your PHP code is okay)I have not looked through it alot
Let me explain what i am hope to acomplish:
I want to allow my users to upload a image as avatar.
I found many php upload tutorials but i don't know hoy to upload the avatars as user_id.ext in /avatars folder.
I hope i was clear, thanks.
In any upload script, you go through a few basic steps. First, you get data from $_FILES telling you where the temporary upload file is. You validate the file based on something to make sure it's not evil/malicious/wrong. Then you rename it and move it somewhere useful. In your last step, when you move the image to where it's going, take that opportunity to name the file as you like. If you're dealing with a user's account it should be trivial to get the username, id, middle name, etc and use that to set the file's name.
This script gets the uploaded file and save it as /avatars/$user_id.ext, $user_id retrieved from POST:
<?php
if ($_FILES["file"]["error"] > 0) {
echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
} else {
move_uploaded_file($_FILES["file"]["tmp_name"], "/avatar/{$_POST['user_id']}.ext");
echo "Stored in: " . "/avatar/{$_POST['user_id']}.ext";
}
?>
And this is the form:
<form method="POST" enctype="multipart/form-data">
<input type="file" name="file">
<input type="hidden" name="user_id" value="<?php echo $user_id ?>">
<input type="submit" value="submit"></form>