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 Upload Image Media

Wordpress WP REST API V2 tutorial and code example upload image / media with PHP cURL

wp rest api v2

WP REST API Create Category PHP cURL

Wordpress Tutorial WP REST API V2 Create Category With PHP cURL with code example

WP REST API V2 Auth

WP REST API Create Post With PHP cURL

Create post in WP REST API V2 with PHP cURL. Wordpress tutorial creating post with WP REST API / WP-JSON using PHP cURL script.

wp rest api v2

WP REST API Get Posts By Category

WordPress REST API tutorial get posts by category id with php script

wp rest api v2

WP REST API Get Post By Id With PHP

WordPress WP REST API V2 Tutorial get post by post id using php script.