How to retrieve file name from php and putting it in JS - php

I have a JavaScript function below where it displays a message after file uploading is complete:
function stopVideoUpload(success) {
var namevideofile = $('.fileVideo').val();
var result = '';
if (success == 1) {
result = '<span class="msg">The file was uploaded successfully!</span><br/><br/>';
$('.listVideo').append(namevideofile + '<br/>');
}
else {
result = '<span class="emsg">There was an error during file upload!</span><br/><br/>';
}
return true;
}​
Below is the php script which is on another page which successfully uploads the files:
if( file_exists("VideoFiles/".$_FILES['fileVideo']['name'])) {
$parts = explode(".",$_FILES['fileVideo']['name']);
$ext = array_pop($parts);
$base = implode(".",$parts);
$n = 2;
while( file_exists("ImageFiles/".$base."_".$n.".".$ext)) $n++;
$_FILES['fileVideo']['name'] = $base."_".$n.".".$ext;
move_uploaded_file($_FILES["fileVideo"]["tmp_name"],
"VideoFiles/" . $_FILES["fileVideo"]["name"]);
$result = 1;
}
else
{
move_uploaded_file($_FILES["fileVideo"]["tmp_name"],
"VideoFiles/" . $_FILES["fileVideo"]["name"]);
$result = 1;
}
?>
<script language="javascript" type="text/javascript">window.top.window.stopImageUpload(<?php echo $result;?>);</script>
Now except having var namevideofile to retrieve the value from the file input value (.fileVideo is the class for the file input), what I want it to do is that when the uploading is complete, the name given to file in the server would be var namevideofile. So if I have 2 files known as video.png, as I stated in my php code that if file exists then add a number to end of file name so that would create video.png and video1.png in server.
So when I append namevideofile, it should display video.png and video1.png after uploading is completed for both files. The problem with var namevideofile = $('.fileVideo').val();, is that it displays both file names as video.png which is incorrect.
So does anyone know how to change var namevideofile so that it retrieves the file name from the server after uploading? The issue is that the php script is on a separate page (videoupload.php) to the JS function (QandATable.php) so does ajax need to be involved here or not.
Anyone who could provide an example of how this can be coded would be very helpful to me :)

you can echo and store the value in a javaScript variable:
var namevideofile = <php echo $filename; ?>;

Related

PHP can't pick up file

