Avatar of Rozamunda
Rozamunda

asked on 

ajax file upload problem

Hi, I am always getting  error number 4.

in my php (upl1.php) i am opening an modal window when i create a form (upl2.php), i want to upload a file from this form. File upload I submit through ajax call to upl3.php
upl1.php:

<?php
session_start ();
           
            switch ($_POST ['form']) {
                  case '1' :
           
                        break;
                  case '4':                        
           
                      break;
                  case '2':
                 

                  break;   // bulk load  

                  case '5':
                   echo 'excel';      
                  break;      
                             
}                  
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
       
 <link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.10/themes/base/jquery-ui.css">
     
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
 
 <style TYPE="text/css">
 
a.button  {
      background-color: #aaa;
             
}            
#page_bg {
      padding: 0;
      background-color: #A0B0B8;
}
 

 </style>
 
 <script type="text/javascript"
    src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js">
 </script>

  <script type="text/javascript"
 
   src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.10/jquery-ui.min.js">
 
  </script>
   
 
 <script  type="text/javascript">
 $(document).ready(function() {
 $("#excel").bind("click", function(event){        
      event.preventDefault();                                                            
             
            $.ajax({
               type: "POST",      
               url: "upl2.php",
               data: "action=excel",
               success: function(data) {
                   var form = $(data).hide(),
                    modal = fx.initModal();                                
                     fx.boxin(null,modal);
                   
                   form
                    .appendTo(modal)
                    .addClass("savtxta")
                    .fadeIn("slow");
                                       
               },
               
               error: function(msg){
                     modal.append(msg);
                    alert("error");
               }
            });
            modal = fx.initModal();                        
      });
     

 $("#excel  #buttonUpload").live(
              "click", function(event){
                 
                    $.ajax({                                
                          type: 'POST',
                          url: "upl3.php"                                                            
                       });
                   
                    fx.boxout(event);
                   
                                                                 
                     $("#form").val(5);                                                        
                         
                         $("#ctrform").submit();                        
                 
              }
            );





 
 var fx = {
                  // Checks for a modal window and returns it, or
                  // else creates a new one and returns that
                  "initModal" : function() {
                  // If no elements are matched, the length
                  // property will return 0
                  if ( $(".modal-window").length==0 )
                  {
                  // Creates a div, adds a class, and
                  // appends it to the body tag
                  return $("<div>")
                  .addClass("modal-window")
                  .appendTo("body");
                  }
                  else
                  {
                  // Returns the modal window if one
                  // already exists in the DOM
                  return $(".modal-window");
                  }
                  },
               "boxin": function(data,modal) {                    
                   $("<div>")  
                   .hide()
                   .addClass("modal-overlay")
                   .click(function(event) {
                         fx.boxout(event);                                      
                   }).appendTo("body");
                         
                   modal
                      .hide()
                      .append(data)
                      .appendTo("body");                              
                 
                  $(".modal-window,.modal-overlay")  
                     .fadeIn("slow");
               },  

               "boxout": function(event) {                              
                    if (event!=undefined)
                    {                                      
                        event.preventDefault();  
                    }
                    $("a").removeClass("active");
                    $(".modal-window, .modal-overlay")
                      .fadeOut("slow",function(){
                        $(this).remove();
                            }
                     );
                  }        
      };

 });
 
 </script>
     
</head>
  <body id="page_bg">
     
   <div id="wrapper">
 
 
 <form id="ctrform" name="ctrform" method='post'>
   
           
   <input type="hidden" name="form" id="form">
       
 
       
      <div > <a id="excel" class="button"  href="#"><span> Excel </span></a>  </div>
 
 
    </form>              
    </div>
 
     
</body>

</html>

