How to create a simple REST API in PHP and call them in JavaScript
In this post, we are going to talk about how we can create a simple REST API in PHP and call them in JavaScript using various technologies. For example, using XMLHttpRequest, jQuery AJAX and AngularJS AJAX. In order to create a simple REST API that might actually be used in practice, we are going to use WordPress API namely the username_exists() function that allow us to check if the username exist in a WordPress database and return true if the username exists or false otherwise. For simplicity, we are going to skip on how to build a WordPress site, and go straight to writing the PHP code for the simple REST API.
An example of a response from this simple REST API is as follows, or you may click the link above. (Notice that the request would have to be POST, you may test it out using Postman)
Now we have a really simple REST API that allows us to check if the username exist or not. This is especially useful in registration form where we allow the user to know if the username exist or not before they submit the form. This can be done using JavaScript. First example that I would like to show is using XMLHttpRequest. Here is a sample code that does the job.
As the user type, they may immediately see if the username is taken or not. An example of taken username is test as mentioned earlier.
Wrapping Up
Hopefully this guide has given you the confidence to do many other things with querying a simple REST API using various technologies like pure JavaScript with XMLHttpRequest or AJAX call via jQuery or AngularJS AJAX. Please go ahead and take a look at the code and add more things to it to make it do more interesting things. I am sure that you will start getting the hang of it while you add those new things. I hope that this post has helped you and good luck to you!
Resources
I’ll try to keep this list current and up to date. If you know of a great resource you’d like to share or notice a broken link, please let us know.
Comments