0

I created a jQuery script to do some form validation (i.e. register users, login users, create projects/albums etc.) it has been working just fine with the $_POST function in PHP. I'm trying to create an upload form to upload files to specific albums now and the jQuery is unresponsive. Here is the code:

The form:

<?PHP 
include 'init.php';
if (!isset ($_SESSION['user_id'])){
    header('Location: index.php');
    exit();       
}

if (!logged_in()){
    header('Location: ../index.php');
    exit();        
}

$shots = get_shots();

?>
<head>
    <title></title>
    <link href="css/style.css" rel="stylesheet" type="text/css">
    <script src="js/jquery_1_6_2.js" type="text/javascript"></script>
    <script src="js/jfunc.js" type="text/javascript"></script>
</head>

<div class="grid_1_head"> Upload File <span class="right_shots"><a id="close-panel" href="#"class="create_new_shot">Close this window</a></span></div>
<div class="hover_1_body"> 


<p> Select the file you would like to upload then click the Upload File Button. </p>    

    <div class="project_form_text">

<div class="hover_1_error">           
<div class="message_error"></div>
<div class="project_create_success"></div>  
</div>

        <div class="form_left">     
        <form id="upload_file" action="widgets/upload_file_process.php" method="post" enctype="multipart/form-data">  



     <p>
     <label for="selected_file">Choose a File:</label>
     <input id="selected_file" name="selected_file" type="file" class="field_boarder" value="" /> <br />

     Choose a shot:
     <select name="shot_id" class="select_style"> 

     <?php

     foreach ($shots as $shot){

         echo '<option value="', $shot['shot_id'], '">', $shot['shot_name'], ' </option>';        
     }
     ?>
     </select>

     </p> 



   <div class="login_button_container">
   <input name="upload_file" type="submit" class="login_button" value="Upload File"/>

    </div>

</form>

  </div> 

</div>

THIS IS THE PHP THAT PROCESS THE FORM:

<?php
include '../init.php';

if (!logged_in()){
    header('Location: ../index.php');
    exit();        
}


if (isset($_FILES['selected_file'], $_POST['shot_id'])){
    $file_name = $_FILES['selected_file']['name'];
    $file_size = $_FILES['selected_file']['size'];
    $file_temp = $_FILES['selected_file']['tmp_name'];  
    $allowed_ext = array('mov','r3d','avi','mp4','wmv','ogg','webm',                                            //Video Files
                         'mp3','aif','aiff','wav','ac3',                                                        //Audio Files
                         'gif','jpg','jpeg','png','pic','pict','psd','bmp','dpx','raw','jpf','pcx','tga',       // Still bitmap files and Sequences
                         'tif','tiff','hdr','exr', 'picio','rla','rpf','sgi','iff','cin','als',                
                         'ai','svg','svgz','eps',                                                               // Still Vector files
                         'fcp','color','edl','mxf','aaf','omf','xml',                                           // Interchange formats 
                         'pdf','xls','doc','txt','ppt','xlsx','docx','rtf');                                    // Documents

    $file_ext = strtolower(end(explode('.', $file_name)));
    $shot_id = $_POST['shot_id'];
    $errors = array();


    if (empty($file_name) || empty($shot_id)){

         $file_exists_check = 'invalid';

        }else {

          $file_exists_check = 'valid';
        }

    if (in_array($file_ext, $allowed_ext) === false){

            $file_type_check = 'invalid';        

        }else {

          $file_type_check = 'valid';
        }


    if ($file_size > 2097152000) {

          $file_size_check = 'invalid';

        }else {

          $file_size_check = 'valid';
        }

    if (shot_check($shot_id) === true){

          $shot_exists_check = 'invalid';

        }else {

          $shot_exists_check = 'valid';
        }



   $errors["file_exists_check"] = $file_exists_check;
   $errors["file_type_check"] = $file_type_check; 
   $errors["file_size_check"] = $file_size_check;
   $errors["shot_exists_check"] = $shot_exists_check;


       echo json_encode($errors);    

}