I've been trying to create a registration form that requires students to upload documents at the very end. However, after picking up the form values via jQuery, the PHP document can't seem to pick up my uploaded form. Any ideas?
Form:
<form id="joinUs" enctype="multipart/form-data" method="post">
<!--various form fields-->
<input type="file" name="transcript" id="transcript">
<div class="button" id="submit">Submit!</div>
</form>
jQuery:
$("#submit").click(function(){
//firstName, lastName, grade, studentID, email, phone are all form values
var data = "firstName="+firstName+"&lastName="+lastName+"&grade="+grade+"&studentID="+studentID+"&email="+email+"&phone="+phone;
$.ajax({
type: "POST",
url: "join_submit.php",
data: data,
success: function() {
location.href="http://mvcsf.com/new/success.php";
}
});
join_submit.php
$allowedExtensions = array("pdf");
$max_filesize = 20000;
$upload_path = "docs/transcripts";
$filename = $_FILES["transcript"]["name"];
$filesize = $_FILES["transcript"]["size"];
$extension = $_FILES["transcript"]["type"];
if ($_FILES["transcript"]["error"] > 0) {
echo "Error: " . $_FILES["transcript"]["error"] . "<br />";
}
else if((in_array($extension, $allowedExtensions)) && ($filesize < $max_filesize)) {
move_uploaded_file($_FILES["transcript"]["tmp_name"], $upload_path . $filename);
}
I ran this, and I got no errors. I also tried to print out the file name, except nothing printed out.
This should do it for you :
$("#submit").click(function () {
var transcript = $("#transcript").val();
var data = "firstName=" + firstName + "&lastName=" + lastName + "&grade=" + grade + "&studentID=" + studentID + "&email=" + email + "&phone=" + phone;
var formData = new FormData();
formData.append("file", transcript);
formData.append("data", data);
$.ajax({
type: "POST",
url: "join_submit.php",
enctype: 'multipart/form-data',//optional
cache: false,
contentType: false,
processData: false,
data: {
file: file
data: data
},
success: function () {
location.href = "http://mvcsf.com/new/success.php";
}
});
});
Cheers
First, In your code, you are posting data with $.ajax({...}) and the data sent is
"firstName="+firstName+"&lastName="+lastName+"&grade="+grade+"&studentID="+studentID+"&email="+email+"&phone="+phone;
There is no transcript at all.
Secondly, and most important, you cannot post file with $.ajax({...}) like that, it will not working like that. As #Roy M J says, you should take a look at FormData (for recent browser only), or take a look on the web for an upload jQuery plugin (don't re-invent the whell, some good plugin already exists :))
Take a look here
You cannot send a file like you do the values of HTML elements. There are two methods to file upload, the one I've used successfully is the AJAX method using a third-party feature called 'AjaxUploader'.You can download it here via GitHub. Once you've done it, add the ajaxuploader.js file in your 'js' folder (or wherever you've put all of your script files), include the file in the HTML page where you've to use the uploader. Now, uploading is as simple as follows.
HTML:
<input type="file" name="transcriptUploader" id="transcriptUploader" value="Upload" />
jQuery (you need to have the jQuery file included in your page):
new AjaxUpload('transcriptUploader', {
action: "page_to_handle_upload.php", // You need to have either a separate PHP page to handle upload or a separate function. Link to either one of them here
name: 'file',
onSubmit: function(file, extension) {
// This function will execute once a user has submitted the uploaded file. You can use it to display a loader or a message that the file is being uploaded.
},
onComplete: function(file, response) {
// This function will execute once your file has been uploaded successfully.
var data = $.parseJSON(response); // Parsing the returning response from JSON.
if(data.error == 0)
{
// If the file uploaded successfully.
}
else if(data.error == "size"){
// If the response object sent 'size' as the error. It means the file size exceeds the size specified in the code.
}
else if(data.error == "type"){
// If the response object sent 'type' as the error. It means the file type is not of that specified in the code (in your case, pdf).
}
else{
// In case the file didn't upload successfully or the code didn't return a usual error code. It is still an error so you need to deal with it appropriately.
}
}
});
Your back-end PHP code that will be doing all the heavy lifting (uploading the file, checking extensions, moving it etc):
if(isset($_FILES)) // Checking if a file is posted.
{
if ($_FILES['file']['error'] == 0) //Checking if file array contain 0 as an error. It means AJAX had no error posting the file.
{
$response = array(); // Initializing a new array.
$allowedExts = array("pdf"); // Allowable file format.
$filename = stripslashes($_FILES['file']['name']); // Storing file name.
//$extension = strtolower(self::_getExtension($filename)); // Fetching file extension.
// Code block to extract file extension and storing it in a variable called $extraction.
$i = strrpos($str, ".");
if (!$i)
{
$extension = "";
}
$l = strlen($str) - $i;
$extension = strlower(substr($str, $i + 1, $l));
$size = $_FILES['file']['size']; // Storing file size (in bytes).
$fileNameAfterUpload = md5((time() + microtime())) . '.' . $extension; // Concatinating file name and extension.
$baseSystemPath = "/var/www/<your_folder_name>/uploaded_transcripts/" // Path on which the file will be uploaded. Need to be relative web path.
$maxSize = 10*10*1024; // Storing file size. Be advised the file size is in bytes, so this calculation means max file size will be 10 MB.
$webPath = "uploaded_transcripts/". $filename; // Creating web path by concatinating base web path (the folder in which you'd be uploading the pdf files to) with file name.
if (in_array($extension, $allowedExts)) // Checking if file contains allowabale extensions.
{
if($size <= $maxSize) // Checking if the size of file is less than and equal to the maximum allowable upload size.
{
$moved = move_uploaded_file($_FILES['file']['tmp_name'], $webPath); // Moving the file to the path specified in $webPath variable.
if($moved == true)
{
$response['error'] = 0; // If moved successfully, storing 0 in the response array.
$response['path'] = $webPath; // Storing web path as path in the response array.
$response['filename'] = $filename; // Storing file name in the response array.
}
else
{
$response['error'] = 'internal'; // If move isn't successfull, return 'internal' to AJAX.
}
}
else
{
$response['error'] = 'size'; // If file size is too small or large, return 'size' to AJAX.
}
}
else
{
$response['error'] = 'type'; // If file type is not that of defined, return 'type' to AJAX.
}
echo json_encode($response); // Returning the response in JSON format to AJAX.
}
}
Do let me know if you need further assistance.
P.S: Don't forget to mark it as an answer if it worked.

how to get array and session variable to go back to being blank after browser is refreshed?

I have a problem where everytime I refresh the browser, I want the array which contians a $_SESSION variable to go back to being blank. At moment lets say I uploaded 2 files and then refresh browser, when I upload another file, it shows the name of the previous files uploaded when it shouldn't. How can I get the array and session variable to go back to being blank if browser is refreshed?
Below is code:
function stopImageUpload(success){
var imageNameArray = new Array();
// WHEN PAGE IS REFRESH, ARRAY SHOULD GO BACK TO BEING BLANK
imageNameArray = <?php echo json_encode(isset($_FILES ['fileImage']['name']) ? $_FILES ['fileImage']['name'] : null); ?>;
//RETRIEVES THE SESSION VARIABLE FROM THE PHP SCRIPT OF THE FILE NAMES WHICH HAVE BEEN UPLOADED
var result = '';
if (success == 1){
result = '<span class="msg">The file was uploaded successfully!</span><br/><br/>';
for(var i=0;i<imageNameArray.length;i++) //LOOP THROUGH ALL UPLOADED FILE NAMES
{
$('.listImage').append(imageNameArray[i]+ '<br/>');//APPEND FILE NAME
}
}
else {
result = '<span class="emsg">There was an error during file upload!</span><br/><br/>';
}
return true;
}
Below is the php script where it uploads a file which is on another page from the javascript function above:
<?php
session_start();
$result = 0;
$errors = array ();
$dirImage = "ImageFiles/";
if (isset ( $_FILES ['fileImage'] ) && $_FILES ["fileImage"] ["error"] == UPLOAD_ERR_OK) {
$fileName = $_FILES ['fileImage'] ['name'];
$fileExt = pathinfo ( $fileName, PATHINFO_EXTENSION );
$fileExt = strtolower ( $fileExt );
$fileDst = $dirImage . DIRECTORY_SEPARATOR . $fileName;
if (count ( $errors ) == 0) {
if (move_uploaded_file ( $fileTemp, $fileDst )) {
$result = 1;
}
}
}
?>
<script language="javascript" type="text/javascript">window.top.stopImageUpload(<?php echo $result;?>);</script>
After the form is submitted and your PHP has done its work you need to do a 303 redirect to the page you wish to display. Then when a user refreshes the page you won't a second form submission.
For example:
header('Location: ' . $_SERVER['PHP_SELF'], true, 303);
Although I agree with the comment of #Reza Sanaie, you can solve your particular problem by unsetting the variable after a successful upload:
if (success == 1)
{
result = '<span class="msg">The file was uploaded successfully!</span><br/><br/>';
for(var i=0;i<imageNameArray.length;i++) //LOOP THROUGH ALL UPLOADED FILE NAMES
{
$('.listImage').append(imageNameArray[i]+ '<br/>');//APPEND FILE NAME
}
$_SESSION ['fileImage'] = NULL; // or use unset()
}
Just do your error checking in PHP, and pass an array to your HTML page to display the list of uploaded files in the page. You don't need javascript.
Have a look at How to upload files in PHP

How to retrieve the name of the file's name from the server using javascript?

I have a function below where when the file stops uploading, it displays a message whether upload was successful or not and then more importantly displays the name of the file uploaded using this code below:
$('.listImage').append(nameimagefile + '<br/>');
This code above retrieves the name of the file selected from the file input. The problem with this though is that I don't want the name of the file entered in the file input. Instead I want the name of the file which is uploaded into the server.
For example if I have uploaded 2 files which are both tulips.png, in the server they are saved and uploaded as tulips.png and tulips2.png but because I am using $('.listImage').append(nameimagefile + '<br/>');, it displays both file names as 'tulips.png' which is not what I want.
So this is where I decided i want to retireve the name of the file not from the value of the input file but the name saved when uploaded in the file.
How can I code this in the javascript function?
The javascript function and php script are on seperate pages but I do use a call back function in the php script to the javascript function:
Below is the form code:
<form action='imageupload.php' method='post' enctype='multipart/form-data' target='upload_target' onsubmit='stopImageUpload(this);' class='imageuploadform' >
<p>Image File: <input name='fileImage' type='file' class='fileImage' />
<input type='submit' name='submitImageBtn' class='sbtnimage' value='Upload' />
</p>
<ul class='list'></ul>
</form>
Below is the javascript function which gets the name of the file and displays a message if file is successful or not:
function stopImageUpload(success){
var nameimagefile = $('.fileImage').val();
var result = '';
if (success == 1){
result = '<span class="msg">The file was uploaded successfully!</span><br/><br/>';
$('.listImage').append(nameimagefile + '<br/>');
}
else {
result = '<span class="emsg">There was an error during file upload!</span><br/><br/>';
}
return true;
}
Finally below is the php script with the javascript call back function. aLl it does is upload file if file exists or not in server's folder. If it exists then it gives it a different file name by adding a name at end of file name, if it doesn't exist then it uploads file with same name:
if( file_exists("ImageFiles/".$_FILES['fileImage']['name'])) {
$parts = explode(".",$_FILES['fileImage']['name']);
$ext = array_pop($parts);
$base = implode(".",$parts);
$n = 2;
while( file_exists("ImageFiles/".$base."_".$n.".".$ext)) $n++;
$_FILES['fileImage']['name'] = $base."_".$n.".".$ext;
move_uploaded_file($_FILES["fileImage"]["tmp_name"],
"ImageFiles/" . $_FILES["fileImage"]["name"]);
$result = 1;
}
else
{
move_uploaded_file($_FILES["fileImage"]["tmp_name"],
"ImageFiles/" . $_FILES["fileImage"]["name"]);
$result = 1;
}
?>
<script language="javascript" type="text/javascript">window.top.window.stopImageUpload(<?php echo $result;?>);</script>
Hopefully that is all the info you need and thank you.
You could pass $_FILES["fileImage"]["name"] as argument to your js function. Javascript is a client side language, and thus, unable to handle files on the server.

it is not displaying the messages correctly

I have a javscript function below which displays a message depending on on the result:
function stopImageUpload(success){
var result = '';
if (success == 1){
result = '<span class="msg">The file was uploaded successfully!<\/span><br/><br/>';
}
else {
result = '<span class="emsg">There was an error during file upload!<\/span><br/><br/>';
}
return true;
}
The code below always displays the message "The file was uploaded successfully!"
<?php
$destination_path = str_replace("//", "/", $_SERVER['DOCUMENT_ROOT']."/")."ImageFiles";
$result = 0;
$target_path = $destination_path . basename( $_FILES['fileImage']['name']);
if(move_uploaded_file($_FILES['fileImage']['tmp_name'], $target_path)) {
$result = 1;
}
sleep(1);
?>
<script type='text/javascript' language='javascript'>
window.top.window.stopImageUpload(1);
</script>
But if I change the last line to this below then it always displays the message "There was an error during file upload!". Why is this and how can it be fixed so it displays the right message depending on the result?
<script language="javascript" type="text/javascript">
window.top.window.stopImageUpload(<?php echo $result; ?>);
</script>
Find out what this <?php echo $result; ?> actually renders to. Just look in the page source.
Most likely, it will be 0. Then try to find out why move_uploaded_file returns false. Probably, there's something wrong happening while moving the file.

multiple upload's title not saved to database

I am sorry but these solutions din't solved my purpose. So m giving more detail of my code,
var a=0;
function _add_more() {
var txt = "<br><input type=\"file\" name=\"item_file[]\"><br><input type=\"text\" name=\"text[]\">";
document.getElementById("dvFile").innerHTML += txt;
alert(a);
a=a+1;
}
here i have used a to increement title.
function upload(){
if(count($_FILES["item_file"]['name'])>0) { //check if any file uploaded
$GLOBALS['msg'] = ""; //initiate the global message
for($j=0; $j < count($_FILES["item_file"]['name']); $j++) { //loop the uploaded file array
$filen = $_FILES["item_file"]['name']["$j"]; //file name
$path = 'uploads/'.$filen; //generate the destination path
$text=$_POST['text']['name']["$j"] + "<br>";
if(move_uploaded_file($_FILES["item_file"]['tmp_name']["$j"],$path)) {
$insert=mysql_query("insert into image_upload set title='".$text."', image='".$filen."'") or die(mysql_error());
//upload the file
$GLOBALS['msg'] .= "File# ".($j+1)." ($filen) uploaded successfully<br>"; //Success message
}
}
}
else {
$GLOBALS['msg'] = "No files found to upload"; //Failed message
}
uploadForm(); //display the main form
}
this is what i have done. Please help me to get title for each uploaded file. as i am able to save different images in database but title appears to be same for all in database.
Try this:
$text=$_POST['text'][$j];

Categories