WP REST API jQuery Ajax Basic Authentication

By | May 27, 2017

WP REST API V2 Basic Authentication jQuery Ajax.

In the previous posts I’ve written about wp rest api authentication with php cURL and file_get_contents methods. Now in this post we will try to make a basic authentication wp json api call with jQuery AJAX. In this tutorial I will use users endpoint to get current user data.

<!DOCTYPE html>
<html lang="en">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<head>
<meta charset="utf-8" />
<title>WP Rest API Basic Authentication With jQuery  Ajax</title>
</head>
<body>
<script>
jQuery.ajax({
    url: 'http://youwebsite/wpj-son/wp/v2/users/me',
    method: 'GET',
    crossDomain: true,
    beforeSend: function ( xhr ) {
    xhr.setRequestHeader( 'Authorization', 'Basic ' + btoa("username:password") );
    },
    success: function( data, txtStatus, xhr ) {
        //console.log( data );     
        document.getElementById("response").innerHTML = JSON.stringify(data,  null, 2);
    },
    error: function (error) {
      document.getElementById("response").innerHTML = "Error";
    }
});
</script>
<p>View response</p>
<pre id="response"></pre>
</body>
</html>

Don’t forget that you aso need to install and activate Basic Auth Plugin.

 

Related Posts

WP REST API V2 Auth

WP REST API Edit Post PHP cURL

Wordpess Tutorial WP REST API V2 Update Post by post id with PHP cURL

wp rest api v2

Disable WP Rest API V2

Disable Wordpres WP JSON – WP Rest API V2 with and without plugin

wp rest api v2

WP REST API Get Post By Slug With PHP

WordPress WP REST API Tutorial Get Post Data By Slug With PHP

WP REST API V2 Auth

WP REST API Delete Post PHP File Get Contents

WordPress WP REST API Delete Post Tutorial With PHP File Get Contents Function

wp rest api v2

WP REST API Get Media Detail By ID

WordPress WP REST API V2 get media attachment by id with php curl tutorial and code example