1

I have a simple file upload ajax request towards admin-ajax.php.

var data = new FormData();
jQuery.each(jQuery('input[data-field=file]')[0].files, function(i, file) {
    data.append('file-'+i, file);
});

$.ajax({
    url : '/wp-admin/admin-ajax.php',
    data: data,
    cache: false,
    contentType: false,
    processData: false,
    method: 'POST',
    success: function(data){
        console.log(data);
    },
    error: function() {
        console.log("Error");
    }
});

e.preventDefault();

Now, if I send the ajax request anywhere else than admin-ajax.php (e. g. /test.php), the data is passed normally.

The problem is, that admin-ajax.php will always return 0 because it has the following lines:

if ( empty( $_REQUEST['action'] ) )
    wp_die( '0', 400 );

If I try to pass the data like this (with processData: false):

data: {
    action: 'cas_contact_form',
    data: data,
},

admin-ajax.php still dies with a 0.

If I remove processData: false, I will get an Uncaught TypeError: Illegal invocation error, and I won't be able even to send the data to admin-ajax.php.

So far, it seems like a catch22 problem to me. Am I missing something?

2
  • 1
    Well you moved the rest of the data “down one level” now, by introducing another data key inside the data object. But the receiving end likely expects the data fields and the action key on the same level. Do data.append('action', 'cas_contact_form'); instead after you added the input fields to data, that should work. Commented Jan 16, 2018 at 8:03
  • Ok, added it as an answer. Commented Jan 16, 2018 at 8:16

1 Answer 1

1

If I try to pass the data like this (with processData: false):

data: {
    action: 'cas_contact_form',
    data: data, }, admin-ajax.php still dies with a 0.

Well you moved the rest of the data “down one level” now, by introducing another data key inside the data object. But the receiving end likely expects the data fields and the action key on the same level.

But you can append this additional parameter to the FormData object the same way you already added the input fields:

data.append('action', 'cas_contact_form');

https://developer.mozilla.org/en-US/docs/Web/API/FormData/append

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.