0

I have a form that is handled via $.post, sending data to a php script. My client just asked me to include the ability to upload an image using this (and a few other) forms.

I have been googling around on this for about an hour, and haven't seen any evidence that you can actually do this using $.post(), so I wanted to reach out and see if there is a way to do this.

the form is handled this way:

jQuery( '.js-saveProduct' ).click(function(e) {
    e.preventDefault();
    acSaveProduct( jQuery(this).serializeArray() )
};

var acSaveProduct = function( form ) {
    var _data = {
        action: 'ac_save_product',
        form: JSON.stringify( form )
    }

    jQuery.post(
        ajaxscript.ajaxurl,
        _data,
        function( response ) {
            // Do Stuff
        }
    );
};

If I console.log(form) after acSaveProduct() is called, the upload fields aren't even in the array of objects that gets logged.

I haven't even started on the PHP side of this, as I know that the form object that gets passed to my PHP function doesn't contain the values I am looking for.

EDIT TO SHOW NEW ATTEMPT

So, trying the technique linked by @Andreas, I'm still having trouble with this. Below is my update jQuery / PHP code:

HTML

<input type="file" name="acImageNew" id="acImageNew">

jQuery

var acSaveProductAlt = function( form ) {
    var file_data = jQuery( '#acImageNew' ).prop('files')[0];
    var form_data = new FormData();
    form_data.append('file', file_data);

    alert(form_data);

    jQuery.ajax({
        url: the_ajax_script.ajaxurl,
        dataType: 'json',
        cache: false,
        contentType: false,
        processData: false,
        data: form_data,
        type: 'post',
        action: 'ac_ajax_save_product_alt',
        success: function( response ) {
            alert(JSON.parse(response.success));
        }
    });
};

PHP

function ac_ajax_save_product_alt(){
    if ( 0 < $_FILES['file']['error'] ) {
        echo 'Error: ' . $_FILES['file']['error'] . '<br>';
    }
    else {
        move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);
    }

    $response = json_encode(
        array(
            'success' => true,
        )
    );

    header( "Content-Type: application/json" );
    echo $response;
    exit;
}

At the end of it all, I get an alert with 0 as the contents of the alert. What am I doing wrong?

idealbrandon
  • 325
  • 4
  • 14
  • 2
    Possible duplicate of [jquery ajax File Upload php](http://stackoverflow.com/questions/23980733/jquery-ajax-file-upload-php) – Andreas Nov 16 '15 at 22:16
  • I'll read that. Will there be a big difference using $.ajax instead of $.post? I'm really trying to not have to refactor all this code – idealbrandon Nov 16 '15 at 22:17
  • `$.post()` is just a shortcut for `$.ajax({url: ..., method: "post", ...})`: [source on github](https://github.com/jquery/jquery/blob/c9935b6d2db9e1be4bed12f7419e98cdca45763e/src/ajax.js#L827) – Andreas Nov 16 '15 at 22:24
  • @idealbrandon there isn't, `$.post` calls `$.ajax` with a few extra data members, you may just need to add those things in, but they use the same methods – iam-decoder Nov 16 '15 at 22:25
  • Thanks for the clarification. I'm still struggling with this, but am reading through the post and links inside it that @Andreas mentioned – idealbrandon Nov 16 '15 at 22:45
  • The change from `$.post()` to `$.ajax` is fairly easy: Extend `_data` with `url: ajaxscript.ajaxurl, method: "post"`, change `jQuery.post(ajaxscript.ajaxurl, _data, function()...)` to `jQuery.ajax(_data).done(function(response) { ... });` and you're done – Andreas Nov 16 '15 at 22:50

1 Answers1

1

Try JSON parsing the response first, then accessing the success key.

jQuery.ajax({
    url: the_ajax_script.ajaxurl,
    dataType: 'json',
    cache: false,
    contentType: false,
    processData: false,
    data: form_data,
    type: 'post',
    action: 'ac_ajax_save_product_alt',
    success: function( response ) {
        alert(JSON.parse(response).success);
    }
});
Sara
  • 8,222
  • 1
  • 37
  • 52