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?