I am trying to upload image from wordpress register form(custom form). I found many ways to upload via ajax but none of them working for me.
here is form without tag
<div class="lofin-form"><div class="row">
<input type="text" name="first_name" id="first_name" placeholder="First Name" class="input" value="" size="20" />
</div>
<div class="row">
<lable>Id proof <input type="file" name="id_proof" id="id_proof" class="input" />
</div>
<p class="submit"><input type="submit" name="wp-submit" id="wp-submit-register" class="btn vernil small" value="'.__('Sign Up','wpestate').'" /></p>
</div>
and here is the jQuery script code
$('#wp-submit-register').click(function(){
wpestate_register();
});
function wpestate_register (){
var user_role = $('#first_name').val();
var fdata = new FormData();
fdata.append('file', $('#id_proof')[0].files[0]);
$.ajax({
type: 'POST',
url: ajaxurl,
data: {
'action' : 'ajax_free_register_form',
'first_name' : first_name,
'file_data' : fdata
},
success:function(data) {
alert('success');
}
}
And here is php function
add_action( 'wp_ajax_nopriv_ajax_free_register_form', 'ajax_free_register_form' );
add_action( 'wp_ajax_ajax_free_register_form', 'ajax_free_register_form' );
function ajax_free_register_form(){
$first_name = trim( $_POST['first_name'] ) ;
$id_proof = $_FILES['id_proof'] ;
}
RESOLVE [EDIT]
Just add form tag in form and gave an ID 'user_reg_form'.
<form id="user_reg_form" action="" method="post" enctype="multipart/form-data">
----------------------input fields goes here-------------------
</form>
And update the script:
$('#wp-submit-register').click(function(){
wpestate_register();
});
function wpestate_register (){
var formdata = new FormData( $("#user_reg_form")[0] );
formdata.append('action', 'ajax_free_register_form');
$.ajax({
type: 'POST',
cache: false,
contentType: false,
processData: false,
url: ajaxurl,
data: formdata,
success:function(data) {
alert('success');
}
});
}
After that you can simply get the uploaded file with
$attachment = $_FILES['id_proof'];
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');
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With