ajaxForm unable to POST file - php

What I'm trying to do
I have a form which is posted via ajaxForm. The form contains a file input field, however the data isn't being processed with the rest of the information in the POST.
The code
HTML Form
<form id="profilepicForm" action="user/profilepic.php" method="post" enctype="multipart/form-data">
<input type="file" accept="image/gif, image/jpeg, image/png" name="file" />
<input type="hidden" name="userid" value="<?php echo $_SESSION['user']['id'] ?>" />
<input type="submit" value="Upload">
</form>
Javascript
var options = {
complete: function(response) {
$("#profilepicMessage").html(response.responseText);
},
error: function(){
$("#profilepicMessage").html("ERROR: unable to upload file");
}
};
$("#profilepicForm").ajaxForm(options);
PHP
$user_id = $_POST['userid'];
$image = $_FILES['file']['name'];
print_r($_POST);
exit;
What's happening
All that comes through is Array ( [userid] => 34 ), where 34 is my particular userid. Therefore I know that the form is being posted, but the file is not going through.

You should look at global variable $_FILES.

You'll have to look for something like uploadifive to manage that, for ajax can't currently handle file transfers
(this is not entirely true, there is ajax2 and html5 file api, but save yourself a problem, look for uploadifive).

Related

POST request shows no visible value

I have recently been working on a project that uses a bit of PHP. I don't know whether my question is obvious to those who have loads of experience, but here goes.
I don't know how to get a response from an upload PHP I created. If I have a form, like so...
<!DOCTYPE html>
<html>
<body>
<form action="upload.php" method="POST" enctype="multipart/form-data">
<label>Select image to upload:</label>
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
</body>
</html>
...and I have a PHP script that uploads these images to Cloudinary...
<?php
// Cloudinary init
require 'Cloudinary.php';
require 'Uploader.php';
require 'Api.php';
\Cloudinary::config(array(
"cloud_name" => "(cloud name)",
"api_key" => "(my key)",
"api_secret" => "(secret here)"
));
// Uploads images to Cloudinary
\Cloudinary\Uploader::upload($_FILES["fileToUpload"]["tmp_name"]);
?>
...how can I make it so that when submitted, it adds the value of the photo's URL (which is stored in a hash) to a hidden input in another form? Thanks so much.
P.S. Sorry for asking such n00b-y questions! (I'm new here)
First, make sure the session has been started. This allows you to send data over the server with post and files.
session_start()
Then you can access your inputs by name using the post and file functions.
# form.php
<?php session_start() ?>
<form action="after_form.php" method="POST" enctype="multipart/form-data">
<input type="text" name="text-input" value="Moon Text" />
<input type="hidden" name="some-input" value="xyyz" />
<input type="submit" />
</form>
Then on your next page, once the form has been submitted,
# after_form.php
echo $_POST['text-input']; //prints "Moon Text"
echo $_POST['some-input']; //prints "xyyz"
Usually you would save these data somewhere though.
If on this same after_form.php page you have a new hidden input, you could do something like
<input type="hidden" name="file-path" <?php echo 'value="'.$_POST['data'].'"';?> />

How to save multiple values from input form fields to JS variable?

I am using plupload to upload image files. My goal is to save the name of the uploaded thumb_nail files to a session, in case user leaves page or an submit error happens.
Plupload creates file_names in this manner:
<div id="files">
<input type="hidden" id="p1adsfucka1h0p1s0624cauu623" name="files[]" value="p1adsfucka1h0p1s0624cauu623.jpg">
<input type="hidden" id="p1adsfucka1h0p1s0624cauu624" name="files[]" value="p1adsfucka1h0p1s0624cauu623.jpg">
</div>
from plupload functions I want to call this function:
function autosave_form_cl(session_name){
console.log($("input[name=files").val() + $('#title').val());
$.post("/act_autosave_formdata.php", {
session_name:session_name,
cellphone: $('#cellphone').val(),
files: $("input[name=files").val()
} );
}
This returns an undefined for the value of the file fields. How could I access and save those names? Submitting and saving the values to a session works by accessing $_POST.
Collect all [name=files] first then pass it to your $.post.
I assume what's inside <div id="files"> is all inputs with [name=files]
function autosave_form_cl(session_name){
//console.log($("input[name=files]").val() + $('#title').val());
files = [];
$('div#id').find('input').each(function(i,inp){
files.push($(inp).val());
});
console.log(files);
$.post("/act_autosave_formdata.php", {
session_name:session_name,
cellphone: $('#cellphone').val(),
files: files
} );
}
Let me know if it works.

Unable to Get Text Input from Form

For some reason I can't get the text input from the form. I'm successfully able to get the file.
<form action="upload.php" method="post" enctype="multipart/form-data" id="msform">
<fieldset>
<h2 class="fs-title">Upload Photo</h2>
Select Image: <input type="file" name="image">
Photo Name: <input type="text" name="photoName">
Photo Name2: <input type="text" name="photoName">
<input type="submit" value="Upload Image" name="submit" class="submit action-button">
</fieldset></form>
This is my code to get the form data:
if ( isset( $_FILES['image'] ) ) {
// save file to Parse
$file = ParseFile::createFromData( file_get_contents( $_FILES['image']['tmp_name'] ), $_FILES['image']['name'] );
$file->save();
$foo = $_POST['photoName'];
echo $foo;
$foo does not display. I've tried using $_GET and $_REQUEST
Your second input overrides the first. Try to make a:
var_dump($_POST);
at the beginning of the php script, so you will see what is arriving as a parameter

Submiting a form using PHP

I am trying to submit a form using PHP. I am trying to grab the value from two file inputs in my form, yet when I try to index them with my PHP code, I keep getting an error.
The error I get:
Undefined index: profile-pic in C:\xampp\htdocs\shareitme\form-test.php on line 5
Undefined index: cover-pic in C:\xampp\htdocs\shareitme\form-test.php on line 6
My Code:
<?php
if (isset($_POST['submit'])) {
$profile_pic= time() . $_FILES['profile-pic']['name'];
$cover_pic= time() . $_FILES['cover-pic']['name'];
}
?>
<form id="editprofile" method="post" action="<?php echo $_SERVER['PHP_SELF']
?>">
<input type="hidden" name="MAX_FILE_SIZE" value="5000000"/>
<input type="file" name="profile-pic"/>
<input type="file" name="cover-pic"/>
<input type="submit" name="submit" value="submit"/>
</form>
I know I have the names right, what am I doing wrong?
For uploading a file include enctype="multipart/form-data" in your form, like below:
<form id="editprofile" enctype="multipart/form-data" method="post" action="<?php echo $_SERVER['PHP_SELF']
?>">
The enctype attribute specifies how the form-data should be encoded when submitting it to the server.
For more info on forms : http://www.w3schools.com/tags/att_form_enctype.asp
For renaming a uploaded file, it better to upload it to server with move_uploaded_file and than rename it.
try:
<?php
if (isset($_REQUEST['go']) && $_REQUEST['go'] == "1") {
$profile_pic= time() . $_FILES['profile-pic']['name'];
$cover_pic= time() . $_FILES['cover-pic']['name'];
}
?>
<form id="editprofile" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="hidden" name="MAX_FILE_SIZE" value="5000000"/>
<input type="file" name="profile-pic"/>
<input type="file" name="cover-pic"/>
<input type=hidden name="go" value="1">
<input type="submit" name="submit" value="submit"/>
</form>
Whenever you are want to upload file. you need to add enctype in from.
`enctype="multipart/form-data"'
This should work
<form id="editprofile" enctype="multipart/form-data" method="post" action="<?php echo $_SERVER['PHP_SELF']
?>">
What you're trying to do here, if I'm not mistaken, is upload images on your server, right? You can simply use a third-party upload tool for that. I'd recommend AjaxUpload as it is based on AJAX and pretty easy to implement.
For simplicity, I'm applying the upload functionality on one image. You can simply put it inside a function and reuse it.
<p id="showMsg"></p>
<input type="file" name="profile-pic" id="profilePic" />
JQuery:
$("#profilePic").ajaxUpload({
url : $_SERVER['PHP_SELF'],
name: "file",
onSubmit: function() {
$('#showMsg').html('Uploading ... ');
},
onComplete: function(result) {
$('#showMsg').html('File uploaded with result' + result);
}
});
PHP:
<?php
if (isset($_FILES))
{
$file = $_FILES['file'];
move_uploaded_file($_FILES["file"]["tmp_name"], 'upload_dir/' . $_FILES["file"]["name"]); // This function will upload the image to 'upload_dir' folder. You can modify it as per your requirements.
}
?>
1) if you are using file type then your form attribute should be enctype="multipart/form-data".
<form id="editprofile" enctype="multipart/form-data" method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
2) Before using your post value it is best practice to check whether its setted or not.
$pic=isset($_FILES['profile-pic']['name']) ? $_FILES['profile-pic']['name'] : '';
Use enctype="multipart/form-data" in form tag.
Whenever you want to post binary datas you must have to set this enctype attribute.

uploading sessions with php not outputing

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 ;)

Categories