upl2.php:
<?php
 session_start();
 // Displays popups through modal windows

  if ((isset($_POST['action'])))      
   {
        $act = trim(($_POST['action']));        
        switch($act)
        {

             
         case 'excel':
        $formmrk =<<<FORM_MARKUP
   <form name="excel" id="excel" action=""
      method="POST" enctype="multipart/form-data
    target="upload_target">
      <table cellpadding="0" cellspacing="0" class="tableForm">
      <thead>
      <tr>
            <th>Please select a file and click Upload button</th>
                  </tr>
            </thead>
            <tbody>      
                  <tr>
                        <td><input id="fileToUpload" type="file" size="25" name="fileToUpload" class="input"></td>                  </tr>
            </tbody>
                  <tfoot>
                        <tr>
                              <td><button id="buttonUpload" class="button">Upload</button></td>
                        </tr>
                  </tfoot>
      </table>
            </form>
<iframe id="upload_target" name="upload_target" src="#" style="width:0;height:0;border:0px solid #fff;"></iframe>                                    
FORM_MARKUP;
     
 echo $formmrk;
               
               
  break;
         
        }      
       
   }
?>

upl3.php:

<?php
 session_start();      
 $target="/tmp/";
                                 
      ini_set ("display_errors", "1");
    error_reporting(E_ALL);
         
     
      $fileElementName = 'fileToUpload';
      var_dump($_FILES);
      if(!empty($_FILES[$fileElementName]['error']))
      {
            switch($_FILES[$fileElementName]['error'])
            {

                  case '1':
                        $error = 'The uploaded file exceeds the upload_max_filesize directive in php.ini';
                        break;
                  case '2':
                        $error = 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form';
                        break;
                  case '3':
                        $error = 'The uploaded file was only partially uploaded';
                        break;
                  case '4':
                        $error = 'No file was uploaded.';
                        break;

                  case '6':
                        $error = 'Missing a temporary folder';
                        break;
                  case '7':
                        $error = 'Failed to write file to disk';
                        break;
                  case '8':
                        $error = 'File upload stopped by extension';
                        break;
                  case '999':
                  default:
                        $error = 'No error code avaiable';
            }
      }elseif(empty($_FILES['fileToUpload']['tmp_name']) || $_FILES['fileToUpload']['tmp_name'] == 'none')
      {
            $error = 'No file was uploaded..';
      }else
      {
             $msg .= " File Name: " . $_FILES['fileToUpload']['name'] . ", ";
             
         
            $msg .= " File Size: " . @filesize($_FILES['fileToUpload']['tmp_name']);
            //for security reason, we force to remove all uploaded file
           
        move_uploaded_file($_FILES['fileToUpload']['tmp_name'],$target.$_FILES['fileToUpload']['name']);
       
           
      @unlink($_FILES['fileToUpload']);            
      }            
      echo "{";
      echo                        "error: '" . $error . "',\n";
      echo                        "msg: '" . $msg . "'\n";
      echo "}";
?>
jQueryAJAXPHPJavaScript

Avatar of undefined
Last Comment
Rozamunda
Avatar of HugoHiasl
HugoHiasl

Is it intended that you missed the closing quote for the enctype attribute?

 <form name="excel" id="excel" action=""
      method="POST" enctype="multipart/form-data
    target="upload_target">
Avatar of Rozamunda
Rozamunda

ASKER

i fixed it thanks, but it did not help
Avatar of Rozamunda
Rozamunda

ASKER

it looks like $_FILES is empty . Why ?
Avatar of leakim971
leakim971
Flag of Guadeloupe image

		$("#excel  #buttonUpload").live("click", function(event){
// send nothing (or some cookies & donuts) to upl3.php
			$.ajax({ type: 'POST', url: "upl3.php" });
// hide the modal
			fx.boxout(event);
// set the value of a form?
			$("#form").val(5);
// submit the form and reload  the page
			$("#ctrform").submit();                        
		});

Open in new window

Avatar of leakim971
leakim971
Flag of Guadeloupe image

please use the code snippet (or select it and click on the code button)
Avatar of Rozamunda
Rozamunda

ASKER

Leakim,
I set form value to 5, for further logic I removed for simplicity.
I want to submit that form after i upload and process my excel file, but the form which i am using
to upload the file is inside my modal window

I read the info, so  yes I am using iframe in my file upload. I was thinking that since
$_FILES is superglobal it will be accessible in ajax call.

