0

I'm using a Using modal window with + form to change the profile avatar. Like the following (functions.php):

add_action('change_avatar', 'edit_avatar_function');
function edit_avatar_function($uid, $pid) { 
    $av = get_user_meta($uid, 'avatar_' . 'project', true);
    $avatar = wp_get_attachment_image_src( $av, 'thumb300' );
    ?>
<div id="avatar-modal" class="modal fade" role="dialog">
    <div class="modal-dialog browse-panel">
        <div class="box_title">
          <?php _e('Edit your Avatar', 'KleeiaDev') ?>
        </div>
        <div class="box_content top-15 text-center" id="my-media">
            <form id="change-avatar" action="#" method="post" enctype="multipart/form-data">
                <p class="top-20">
                    <input id="input-avatar" data-buttonText="<?php _e('Upload an image (300x300px)','KleeiaDev'); ?>" type="file" name="avatar" style="display:inline-block!important" class="filestyle avatar" data-icon="false" data-input="false"/>
                    <input id="pid" type="hidden" name="pid" value="<?php echo $pid ?>"/>
                    <input id="uid" type="hidden" name="uid" value="<?php echo $uid ?>"/>
                </p>
            </form>
            <p class="top-20">
                <button id="upload-avatar" type="button" class="submit_light full_width"><?php _e('Update Cover image','KleeiaDev') ?></button>
            </p>
        </div>
   </div>
</div>

I call this modal with <?php do_action('change_avatar', $myuid ); ?> in my page and I send the infos through AJAX, enqueuing the action like this (functions.php)

add_action('wp_ajax_update_avatar_function', 'update_avatar_function', 10, 2 );
function update_avatar_function(){
    $pid = $_POST['pid'];
    $uid = $_POST['uid'];
    $avatar = $_POST['avatar'];

    //perform update user meta and other stuff

    //send me back uid and pid to check if they're correct
    $response = array('uid'=>$uid,'pid'=>$pid);
    echo json_encode($response);
    die();
}

add_action( 'wp_enqueue_scripts', 'add_frontend_ajax_javascript_file', 10, 2 );
function add_frontend_ajax_javascript_file()
{
   wp_localize_script( 'ajax-script', 'ajaxobject', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
}

At the latest I use this jQuery/AJAX:

var updatebuttonav = $('#upload-avatar');
updatebuttonav.on('click', function() {
    event.preventDefault();
    update_avatar();
});
function update_avatar()
{
    var form_data = new FormData($('form#change-avatar')[0]);
    form_data.append('pid', $('#pid').val()), //no sending value
    form_data.append('uid', $('#uid').val()), //no sending value
    form_data.append('avatar', $('#input-avatar')[0].files[0]), //no sending file
    form_data.append('action', 'update_avatar_function'),
    console.log(form_data); //here is printing No Properties
    jQuery.ajax({
        method: 'post',
        url : ajaxurl,
        dataType: 'json',
        data: form_data,
        processData: false,
        beforeSend:function(data){
            //other functions
        },
        success:function(data) {
            alert(data.uid + data.pid);  
        },
        error: function(data){
            console.log(data);
        }
    });
    //alert("a");
}

Well, with this I see in my console.log that No Object Properties and values are sent. Furthermore the json response is Nan. I use this method with other section of my website and I can't see why here It's not working. Is that possible that through do_action the form is not seen? Am I missing something? Any suggestion would be more than appreciated!

Note: I'm not using the wp_ajax_nopriv because users I need it when I'm logged of course.

  • Can you try just new FormData() instead of new FormData($('form#change-avatar')[0]), and after processData:false can you add contentType: false,, and for url, instead of ajaxurl can you try ajaxobject.ajaxurl and let me know what response you get? – czerspalace Jul 26 '16 at 19:52
  • @czerspalace woow man! I've forgotten the contentType! That does the trick. I correctly receive my json response now. I kept the ajaxurl and I clear the formData as suggested. Great man, you made my day. Write an answer! Thanks again. – huraji Jul 26 '16 at 20:10
1

You can try to use new FormData() instead of new FormData($('form#change-avatar')[0]). Also, after processData:false you should add contentType: false since jQuery will set it incorrectly otherwise, and for url, instead of ajaxurl you should useajaxobject.ajaxurl, since with wp_localize_script, the second parameter is the javascript object name

  • Another thing, for you the form_data.append('avatar', $('#input-avatar')[0].files[0]) is correct? I mean for sending a file. I'm not sure about that. – huraji Jul 26 '16 at 20:30
0

First, I would make sure the update_avatar() function can read the form data. Maybe the function needs to accept an object? Like the form or even the event...

Second, I think you need to specify in your data an "action". This is the name of the ajax function that processes the data being sent. In other words, the target of the ajax call. In your case, it would be:

action: 'update_avatar_function'

See the Codex for more information.

(You could hard-code sample data to make sure the ajax is working properly, then work on sending the form data.)

  • Thanks for the answer, but it's not just necessary to append the action to formData? – huraji Jul 26 '16 at 19:30
  • In Wordpress, the action is the hook that gets fired. What if you have a thousand ajax functions defined in functions.php? How does ajaxurl know which one to use? I also realized that the data you are appending might need to be explicitly converted to JSON in order to send it thru ajax that way. – scott Jul 26 '16 at 19:39
  • Thanks but once again the action is appended to formData form_data.append('action', 'update_avatar_function'). In fact, as @czerspalace has suggested clearing formData() and adding contentType:false, values are correctly send. I see the json response. Anyway I'll use your precious suggestion for converting to JSON. – huraji Jul 26 '16 at 20:08

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.