?>

THIS IS THE JQUERY FUNCTION THAT NEEDS TO ALERT USERS OF PROBLEMS AND THE FINISH THE FORM:

// UPLOAD FILE VALIDATION

$(function(){

    $("#upload_file").submit(function(e){

  // e.preventDefault();  

       $.post("widgets/upload_file_process.php", $("#upload_file").serialize(),


    function(data){


            if(data.file_exists_check == 'invalid'){

                    $('div.message_error').hide();
                    $('div.project_create_success').hide();
                    $('div.message_error').fadeIn();
                    $('div.message_error').html("<div>You need to select a file.</div>");

            } else if (data.file_type_check == 'invalid'){

                    $('div.message_error').hide();
                    $('div.project_create_success').hide();
                    $('div.message_error').fadeIn();
                    $('div.message_error').html("<div>File type not supported</div>");

            } else if (data.file_size_check == 'invalid'){

                    $('div.message_error').hide();
                    $('div.project_create_success').hide();
                    $('div.message_error').fadeIn();
                    $('div.message_error').html("<div>File must be less than 2GB</div>");

            }else if (data.shot_exists_check == 'invalid'){

                    $('div.message_error').hide();
                    $('div.project_create_success').hide();
                    $('div.message_error').fadeIn();
                    $('div.message_error').html("<div>That shot does not exist</div>");

            }else {


                $('div.message_error').hide();
                $('div.project_create_success').fadeIn();
                $('div.project_create_success').html("<div>File Uploading </div>");
                  $(function(){


                     $('#lightbox_content').delay(300).fadeOut(300 , function(){
                     $(this).remove();
                   });

                     $('#lightbox_bg').delay(300).fadeOut(300, function(){
                     $(this).remove();
                   window.location.replace("producer.php");

           });      
                });

            return false;

                }

        }, "json");

    });

});

THIS is almost identical to a function I have for registering users that works just fine. The only thing that is new (to me) is using the $_FILES to get the file info. is there a problem using that with jQuery?

Thank you in advance.

2
  • 1
    At what point does it become unresponsive? When you debug into it, is there a specific line on which the system hangs? What are the states of the objects on that line? Commented Sep 13, 2011 at 23:32
  • Its weird if I put an alert before the query function and comment out the prevent default the alert will trigger on clicking the submit button. If I put the path to the php processing page in the form action and comment out the prevent default the page will process and return valid JASON. If I put the alert inside the jquery function(data) it will not trigger. Commented Sep 13, 2011 at 23:41

3 Answers 3

1

You can not upload files using xmlhttprequest.
Either use frames/iframes(prefered by me and google)/Flash/Java if you want to do it async

Sign up to request clarification or add additional context in comments.

3 Comments

I don't understand. I'm following a tutorial to create the php upload and it works fine for them BUT they are not using java/jquery to validate the form which is what I want to do.
@Craig: Can you provide a link to the tutorial you're referring to?
www.phpacademy.org it's the image upload site tutorial. the file uploading section is 12 or 15 videos in.
0

File uploads with AJAX is a complicated matter. You might find this informative: $(form).serialize() Workaround for File Fields. It suggests using jQuery Form Plugin.

That’s the best you’re likely to get. I’m sorry I couldn’t be more helpful.

Good luck to you.

Comments

0

Why don't you try using jquery ajax, it is much simpler

function uploadDocument() {
        var formArray = new FormData($('#upload_file')[0]);
        $.ajax({
            url: "<?php echo Router::url('/uploadDocument'); ?>",
            data: formArray,
            type: "POST",
            dataType: "json",
            success: function(data){
            //do something upon success 
            }
        });
    }
$('#upload_file').live('submit',function(){
var file = $('#selected_file')[0].files[0];
//run validation   
uploadDocument();
return false;
})

in your uploadDocument.php, you can just print_r($_FILES); I have not try this but theoritically it should work.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.