And yes i need  more help
Avatar of Rozamunda
Rozamunda

ASKER

So my problem is how to pass $_FILES to upl3.php where I could process it ?
Avatar of leakim971
leakim971
Flag of Guadeloupe image

in upl2.php you should have : <form name="excel" id="excel" action="upl3.php"
and you don't need :
$.ajax({                                 
                          type: 'POST',
                          url: "upl3.php"                                                             
                       });

Open in new window

Avatar of leakim971
leakim971
Flag of Guadeloupe image

another problem, is fx.boxout(event) :

$(".modal-window, .modal-overlay")
                      .fadeOut("slow",function(){
                        $(this).remove();
                            }
                     );

This remove the form+iframe before having successfully posted the data (excel file)
 
Avatar of Rozamunda
Rozamunda

ASKER

I changed upl1.php to, does not seem to submit the form

and also changed form in upl2
$("#excel  #buttonUpload").live(
		  "click", function(event){
			 
			  $("#excel").submit();
			  
			  fx.boxout(event);
			  
			  				  			  
			   $("#form").val(5);		 					  		
	 			
				 $("#ctrform").submit();				 
			
		  }
		);


upl2:


 <form name="excel" id="excel" action="upl3.php" 
      method="POST" enctype="multipart/form-data" 
    target="upload_target">
	<table cellpadding="0" cellspacing="0" class="tableForm">
	<thead>
	<tr>
		<th>Please select a file and click Upload button</th>
			</tr>
		</thead>
		<tbody>	
			<tr>
				<td><input id="fileToUpload" type="file" size="25" name="fileToUpload" class="input"></td>			</tr>
		</tbody>
			<tfoot>
				<tr>
					<td><button id="buttonUpload" class="button">Upload</button></td>
				</tr>
			</tfoot>
	</table>
		</form>
<iframe id="upload_target" name="upload_target" src="#" style="display:none"></iframe> 						
FORM_MARKUP;

Open in new window

Avatar of leakim971
leakim971
Flag of Guadeloupe image

because your line 6 : fx.boxout(event);
it remove the modal and its content before posting anything

replace :
$("#excel  #buttonUpload").live(
		  "click", function(event){
			 
			  $("#excel").submit();
			  
			  fx.boxout(event);
			  
			  				  			  
			   $("#form").val(5);		 					  		
	 			
				 $("#ctrform").submit();				 
			
		  }
		);

Open in new window

by :
$("#excel  #buttonUpload").live("click", function(event){
			//$.ajax({ type: 'POST', url: "upl3.php" });
			$("#upload_target").load(function() {
				fx.boxout(event);
			})
			$("#form").val(5);                                                         
			//$("#ctrform").submit();	
		});

Open in new window

Avatar of Rozamunda
Rozamunda

ASKER

Hmm...Did you check it ?. For me it is not calling upl3
Besides question when  $("#upload_target").load is triggered ? after Excel is uploaded ?


<?php
session_start ();
	

		switch ($_POST ['form']) {
			case '1' :
		
				break;
			case '4':				
		
			    break;
			case '2':
			

			break;   // bulk load   

			case '5':
			 echo 'excel';	
			 var_dump($_FILES);
			break;	
					 
}			
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 	
 <link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.10/themes/base/jquery-ui.css">
     
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  
 <style TYPE="text/css"> 
 
