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 Basic Authentication With PHP Curl

Wordpress Tutorial WP REST API Basic Authentication With PHP Curl

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 Auth

WP REST API Create Post with jQuery Ajax

Wordpress WP REST API v2 tutorial create post with jquery ajax using basic authentication with code example

wp rest api v2

WP REST API Get Featured Image With Custom Endpoint

WP REST API Get Featured Image By Adding Custom Endpoint in Theme Function

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.