How to upload image through jQuery/Ajax in wordpress How to upload image through jQuery/Ajax in wordpress wordpress wordpress

How to upload image through jQuery/Ajax in wordpress


Make sure your version of ajax support it.And you need to set ajax processData and contentType to FALSE.Para contentType means do not set the Content-Type HEAD,and processData means do not handle the data into string.

Try this:

$.ajax({    type: 'POST',     url: ajaxurl,    data: fdata,    processData : false,    contentType: false,    success:function(data) {        alert('success');    }}


upload image through jQuery/Ajax in wordpress

HTML:

    <input type="file" id="ct-file" name="ct_file">

JS:

    var sofg_mixup = jQuery.noConflict();    sofg_mixup(document).ready(function() {        sofg_mixup('#ct-file').change(function() {            var fileInput = sofg_mixup('#ct-file').prop('files')[0];            var myFormData = new FormData();            myFormData.append('ct_file', fileInput);            sofg_mixup.ajax({                url: '<?php echo get_template_directory_uri() ?>/save_file.php',                type: 'POST',                processData: false, // important                contentType: false, // important                dataType: 'json',                data: myFormData,                success: function(jsonData) {                    console.log(jsonData.url);                },                error: function(xhr, ajaxOptions, thrownError) {                    console.log(xhr);                }            });        });    });

PHP

require_once('../../../../../wp-load.php');if (isset($_FILES['ct_file'] ) && !empty($_FILES['ct_file']['name']) )        {            $allowedExts = array("doc", "docx", "pdf");            $temp = explode(".", $_FILES["ct_file"]["name"]);            $extension = end($temp);            if ( in_array($extension, $allowedExts))            {                if ( ($_FILES["ct_file"]["error"] > 0) && ($_FILES['ct_file']['size'] <= 3145728 ))                {                    $response = array(                        "status" => 'error',                        "message" => 'ERROR Return Code: '. $_FILES["ct_file"]["error"],                        );                }                else                {                    $uploadedfile = $_FILES['ct_file'];                    $upload_name = $_FILES['ct_file']['name'];                    $uploads = wp_upload_dir();                    $filepath = $uploads['path']."/$upload_name";                    if ( ! function_exists( 'wp_handle_upload' ) )                    {                        require_once( ABSPATH . 'wp-admin/includes/file.php' );                    }                    require_once( ABSPATH . 'wp-admin/includes/image.php' );                    $upload_overrides = array( 'test_form' => false );                    $movefile = wp_handle_upload( $uploadedfile, $upload_overrides );                    if ( $movefile && !isset( $movefile['error'] )  ) {                        $file = $movefile['file'];                        $url = $movefile['url'];                        $type = $movefile['type'];                        $attachment = array(                            'post_mime_type' => $type ,                            'post_title' => $upload_name,                            'post_content' => 'File '.$upload_name,                            'post_status' => 'inherit'                            );                        $attach_id=wp_insert_attachment( $attachment, $file, 0);                        $attach_data = wp_generate_attachment_metadata( $attach_id, $file );                        wp_update_attachment_metadata( $attach_id, $attach_data );                    }                    $response = array(                        "status" => 'success',                        "url" => $url                        );                }            }            else            {                $response = array(                    "status" => 'error',                    "message" => 'something went wrong, most likely file is to large for upload. check upload_max_filesize, post_max_size and memory_limit in you php.ini',                    );            }        }        print json_encode($response);        exit;