0

What I'm doing:

Publishing a post that has some of it's fields checked via AJAX.

The problem:

The images posted are not being saved. All the rest of the infos are. The image is not uploaded to the server.

What I tried:

I tried using $_POST, and it was working like that, before I had to check stuff with AJAX, and had to use .preventDefault() and .submit(). Since I had to use AJAX, tried a bunch of stuff, including the fileReader().

What's being done in the code:

When the user clicks on the 'submit', I get the fields that have to be checked via JS, pass them with AJAX to PHP, if everything is ok, I return them to the JS and activate the .submit() with the form ID.

The part of the code that has the 'input=file':

<input class="text-input file-input img_destaque" name="img_destaque" type="file" id="img_destaque" multiple="false" />
<input type="submit" class="btn-pub-ad cadastro-anuncio" id="publicar" name="publicar" value="PUBLICAR">
<?php wp_nonce_field( 'publicar','nonce_anuncio' ); ?>

The part of the code that has the submit button:

<input type="submit" class="btn-pub-ad cadastro-anuncio" id="publicar" name="publicar" value="PUBLICAR">

The part of the code that handles the info and sends via AJAX, using the formData() as sugested in the answers:

function adAnuncio(e){
    e.preventDefault();
    var form = document.getElementById('criar_anuncio');
    var formData = new FormData(form);
    formData.append( 'action', 'publicar_anuncio' );
    $.ajax({
        type: "POST",
        url: clocal.ajaxurl,
        dataType: "html",
        processData: false,
        contentType: false,
        data: formData,
        }).success(function (data) {
            $data = $(data);
            $("#mensagem").html($data);
            var anchor = $('#mensagem');
            $('html,body').animate({scrollTop: anchor.offset().top},'slow');
            if ($('.linha-sucesso').length){
                $('#criar_anuncio').submit();
            }
        });
}

The part of the code that gets what was sent via AJAX and includes the PHP that has the code to create the post:

// if user is logged in
add_action('wp_ajax_publicar_anuncio', 'publish_anuncio');
// if user is not logged in
add_action('wp_ajax_nopriv_publicar_anuncio', 'publish_anuncio');
function publish_anuncio() {
if ( count( $errors->get_error_messages() ) < 1 ) :
    echo '<div class="linha-sucesso">';
    echo '<img class="ico-sucesso" src="'. get_template_directory_uri() .'/assets/images/success-icon.png">';
    echo 'Seu anúncio foi cadastrado correctamente.';
    echo '</div>';
    include 'inc/inserir-anuncios-verificacao.php';
endif;
wp_die();

The part where the file should be handled, stored and attached to the post:

$post_type = 'cadastro_anuncios';
//the array of arguements to be inserted with wp_insert_post
$postStatus = 'publish';
$new_post = array(
    'post_title'    => $title,
    'post_status'   => $postStatus, 
    'post_type'     => $post_type,
);
//treating the images
// These files need to be included as dependencies when on the front end.
require_once( ABSPATH . 'wp-admin/includes/image.php' );
require_once( ABSPATH . 'wp-admin/includes/file.php' );
require_once( ABSPATH . 'wp-admin/includes/media.php' );
$img_id01 = media_handle_upload( $_POST['img_destaque'], $postID );
update_post_meta($postID, 'img_id01', $img_id01);

It doesnt work. Even if I remove the .submit(), no error is printed or showed on the console. If I keep the .submit() everything gets saved properly except for the images.

  • is the new post correctly created ? – mmm Jan 18 '18 at 12:44
  • @mmm Yes, everything works fine. The new post is created, every other field gets saved. Only the image is not working. – Marcelo Henriques Cortez Jan 18 '18 at 12:44
  • 1
    I created a simple plugin which creates a post and uploads a file via ajax. You can find the code at github.com/ReneLuecking/formdatatest To test it, download it as zip, extract the folder into your plugin directory, activate a plugin and create an new page which contains the shortcode [formular]. Now you find a form on that page, where you can create the post – ahendwh2 Jan 19 '18 at 12:14
  • Wow, that's awesome. Thnx for the help. Or test it and see what I can do. Thnx a lot. – Marcelo Henriques Cortez Jan 19 '18 at 12:17
1

You have to use the javascript FormData object to upload files via ajax. A simple tutorial is provided here. In PHP the file will be available via the globals $_FILES and $_POST.


Additional to the tutorial the WordPress specific data "action" (and maybe "nonce") have to be added to the formData object:

formData.append('action', 'add_your_action_here');
// if necessary
formData.append('nonce', 'add_your_nonce_here');
  • Couldn't make it work. Is that code suposed to work with WordPress? – Marcelo Henriques Cortez Jan 18 '18 at 14:12
  • Yeah except of the part with xhr. For this you should use $.ajax (like you already did in your code) with type = "POST", url = ajaxurl and data = formData – ahendwh2 Jan 18 '18 at 14:32
  • Can you check the code I updated? Tried a few ways... None worked. – Marcelo Henriques Cortez Jan 18 '18 at 14:52
  • In document.getElementById('the-file'); you have to replace "the-file" with the id of your file input – ahendwh2 Jan 18 '18 at 15:06
  • Ops, my bad. The code still don't work. Everything is saved and published. But no images in the library, nor attached to the post. – Marcelo Henriques Cortez Jan 18 '18 at 15:11

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.