a.button  {
	background-color: #aaa;
 		
}		
#page_bg {
	padding: 0;
	background-color: #A0B0B8;
}
 

 </style>
  
 <script type="text/javascript"
    src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js">
 </script> 

  <script type="text/javascript"
  
   src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.10/jquery-ui.min.js">
  
  </script> 
    
 
 <script  type="text/javascript">
 $(document).ready(function() {
 $("#excel").bind("click", function(event){	   
	event.preventDefault();					 					
		 
		$.ajax({
		   type: "POST",	
		   url: "upl2.php", 
		   data: "action=excel",
		   success: function(data) {
			 var form = $(data).hide(),
			  modal = fx.initModal();		 			   
			   fx.boxin(null,modal);
			   
			 form
			  .appendTo(modal)
			  .addClass("savtxta")
			  .fadeIn("slow");
			 	 		 
		   },
		   
		   error: function(msg){
			   modal.append(msg);
			  alert("error"); 
		   }
		});
		modal = fx.initModal(); 				
	});
	

 $("#excel  #buttonUpload").live(
		  "click", function(event){
			 
				$("#upload_target").load(function() {
				//	fx.boxout(event);
				});
				
				$("#form").val(5);                                                         
				//$("#ctrform").submit();	
			});			 
			
 





 
 var fx = {
			// Checks for a modal window and returns it, or
			// else creates a new one and returns that
			"initModal" : function() {
			// If no elements are matched, the length
			// property will return 0
			if ( $(".modal-window").length==0 )
			{
			// Creates a div, adds a class, and
			// appends it to the body tag
			return $("<div>")
			.addClass("modal-window")
			.appendTo("body");
			}
			else
			{
			// Returns the modal window if one
			// already exists in the DOM
			return $(".modal-window");
			}
			},
		   "boxin": function(data,modal) {  			 
			 $("<div>")  
			 .hide()
			 .addClass("modal-overlay")
			 .click(function(event) {
				 fx.boxout(event);		 				 
			 }).appendTo("body");
			 	
			 modal
			    .hide()
			    .append(data)
			    .appendTo("body");		 			 
			 
			$(".modal-window,.modal-overlay")  
			   .fadeIn("slow");
		   },   

		   "boxout": function(event) {		 			
			  if (event!=undefined) 
			  {		 				  
				event.preventDefault();  
			  }
			  $("a").removeClass("active");
			  $(".modal-window, .modal-overlay")
			    .fadeOut("slow",function(){
			    //  $(this).remove();
		   		 } 
			   );
			}  	
	};

 });
 
 </script>
      
</head>
  <body id="page_bg"> 
     
   <div id="wrapper">
  
  
 <form id="ctrform" name="ctrform" method='post'>
   
           
   <input type="hidden" name="form" id="form">
  	
  
 	 
	<div > <a id="excel" class="button"  href="#"><span> Excel </span></a>  </div>
  
 
    </form> 		  
    </div>
 
     
</body>

</html>

Open in new window

<?php
 session_start();
 // Displays popups through modal windows

  if ((isset($_POST['action'])))      
   {
	  $act = trim(($_POST['action']));   	 
  	switch($act) 
  	{

  		
   	case 'excel':
  	$formmrk =<<<FORM_MARKUP
   <form name="excel" id="excel" action="upl3.php" 
      method="POST" enctype="multipart/form-data" 
    target="upload_target">
	<table cellpadding="0" cellspacing="0" class="tableForm">
	<thead>
	<tr>
		<th>Please select a file and click Upload button</th>
			</tr>
		</thead>
		<tbody>	
			<tr>
				<td><input id="fileToUpload" type="file" size="25" name="fileToUpload" class="input"></td>			</tr>
		</tbody>
			<tfoot>
				<tr>
					<td><button id="buttonUpload" class="button">Upload</button></td>
				</tr>
			</tfoot>
	</table>
		</form>
<iframe id="upload_target" name="upload_target" src="#" style="display:none"></iframe> 						
FORM_MARKUP;
	
 echo $formmrk;
   		
   		
  break; 
   	
 	 }	
 	 
   } 
?>

Open in new window

