3

So I have been reading through every WordPress front-end AJAX file upload tutorial I can fine. Nothing is working for me at the moment. The one that makes the most sense to me is this one: http://theaveragedev.com/wordpress-files-ajax/

Here is my code:

In my template file example.php

<script>var ajax_url = "<?php echo admin_url('admin-ajax.php'); ?>"</script>
<form id="file_form">
    <?php wp_nonce_field('ajax_file_nonce', 'security'); ?>
    <input type="hidden" name="action" value="my_file_upload">
    <label for="file_upload">It's a file upload...</label>
    <input type="file" name="file_upload">
    <input type="submit" value="Go">
</form>

This is in ajax-file-upload.js

jQuery(document).ready(function(){
    var form_data = {};
    $(this).find('input').each(function(){
        form_data[this.name] = $(this).val();
    });
    $('#file_form').ajaxForm({
        url: ajax_url, // there on the admin side, do-it-yourself on the front-end
        data: form_data,
        type: 'POST',
        contentType: 'json',
        success: function(response){
            alert(response.message);
        }
    });
});

This is in my functions.php

function q_scripts(){
    $src = get_template_directory_uri().'/js/ajax-file-upload.js';
    wp_enqueue_script('my_ajax_file_uploader_thing', $src, array('jquery', 'jquery-form'));
}
add_action('init', 'q_scripts');

function handle_file_upload(){
    check_ajax_referer('ajax_file_nonce', 'security');

    if(!(is_array($_POST) && is_array($_FILES) && defined('DOING_AJAX') && DOING_AJAX)){
        return;
    }

    if(!function_exists('wp_handle_upload')){
        require_once(ABSPATH . 'wp-admin/includes/file.php');
    }
    $upload_overrides = array('test_form' => false);

    $response = array();

    foreach($_FILES as $file){
        $file_info = wp_handle_upload($file, $upload_overrides);

        // do something with the file info...
        $response['message'] = 'Done!';
    }

    echo json_encode($response);
    die();
}

add_action('wp_ajax_my_file_upload', 'handle_file_upload');

I have tried adding the enctype to the form element and this didn't work. The error I keep getting is an alert saying 'undefined'. Does anyone know how I can correct this issue?

EDIT

The 'undefined' issue has now gone away as I editied the js file to have a click event and changed the selector for the form input loop:

jQuery(document).ready(function($){
    $('#file_form :submit').click(function() {
        var form_data = {};
        $('#file_form').find('input').each(function () {
            form_data[this.name] = $(this).val();
        });
        console.log(form_data);
        $('#file_form').ajaxForm({
            url: ajax_url, // there on the admin side, do-it-yourself on the front-end
            data: form_data,
            type: 'POST',
            contentType: 'json',
            success: function (response) {
                alert(response.message);
            },
            error: function (response) {
                console.log('error');
            }
        });
        return false;
    });
});

The files still aren't being uploaded to the media folder. I also want to get the uploaded URL back once it has uploaded.

I am writing to the console the file object so I can see what is happening. Here is an example of it:

Object {security: "e6db2a6eee", _wp_http_referer: "/chat?sessionappid=138", action: "my_file_upload", file_upload: "C:\fakepath\download.jpg", "": "Go"}

Is there something wrong with this and is that why it isn't uploading?

  • You're missing the action parameter in your js. codex.wordpress.org/AJAX_in_Plugins – shanebp Aug 16 '15 at 18:22
  • Hi Shane (aren't you BuddyPress Shane?). The action parameter is passed as a hidden field in the form. I've decided to use a different solution. I'm using Simple Ajax Upload to upload the files to a different directory. – DL1984 Aug 16 '15 at 19:54
5

Hi You have Use this COde For WordPress front-end AJAX file upload tutorial Code Here is my code:

In my template file example.php

<form enctype="multipart/form-data">
   <input type="text" name="support_title" class="support-title">
   <input type="file" id="sortpicture" name="upload">
   <input class="save-support" name="save_support" type="button" value="Save">
 </form>

This is in ajax-file-upload.js

      jQuery(document).on('click', '.save-support', function (e) {

                        var supporttitle = jQuery('.support-title').val();

                        var querytype = jQuery('.support-query').val();
                        var file_data = jQuery('#sortpicture').prop('files')[0];

                        var form_data = new FormData();
                        if (supporttitle == '') {
                            jQuery('.support-title').css({"border": "1px solid red"})
                            return false;
                        } else {
                            jQuery('.support-title').css({"border": "1px solid #e3ecf0"})
                        }

                        form_data.append('file', file_data);
                        form_data.append('action', 'md_support_save');
                        form_data.append('supporttitle', supporttitle);

                        jQuery.ajax({
                            url: '<?php echo admin_url('admin-ajax.php'); ?>',
                            type: 'post',
                            contentType: false,
                            processData: false,
                            data: form_data,
                            success: function (response) {
                                jQuery('.Success-div').html("Form Submit Successfully")
                            }  
                            error: function (response) {
                             console.log('error');
                            }

                        });
                    });

                });

