PHP Rest Service – Info PHP
This article explains how to create a simple PHP REST service. This simple PHP service has 2 functions. We are going to call these 2 methods using the jQuery Ajax.
This service contains the following three functions:
- GetData
- GetMessage
- PostMessage
GetData
This function will hold all the products in the array. We are going to use this function across various functions.
GetMessage
This function will return all the products in the JSON format that we can later bind it in the HTML using jQuery.
The above method will call our getdata function and convert it to JSON format and return it. To test the API, just call them via a browser.
I have deployed the above file in IIS and created a folder in the “C:inetpubwwwrootphpdemo” and copied the API file.
Call the API service in the browser and check whether you are getting the response as in the following:
PostMessage
This function will return the product based on the product Id. Since it is a POST service, we cannot make an API call directly from the browser. You require some plugins in order to test the POST API services.
Let me show you how to call the PHP API services using jQuery. As I said earlier, the GetMessage function will return all the products.
To show a demo, I have created a button in HTML. Whenever you click on the button, it will call the GetMessage API service using jQuery. Here is the code snippet.
- Calling the PHP API service using the jQuery ajax.
- On successful submission, it will return the JSON data.
- Processing the data using jQuery function and binding it in the table.
In a similar way I have created another Ajax call to make a POST API request. We need to send the data to the PHP service to get the respective data. I’m passing the data in JSON format to the API service.
To show a demo I have created a TextBox with a button. You need to provide the product id on the TextBox and click on the button. Using jQuery I’m retrieving the value from the TextBox and converting it into the JSON and passing the value to the service using Ajax.
Again I’m binding the response data in the table.
I have added the source code with this article. I’m a .Net developer. One of my projects required making PHP API calls. I was looking for some resources on the internet. Based on my learning I have created this. I hope it will help beginners.
Article Prepared by Ollala Corp