1

I want to upload and move the csv file using jquery ajax function.

$("#file").change(function() { 
  alert($("#file").val());
  $.ajax({
    url: "<?php echo base_url(); ?>index.php/Task_controller/upload_tasksquestion",
    type: "post",
    dataType: 'json',
    processData: false,
    contentType: false,
    data: {file: $("#file").val()},
    success: function(text) {
        alert(text);
        if(text == "success") {
            alert("Your image was uploaded successfully");
        }
    },
    error: function() {
        alert("An error occured, please try again.");         
    }
  });   
});

and my html code is:

< input type="file" class="form-control" id="file" name="file">

and i am testing in controller function uploaded file name like $this->input->post('file');

but it is not come to the controller and i want to move that file into a folder. please help me where i am doing mistake...

my server side code is:

$curdate=date('Y-m-d');
$path='./assets/fileuploads/';
$file=basename($_FILES['file']['name']);
        
list($txt, $ext) = explode(".", $file);
$actual_file_name = time().substr($txt, 5).".".$ext;
if(move_uploaded_file($_FILES['file']['tmp_name'],$path.$actual_file_name))
            

2 Answers 2

3

You need to use FormData to send files over via AJAX.

Store the file in a FormData object and pass the object as your data.

$("#file").change(function() {
    var fd = new FormData();
    fd.append('file', this.files[0]); // since this is your file input

    $.ajax({
        url: "<?php echo base_url(); ?>index.php/Task_controller/upload_tasksquestion",
        type: "post",
        dataType: 'json',
        processData: false, // important
        contentType: false, // important
        data: fd,
        success: function(text) {
            alert(text);
            if(text == "success") {
                alert("Your image was uploaded successfully");
            }
        },
        error: function() {
            alert("An error occured, please try again.");         
        }
    });
});

Read File Uploading Class (particularly from The Controller section) on how to deal with the file on the server-side end.

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

3 Comments

any need to add upload library? in serverside? because i am testing but it always says error occurs.Please help.
According to instructions, you need to load the Upload library. Edit your question with the relevant server-side code. Error can mean many things. Open your browser developer tools, find the Network panel that shows all your AJAX requests, and find the actual message that is being given for error.
it is my server side code : $config['upload_path'] = './assets/fileuploads/'; $config['allowed_types'] = '.csv/.CSV'; $this->load->library('upload', $config); echo $this->upload->do_upload('fd'); here just i want to know the uploaded file name.
0

    jQuery(document).ready(function($) {
        $('.import-btn').on('click', function() {
            $('#fileImport').click();
        })

        $('#fileImport').on('change', function() {
            var fileData = new FormData();
            var file = this.files[0];
            if (file) {
                fileData.append("file", file);
            }
            fileData.append("action", "import_data");
            $.ajax({
                url: "<?php echo admin_url("admin-ajax.php"); ?>",
                type: "POST",
                data: fileData,
                processData: false,
                contentType: false,
                success: function(response) {
                    if (response.success) {
                        Swal.fire({
                            title: "Success",
                            text: response.data.message,
                            icon: "success"
                        });

                    } else {
                        Swal.fire({
                            title: "Error",
                            text: response.data.message,
                            icon: "error"
                        });
                    }
                },
                error: function(xhr, status, error) {
                    alert(error);
                }
            });
        });
    });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
add_action('wp_ajax_nopriv_import_data', 'import_data');
add_action('wp_ajax_import_data', 'import_data');
function import_data()
{
    if ($_SERVER['REQUEST_METHOD'] == "POST") {
        if (!empty($_FILES['file']) && isset($_FILES['file']['name'])) {
            $fileTmpName = $_FILES['file']['tmp_name'];

            if (($handle = fopen($fileTmpName, "r")) !== FALSE) {
                $header = fgetcsv($handle);
                while (($data = fgetcsv($handle)) !== FALSE) {
                    $post_title = isset($data[1]) ? $data[1] : '';
                    $category = isset($data[4]) ? $data[4] : '';
                    $post_content = isset($data[5]) ? wp_strip_all_tags(trim($data[5])) : '';
                    $post_thumbnail_url = isset($data[6]) ? $data[6] : '';

                    $args = array(
                        'post_type' => 'news',
                        'post_title' => $post_title,
                        'post_content' => $post_content,
                        'post_status' => 'publish'
                    );

                    $post_id = wp_insert_post($args);
                    if (!$post_id) {
                        wp_send_json_error(array("message" => "Error while importing post"));
                    } else {
                        update_post_meta($post_id, 'category', $category);
                        $upload_dir = wp_upload_dir();
                        $image_name = basename($post_thumbnail_url);
                        $type = wp_check_filetype($post_thumbnail_url)['type'];
                        $upload_path = $upload_dir['path'] . '/' . $image_name;
                        $image_url = $upload_dir['url'] . '/' . $image_name;
                        $image_data = file_get_contents($post_thumbnail_url);
                        if (file_put_contents($upload_path, $image_data)) {
                            $args = array(
                                'guid' => $image_url,
                                'post_status' => 'inherit',
                                'post_parent' => $post_id,
                                'post_mime_type' => $type,
                                'post_title' => $image_name
                            );
                            $attachment_id = wp_insert_attachment($args, $upload_path, $post_id);
                            if ($attachment_id) {
                                $attachment_metadata = wp_generate_attachment_metadata($attachment_id, $upload_path);
                                wp_update_attachment_metadata($attachment_id, $attachment_metadata);
                                set_post_thumbnail($post_id, $attachment_id);
                            } else {
                                wp_send_json_error(array("message" => "Error"));
                                wp_die();
                            }
                        }
                    }
                }
                fclose($handle);
                wp_send_json_success(array("message" => "Imported Successfully"));
            }
        }
    } else {
        wp_send_json_error(array("message" => "Error"));
        wp_die();
    }
}

1 Comment

Why is this CodeIgniter question being answered as if it was a WordPress question? Where is the plain English explanation with this code dump?

Your Answer

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