Does jQuery/Ajax send cookies when using the rest API or do I need to somehow add them?

No, you are not passing cookies with jQuery AJAX calls .. certainly not via Cross-domain access.

If you’re going to use jQuery to pass data, you need to pass the current user ID and use get_userdata($userid) to determine whether the user has the correct capabilities.

Server side:

$jQuery_user = get_userdata($_POST['user_id']);
if(!user_can($jQuery_user,'publish_posts')){
   return array('reply'=>0,'error'=>'Forbidden','code'=>'403');
}

Client side:

// Be sure your form can somehow provide the currently logged in user id, hidden or otherwise.
var idata = {};
idata['url']    = form.find('#attachment').val();
idata['nOnce']  = form.find('#nOnce').val();
// if you have a nonce, you should be able to get user_id
iData['user_id'] = jQuery('#user_id').val(); 
// snip (etc.)
jQuery.ajax({
    type: "POST",
    url: vars.path+'/post',
    data: JSON.stringify(idata),
    contentType: "application/json; charset=utf-8",
    crossDomain: true,
    dataType: "json",
    success: function (data, status, jqXHR) {
        // snip
    },

    error: function (jqXHR, status) {
        // snip
    }
});

Leave a Comment