Home > front end >  Wordpress admin-ajax.php 400 bad request error
Wordpress admin-ajax.php 400 bad request error

Time:02-23

i try to send datas from form by using ajax. First, i have a button "add file". When i click on this one, i display form in ajax and it works.

Now, when i submit my form, i have error bad request from admin-ajax.php

Function: (my add_post.php return only echo 'test';

function add_post(){
    global $wpdb;
    include(dirname( __FILE__ ) . '/templates/includes/add_post.php');
    die();
}
add_action( 'wp_ajax_add_post', 'add_post' );

add_action( 'wp_ajax_nopriv_add_post', 'add_post' );

HTML :

<form  name="form" id="addNewPost" method="post" enctype="multipart/form-data">
    <input type="hidden" name="ispost" value="1" />
    <input type="hidden" name="userid" value="" />
    <input type="hidden" name="catid" value="<?php echo $catID; ?>" />

        <label >Nom du fichier</label>
        <input type="text"  name="titre" />


        <label >Image à upload</label>
        <input id="upfile" type="file" name="sample_image"  />

        <input type="submit"  id="testsub" value="Envoyer" name="submitpost" />
</form>

JS FILE :

$("#testsub").on('click', function(e){
    e.preventDefault();
    var formData=new FormData(document.getElementById('addNewPost'));
    formData.append("action", "add_post");           
    $.ajax({
        url: ajaxurl.ajaxurl,
        type: 'POST',
        data: {
            'action': 'add_post',
            'data': formData
        },
        cache: false,
        processData: false, 
        contentType: false,
    }).done(function(response) {
        $('.test').html(response);
    });
});

If i try to send only input value without the file, my ajax works. Could you please help me ?

CodePudding user response:

Remove this line from code:

data: {
    'action': 'add_post',
    'data': formData
},

And use this:

data: formData,
  • Related