<?php
 session_start(); 	
 $target="/tmp/";
    					
	ini_set ("display_errors", "1");
    error_reporting(E_ALL);
	    
	
	$fileElementName = 'fileToUpload';
	if(!empty($_FILES[$fileElementName]['error']))
	{
		switch($_FILES[$fileElementName]['error'])
		{

			case '1':
				$error = 'The uploaded file exceeds the upload_max_filesize directive in php.ini';
				break;
			case '2':
				$error = 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form';
				break;
			case '3':
				$error = 'The uploaded file was only partially uploaded';
				break;
			case '4':
				$error = 'No file was uploaded.';
				break;

			case '6':
				$error = 'Missing a temporary folder';
				break;
			case '7':
				$error = 'Failed to write file to disk';
				break;
			case '8':
				$error = 'File upload stopped by extension';
				break;
			case '999':
			default:
				$error = 'No error code avaiable';
		}
	}elseif(empty($_FILES['fileToUpload']['tmp_name']) || $_FILES['fileToUpload']['tmp_name'] == 'none')
	{
		$error = 'No file was uploaded..';
	}else 
	{
	 	$msg .= " File Name: " . $_FILES['fileToUpload']['name'] . ", ";
	  	
	     
		$msg .= " File Size: " . @filesize($_FILES['fileToUpload']['tmp_name']);
		//for security reason, we force to remove all uploaded file
		
        move_uploaded_file($_FILES['fileToUpload']['tmp_name'],$target.$_FILES['fileToUpload']['name']);
	   
		
	@unlink($_FILES['fileToUpload']);		
	}		
	echo "{";
	echo				"error: '" . $error . "',\n";
	echo				"msg: '" . $msg . "'\n";
	echo "}";
?>

Open in new window

Avatar of leakim971
leakim971
Flag of Guadeloupe image

Yes, checked upl3.php is called

>Besides question when  $("#upload_target").load is triggered ? after Excel is uploaded ?
Yes, you can place an alert inside to be sure
Avatar of leakim971
leakim971
Flag of Guadeloupe image

If you can upload the codes somewhere we can debug it if you want
It work fine for me locally
Avatar of Rozamunda
Rozamunda

ASKER

I believe you. But could you please check one last time with my snippets ?
Avatar of leakim971
leakim971
Flag of Guadeloupe image

use local JS plugin, I got problem with this ones http://ajax.googleapis.com/....
Avatar of leakim971
leakim971
Flag of Guadeloupe image

with your mast code I got :
on line 46
{
Notice: Undefined variable: error in C:\Apache22\htdocs\upl3-2.php on line 58
error: '', msg: ' File Name: Clipboard06.jpg, File Size: 125733' }

Open in new window


Avatar of Rozamunda
Rozamunda

ASKER

But at least upl3 was called. i can't force it, trying different jquery libraries
ASKER CERTIFIED SOLUTION
Avatar of leakim971
leakim971
Flag of Guadeloupe image

Blurred text
THIS SOLUTION IS ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
Avatar of Rozamunda
Rozamunda

ASKER

Thanks very much , it works on my local host.
There are still some problems on the remote host but, now i know that this method will work
Avatar of Rozamunda
Rozamunda

ASKER

ie9  is giving me a problem (not calling upl3) but Firefox on the remote host also
Avatar of leakim971
leakim971
Flag of Guadeloupe image

Take a look to this thread : https://www.experts-exchange.com/questions/27142805/malsup-Form-Plugin-doesn't-work-for-onChange-submit-form.html
We use ajaxForm to submit the form with iframe as target
It work fine.

$("#excel").ajaxForm({ 
       "success": function(data) {
                                fx.boxout(event); 
                         }
}); 

Open in new window

Avatar of Rozamunda
Rozamunda

ASKER

ok, i  problem with IE is solved, it needed "button type= submit" in upl2.php

Thanks so much again
Avatar of Rozamunda
Rozamunda

ASKER

now i wonder what are the benefits of ajax form
JavaScript
JavaScript

JavaScript is a dynamic, object-based language commonly used for client-side scripting in web browsers. Recently, server side JavaScript frameworks have also emerged. JavaScript runs on nearly every operating system and in almost every mainstream web browser.

127K
Questions
--
Followers
--
Top Experts
Get a personalized solution from industry experts
Ask the experts
Read over 600 more reviews

TRUSTED BY

IBM logoIntel logoMicrosoft logoUbisoft logoSAP logo
Qualcomm logoCitrix Systems logoWorkday logoErnst & Young logo
High performer badgeUsers love us badge
LinkedIn logoFacebook logoX logoInstagram logoTikTok logoYouTube logo