This iS functions.php code

  add_action( 'wp_ajax_md_support_save','md_support_save' );
  add_action( 'wp_ajax_nopriv_md_support_save','md_support_save' );


  public function md_support_save(){
       $support_title = !empty($_POST['supporttitle']) ? 
       $_POST['supporttitle'] : 'Support Title';

        if (!function_exists('wp_handle_upload')) {
           require_once(ABSPATH . 'wp-admin/includes/file.php');
       }
      // echo $_FILES["upload"]["name"];
      $uploadedfile = $_FILES['file'];
      $upload_overrides = array('test_form' => false);
      $movefile = wp_handle_upload($uploadedfile, $upload_overrides);

    // echo $movefile['url'];
      if ($movefile && !isset($movefile['error'])) {
         echo "File Upload Successfully";
    } else {
        /**
         * Error generated by _wp_handle_upload()
         * @see _wp_handle_upload() in wp-admin/includes/file.php
         */
        echo $movefile['error'];
    }
    die();
 }
  • Is that a question or an answer? Please do not post code dumps without any explanation. – fuxia Apr 18 '17 at 8:27
  • ok we have update my code and this ans for WordPress front-end AJAX file upload tutorial – Adnan Limdiwala Apr 18 '17 at 13:36
  • The answer works fine. Why this is not marked as right answer? There is an error in js code. original was --> }error: and the correct one is }, error: (missed the comma after }) – Alaksandar Jesus Gene Nov 14 '17 at 13:43
0

all codes for function.php


if (!empty($_POST) || (!empty($_FILES))) {
    require_once (ABSPATH . '/wp-admin/includes/file.php');
    require_once (ABSPATH . '/wp-admin/includes/image.php');
    global $wpdb;
    if (isset($_POST['submit'])) {
        // Upload Exhibitor Logo
        $file = $_FILES['uploaded_doc'];
        if (!empty($file)) {
            $uploads = wp_upload_dir();
            // Create 'user_avatar' directory if not exist
            $folderPath = ABSPATH . 'wp-content/uploads/Reports';
            if (!file_exists($folderPath)) {
                mkdir($folderPath, 0777, true);
            }

                 $ext = end((explode(".", $_FILES['uploaded_doc']['name'])));            
                if( $ext== 'pdf' || $ext== 'docx' ){                    
                $ABSPATH_userAvatarFullImage = ABSPATH . 'wp-content/uploads/Reports/' . time() . '.' . $ext;
                if (move_uploaded_file($_FILES['uploaded_doc']['tmp_name'], $ABSPATH_userAvatarFullImage)) {                        
                    $data = array(
                    'title' => $_POST['title'],
                    'arabic_title' => $_POST['arabic_title'],
                    'principle_investigators' => $_POST['principle_investigators'],
                    'co_investgators' => $_POST['co_investgators'],
                    'coverage_area' => $_POST['coverage_area'],
                    'publication_year' => $_POST['publication_year'],
                    'types' => $_POST['types'],
                    'uploaded_doc' => $_FILES['uploaded_doc']['name'],
                    'create_date'=> date('Y-m-d H:i:s') 

                    );          
        $table = $wpdb->prefix . "reports_publication";         
        $result = $wpdb->insert($table, $data);

                }
                echo "1";
                }else{
                    echo "File not in format";
                }

        }


}
}

}

  • need an explanation – Rich Nov 11 '17 at 18:07
0

your form

