Php login request with Ajax Programming

85

AJAX can be expanded as  Asynchronous Javascript and XML and it is a method to request a server side script to execute via javascript. This request is generated in a Javascript function and sent to a PHP file. In server side, PHP file it receives and processes the request passed through an AJAX call and send a response. The client-server communication will be done in an asynchronous way. After getting a response from the PHP file, we can update a particular component of a web page and avoid page refresh.

AJAX can be implemented by using various libraries and API. In this tutorial, I am using XMLHTTPRequest API to send an AJAX request for executing PHP login script. After getting the response from the PHP, the AJAX code checks the status and show authentication result in the web page without refreshing it.

Login Form with AJAX Button Handler

The following code shows a  login form with the User Name and the Password fields. On clicking the Login button, it calls a Javascript AJAX function. This function will send the login field values to PHP to process user authentication. It contains a target DIV container where authentication results will be shown to the user by AJAX function without refreshing login page.

Sending Login Request via Javascript AJAX Function

In this Javascript function we create AJAX login request by using XMLHttpRequest instance. Since old browsers are not supporting this API, we can create ActiveXObject. This function sends user’s login details to login.php as the “GET” requests. If the user is authenticated successfully, then this function will show welcome screen. Otherwise, an error message will be shown on top of the login form. All these changes will be made by the AJAX instead of reloading the page.

PHP Login Script with MySQL.

The following PHP code receives AJAX requests and process authentication. It searches user database for the login details passed by the AJAX call. If a match is found, then it will return true as a response.

 

Leave A Reply

Your email address will not be published.