0

I'm using the rest json API plugin http://wp-api.org/ to create a small application.

I'm trying to delete a custom post entry with jquery ajax but something is missing, here is my code:

...
//make the request
        var dataArray = {};
        var urlRequest = WP_API_Settings.root+"/posts/"+postID;
        var typeRequest = 'DELETE';

        //first set the standard stuff
        dataArray["action"] = "wp_api";
        dataArray["_wp_json_nonce"] =  WP_API_Settings.nonce;

        //make the post
        $.ajax(urlRequest,{
            url : urlRequest,
            type : typeRequest,
            data : dataArray,
            cache : false
        }).done(
....

The error I receive is 401 Unathorized with "json_user_cannot_delete_post". I think that the data is not parsed when making a DELETE call, how am I supposed to authenticate? any clue?

thanks

  • 1
    Plugin specific questions are off-topic. The plugin's support forums are a much better place to ask this kind of questions. – Mark Kaplun Sep 26 '14 at 7:57
  • @MarkKaplun wasn't feature plugins on-topic? Or I am missing something? – Sisir Feb 11 '16 at 13:05
  • @Sisir, back then I don't think it was a featured plugin, but it is always possible I was missing something ;) – Mark Kaplun Feb 11 '16 at 13:16
0

You get an 401 because your AJAX isn't authorized to delete Posts. Would be a big Problem, if everyone could send such Kind of AJAX-requests to your WordPress and delete all your Content.

As of the API, your JS code has to be modifyed to something like this:

...
//make the request
    var dataArray = {};
    var urlRequest = WP_API_Settings.root+"/posts/"+postID;
    var typeRequest = 'DELETE';

    //first set the standard stuff
    dataArray["action"] = "wp_api";
    //dataArray["_wp_json_nonce"] =  WP_API_Settings.nonce;

    //make the post
    $.ajax(urlRequest,{
        url : urlRequest,
        type : typeRequest,
        data : dataArray,
        cache : false,
        beforeSend: function (xhr) {
            xhr.setRequestHeader('X-WP-Nonce', WP_API_Settings.nonce);

            if (beforeSend) {
                return beforeSend.apply(this, arguments);
            }
        }
    }).done(
....

So now your NONCE is set in the X-WP-Nonce Header instead as an variable in the data.

May that works, I didn't tested it.

  • Thanks, that's what I was missing! It worked, had to remove that if on (beforeSend) though. – Federico Vezzoli Sep 26 '14 at 10:08

Not the answer you're looking for? Browse other questions tagged or ask your own question.