ENTER YOUR INFORMATION....

                    <div class="form-sec">
                            <form name="signupForm" class="signupForm" method="POST" id="abc"  enctype="multipart/form-data">                           
                        <div class="form-group col-sm-2">
                            <label for="">Title</label>
                        </div>
                        <div class="form-group col-sm-10">
                            <input type="text" class="form-control title"  name="title" placeholder=""/>
                        </div>

                        <div class="form-group col-sm-2">
                            <label for="">Arabic Title </label>
                        </div>
                        <div class="form-group col-sm-10">
                            <input type="text" class="form-control arabic_title"  name="arabic_title" placeholder=""/>
                        </div>

                        <div class="form-group col-sm-2">
                            <label for="">Principle Investigators </label>
                        </div>
                        <div class="form-group col-sm-10">
                            <input type="text" class="form-control principle_investigators"  name="principle_investigators" placeholder=""/>
                        </div>

                        <div class="form-group col-sm-2">
                            <label for="">Co Investigators </label>
                        </div>
                        <div class="form-group col-sm-10">
                            <input type="text" class="form-control co_investgators"  name="co_investgators" placeholder=""/>
                        </div>


                        <div class="form-group col-sm-2">
                            <label for="">Coverage Area</label>
                        </div>
                        <div class="form-group col-sm-10 city">     
                            <select id="Coverage" name="coverage_area"  class="form-control"/>
                                <option value="">Select Coverage Area </option>
                                    <?php
                                        $users = get_users(array(
                                            'role' => 'governorate'
                                        ));
                                        foreach ($users as $user) {
                                            echo '<option value="' . $user->display_name . '">' . esc_html($user->display_name) . '</option>';
                                                }
                                    ?>
                            </select>
                        </div>


                        <div class="form-group col-sm-2">
                            <label for="">Year Of Publication </label>
                        </div>
                        <div class="form-group col-sm-10">
                            <select id="publish" name="publication_year"  class="form-control"/>    
                                <option value="">select year</option>
                                    <?php
                                        for ($i = 1965; $i <= 2050; $i++) {
                                        echo '<option value="' . $i . '">' . $i . '</option>';
                                        }
                                    ?>
                            </select>
                        </div> 

                        <div class="form-group col-sm-2">
                            <label for="">Types</label>
                        </div>
                        <div class="form-group col-sm-10 city">     
                            <select id="types" name="types"  class="form-control"/> 
                                <option value="">select Types</option>
                                <option value="Article">Article</option>
                                <option value="Journal">Journal</option>
                                <option value="Book">Book</option>
                                <option value="Report">Report</option>
                                <option value="Other">Other</option>                                
                            </select>
                        </div>  


                            <div class="fileupload fileupload-new" data-provides="fileupload">
                                <span class="btn btn-primary btn-file">
                                    <span class="fileupload-new">UPLOAD FILE</span>
                                    <input class="uploaded_doc" type="file" name="uploaded_doc"/>
                                </span>                     
                            </div>

                            <input type="hidden" name="action" value="frmreg">


                        <div class="clearfix"></div>
                            <button type="submit" class="btn btn-success" name="submit" value="submit" id="submit1" >SUBMIT</button>
                </form>

                </div>

            </div>
        </div>
    </div>
</div>
                <?php
    }

}
-1

jQuery(document).ready(function() { //alert('hi'); //alert( mytheme.ajax_url);

jQuery('#abc').validate({
    rules: {
        title: "required",
        arabic_title: "required",
        principle_investigators: "required",
        co_investgators: "required",
        coverage_area: "required"



    },
    messages: {
        title: "enter title",
        arabic_title: "arabic title required",
        principle_investigators: "principle investigators required  required",
        co_investgators: "co investgators  required",
        coverage_area: "coverage area  required"

    },
        submitHandler: function(form) {           
        var formData = new FormData(jQuery('#abc')[0]); 
        jQuery.ajax({
            url: mytheme.ajax_url,
            type: 'POST',
            data: formData,
            async: false,
            cache: false,
            contentType: false,
            enctype: 'multipart/form-data',
            processData: false,
            success: function(data) {
                alert(data);
                if (data == '1') {
                    alert("successfully submited");
                }

            }
        });
        return false;
    }

});

});

  • its working so please read all code – Rakesh Shah Jul 10 '17 at 7:20
  • 1
    Welcome to WPSE. Please don't just drop code but give some explanation what it does, why it does it this,... – kraftner Jul 10 '17 at 8:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.