Pages

Feb 17, 2016

How to upload user image using AJAX



In a script add this




function uploadimageajax()
{
jQuery('#msghere').html('');

// alert('up');

 // var file_data = jQuery('#upload_user_image').prop('files')[0];
 

//  if(1==1){

// if(  jQuery('#upload_user_image').val() != ''  ){


var data = new FormData();


/*jQuery.each(jQuery('#upload_user_image')[0].files, function(i, file) {
data.append('file-'+i, file);
});*/

jQuery.each(jQuery('#upload_user_image')[0].files, function(i, file) {
data.append('upload_user_image[]', file);
});


jQuery.ajax({
url:"<?php  echo get_template_directory_uri(); ?>/actions/actionusrimage.php",
type:'POST',
cache: false,
contentType: false,
processData: false,
data:data,  //jQuery("#profile_image_form").serialize() ,

success:function(results)
{

alert(results);
jQuery('#msghere').append(' <div class="msgsucess">Image Succesfully Updated !!</div>');
jQuery('#msgtxt').val('');
}

});

// }
//}
return false;
}



Now create  an external actionusrimage.php file & add this 

<?php @ob_start();

if(isset( $_FILES['upload_user_image'])){
if ( ! function_exists( 'wp_handle_upload' ) ) {
require_once( ABSPATH . 'wp-admin/includes/file.php' ); //this is important

}
$uploadedfile =  $_FILES['upload_user_image'];

echo $uploadedfile ;
exit();

$upload_overrides = array( 'test_form' => false );
$movefile = wp_handle_upload( $uploadedfile, $upload_overrides );
if ( $movefile && !isset( $movefile['error'] ) ) {
$user_ID = get_current_user_id();
if( update_user_meta( $user_ID , 'user_profile_img', $movefile['url']  ) ){
echo 'success';
}
}
}
 ?>

No comments: